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/ADT/StringExtras.h" 51 #include "llvm/Support/ConvertUTF.h" 52 #include "llvm/Support/SaveAndRestore.h" 53 54 using namespace clang; 55 using namespace sema; 56 using llvm::RoundingMode; 57 58 /// Determine whether the use of this declaration is valid, without 59 /// emitting diagnostics. 60 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 61 // See if this is an auto-typed variable whose initializer we are parsing. 62 if (ParsingInitForAutoVars.count(D)) 63 return false; 64 65 // See if this is a deleted function. 66 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 67 if (FD->isDeleted()) 68 return false; 69 70 // If the function has a deduced return type, and we can't deduce it, 71 // then we can't use it either. 72 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 73 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 74 return false; 75 76 // See if this is an aligned allocation/deallocation function that is 77 // unavailable. 78 if (TreatUnavailableAsInvalid && 79 isUnavailableAlignedAllocationFunction(*FD)) 80 return false; 81 } 82 83 // See if this function is unavailable. 84 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 85 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 86 return false; 87 88 if (isa<UnresolvedUsingIfExistsDecl>(D)) 89 return false; 90 91 return true; 92 } 93 94 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 95 // Warn if this is used but marked unused. 96 if (const auto *A = D->getAttr<UnusedAttr>()) { 97 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 98 // should diagnose them. 99 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 100 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 101 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 102 if (DC && !DC->hasAttr<UnusedAttr>()) 103 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 104 } 105 } 106 } 107 108 /// Emit a note explaining that this function is deleted. 109 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 110 assert(Decl && Decl->isDeleted()); 111 112 if (Decl->isDefaulted()) { 113 // If the method was explicitly defaulted, point at that declaration. 114 if (!Decl->isImplicit()) 115 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 116 117 // Try to diagnose why this special member function was implicitly 118 // deleted. This might fail, if that reason no longer applies. 119 DiagnoseDeletedDefaultedFunction(Decl); 120 return; 121 } 122 123 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 124 if (Ctor && Ctor->isInheritingConstructor()) 125 return NoteDeletedInheritingConstructor(Ctor); 126 127 Diag(Decl->getLocation(), diag::note_availability_specified_here) 128 << Decl << 1; 129 } 130 131 /// Determine whether a FunctionDecl was ever declared with an 132 /// explicit storage class. 133 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 134 for (auto I : D->redecls()) { 135 if (I->getStorageClass() != SC_None) 136 return true; 137 } 138 return false; 139 } 140 141 /// Check whether we're in an extern inline function and referring to a 142 /// variable or function with internal linkage (C11 6.7.4p3). 143 /// 144 /// This is only a warning because we used to silently accept this code, but 145 /// in many cases it will not behave correctly. This is not enabled in C++ mode 146 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 147 /// and so while there may still be user mistakes, most of the time we can't 148 /// prove that there are errors. 149 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 150 const NamedDecl *D, 151 SourceLocation Loc) { 152 // This is disabled under C++; there are too many ways for this to fire in 153 // contexts where the warning is a false positive, or where it is technically 154 // correct but benign. 155 if (S.getLangOpts().CPlusPlus) 156 return; 157 158 // Check if this is an inlined function or method. 159 FunctionDecl *Current = S.getCurFunctionDecl(); 160 if (!Current) 161 return; 162 if (!Current->isInlined()) 163 return; 164 if (!Current->isExternallyVisible()) 165 return; 166 167 // Check if the decl has internal linkage. 168 if (D->getFormalLinkage() != InternalLinkage) 169 return; 170 171 // Downgrade from ExtWarn to Extension if 172 // (1) the supposedly external inline function is in the main file, 173 // and probably won't be included anywhere else. 174 // (2) the thing we're referencing is a pure function. 175 // (3) the thing we're referencing is another inline function. 176 // This last can give us false negatives, but it's better than warning on 177 // wrappers for simple C library functions. 178 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 179 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 180 if (!DowngradeWarning && UsedFn) 181 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 182 183 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 184 : diag::ext_internal_in_extern_inline) 185 << /*IsVar=*/!UsedFn << D; 186 187 S.MaybeSuggestAddingStaticToDecl(Current); 188 189 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 190 << D; 191 } 192 193 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 194 const FunctionDecl *First = Cur->getFirstDecl(); 195 196 // Suggest "static" on the function, if possible. 197 if (!hasAnyExplicitStorageClass(First)) { 198 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 199 Diag(DeclBegin, diag::note_convert_inline_to_static) 200 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 201 } 202 } 203 204 /// Determine whether the use of this declaration is valid, and 205 /// emit any corresponding diagnostics. 206 /// 207 /// This routine diagnoses various problems with referencing 208 /// declarations that can occur when using a declaration. For example, 209 /// it might warn if a deprecated or unavailable declaration is being 210 /// used, or produce an error (and return true) if a C++0x deleted 211 /// function is being used. 212 /// 213 /// \returns true if there was an error (this declaration cannot be 214 /// referenced), false otherwise. 215 /// 216 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 217 const ObjCInterfaceDecl *UnknownObjCClass, 218 bool ObjCPropertyAccess, 219 bool AvoidPartialAvailabilityChecks, 220 ObjCInterfaceDecl *ClassReceiver) { 221 SourceLocation Loc = Locs.front(); 222 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 223 // If there were any diagnostics suppressed by template argument deduction, 224 // emit them now. 225 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 226 if (Pos != SuppressedDiagnostics.end()) { 227 for (const PartialDiagnosticAt &Suppressed : Pos->second) 228 Diag(Suppressed.first, Suppressed.second); 229 230 // Clear out the list of suppressed diagnostics, so that we don't emit 231 // them again for this specialization. However, we don't obsolete this 232 // entry from the table, because we want to avoid ever emitting these 233 // diagnostics again. 234 Pos->second.clear(); 235 } 236 237 // C++ [basic.start.main]p3: 238 // The function 'main' shall not be used within a program. 239 if (cast<FunctionDecl>(D)->isMain()) 240 Diag(Loc, diag::ext_main_used); 241 242 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 243 } 244 245 // See if this is an auto-typed variable whose initializer we are parsing. 246 if (ParsingInitForAutoVars.count(D)) { 247 if (isa<BindingDecl>(D)) { 248 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 249 << D->getDeclName(); 250 } else { 251 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 252 << D->getDeclName() << cast<VarDecl>(D)->getType(); 253 } 254 return true; 255 } 256 257 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 258 // See if this is a deleted function. 259 if (FD->isDeleted()) { 260 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 261 if (Ctor && Ctor->isInheritingConstructor()) 262 Diag(Loc, diag::err_deleted_inherited_ctor_use) 263 << Ctor->getParent() 264 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 265 else 266 Diag(Loc, diag::err_deleted_function_use); 267 NoteDeletedFunction(FD); 268 return true; 269 } 270 271 // [expr.prim.id]p4 272 // A program that refers explicitly or implicitly to a function with a 273 // trailing requires-clause whose constraint-expression is not satisfied, 274 // other than to declare it, is ill-formed. [...] 275 // 276 // See if this is a function with constraints that need to be satisfied. 277 // Check this before deducing the return type, as it might instantiate the 278 // definition. 279 if (FD->getTrailingRequiresClause()) { 280 ConstraintSatisfaction Satisfaction; 281 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 282 // A diagnostic will have already been generated (non-constant 283 // constraint expression, for example) 284 return true; 285 if (!Satisfaction.IsSatisfied) { 286 Diag(Loc, 287 diag::err_reference_to_function_with_unsatisfied_constraints) 288 << D; 289 DiagnoseUnsatisfiedConstraint(Satisfaction); 290 return true; 291 } 292 } 293 294 // If the function has a deduced return type, and we can't deduce it, 295 // then we can't use it either. 296 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 297 DeduceReturnType(FD, Loc)) 298 return true; 299 300 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 301 return true; 302 303 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 304 return true; 305 } 306 307 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 308 // Lambdas are only default-constructible or assignable in C++2a onwards. 309 if (MD->getParent()->isLambda() && 310 ((isa<CXXConstructorDecl>(MD) && 311 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 312 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 313 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 314 << !isa<CXXConstructorDecl>(MD); 315 } 316 } 317 318 auto getReferencedObjCProp = [](const NamedDecl *D) -> 319 const ObjCPropertyDecl * { 320 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 321 return MD->findPropertyDecl(); 322 return nullptr; 323 }; 324 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 325 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 326 return true; 327 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 328 return true; 329 } 330 331 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 332 // Only the variables omp_in and omp_out are allowed in the combiner. 333 // Only the variables omp_priv and omp_orig are allowed in the 334 // initializer-clause. 335 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 336 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 337 isa<VarDecl>(D)) { 338 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 339 << getCurFunction()->HasOMPDeclareReductionCombiner; 340 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 341 return true; 342 } 343 344 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 345 // List-items in map clauses on this construct may only refer to the declared 346 // variable var and entities that could be referenced by a procedure defined 347 // at the same location 348 if (LangOpts.OpenMP && isa<VarDecl>(D) && 349 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 350 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 351 << getOpenMPDeclareMapperVarName(); 352 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 353 return true; 354 } 355 356 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) { 357 Diag(Loc, diag::err_use_of_empty_using_if_exists); 358 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); 359 return true; 360 } 361 362 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 363 AvoidPartialAvailabilityChecks, ClassReceiver); 364 365 DiagnoseUnusedOfDecl(*this, D, Loc); 366 367 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 368 369 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 370 if (auto *VD = dyn_cast<ValueDecl>(D)) 371 checkDeviceDecl(VD, Loc); 372 373 if (!Context.getTargetInfo().isTLSSupported()) 374 if (const auto *VD = dyn_cast<VarDecl>(D)) 375 if (VD->getTLSKind() != VarDecl::TLS_None) 376 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 377 } 378 379 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 380 !isUnevaluatedContext()) { 381 // C++ [expr.prim.req.nested] p3 382 // A local parameter shall only appear as an unevaluated operand 383 // (Clause 8) within the constraint-expression. 384 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 385 << D; 386 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 387 return true; 388 } 389 390 return false; 391 } 392 393 /// DiagnoseSentinelCalls - This routine checks whether a call or 394 /// message-send is to a declaration with the sentinel attribute, and 395 /// if so, it checks that the requirements of the sentinel are 396 /// satisfied. 397 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 398 ArrayRef<Expr *> Args) { 399 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 400 if (!attr) 401 return; 402 403 // The number of formal parameters of the declaration. 404 unsigned numFormalParams; 405 406 // The kind of declaration. This is also an index into a %select in 407 // the diagnostic. 408 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 409 410 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 411 numFormalParams = MD->param_size(); 412 calleeType = CT_Method; 413 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 414 numFormalParams = FD->param_size(); 415 calleeType = CT_Function; 416 } else if (isa<VarDecl>(D)) { 417 QualType type = cast<ValueDecl>(D)->getType(); 418 const FunctionType *fn = nullptr; 419 if (const PointerType *ptr = type->getAs<PointerType>()) { 420 fn = ptr->getPointeeType()->getAs<FunctionType>(); 421 if (!fn) return; 422 calleeType = CT_Function; 423 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 424 fn = ptr->getPointeeType()->castAs<FunctionType>(); 425 calleeType = CT_Block; 426 } else { 427 return; 428 } 429 430 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 431 numFormalParams = proto->getNumParams(); 432 } else { 433 numFormalParams = 0; 434 } 435 } else { 436 return; 437 } 438 439 // "nullPos" is the number of formal parameters at the end which 440 // effectively count as part of the variadic arguments. This is 441 // useful if you would prefer to not have *any* formal parameters, 442 // but the language forces you to have at least one. 443 unsigned nullPos = attr->getNullPos(); 444 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 445 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 446 447 // The number of arguments which should follow the sentinel. 448 unsigned numArgsAfterSentinel = attr->getSentinel(); 449 450 // If there aren't enough arguments for all the formal parameters, 451 // the sentinel, and the args after the sentinel, complain. 452 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 453 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 454 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 455 return; 456 } 457 458 // Otherwise, find the sentinel expression. 459 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 460 if (!sentinelExpr) return; 461 if (sentinelExpr->isValueDependent()) return; 462 if (Context.isSentinelNullExpr(sentinelExpr)) return; 463 464 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 465 // or 'NULL' if those are actually defined in the context. Only use 466 // 'nil' for ObjC methods, where it's much more likely that the 467 // variadic arguments form a list of object pointers. 468 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 469 std::string NullValue; 470 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 471 NullValue = "nil"; 472 else if (getLangOpts().CPlusPlus11) 473 NullValue = "nullptr"; 474 else if (PP.isMacroDefined("NULL")) 475 NullValue = "NULL"; 476 else 477 NullValue = "(void*) 0"; 478 479 if (MissingNilLoc.isInvalid()) 480 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 481 else 482 Diag(MissingNilLoc, diag::warn_missing_sentinel) 483 << int(calleeType) 484 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 485 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 486 } 487 488 SourceRange Sema::getExprRange(Expr *E) const { 489 return E ? E->getSourceRange() : SourceRange(); 490 } 491 492 //===----------------------------------------------------------------------===// 493 // Standard Promotions and Conversions 494 //===----------------------------------------------------------------------===// 495 496 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 497 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 498 // Handle any placeholder expressions which made it here. 499 if (E->getType()->isPlaceholderType()) { 500 ExprResult result = CheckPlaceholderExpr(E); 501 if (result.isInvalid()) return ExprError(); 502 E = result.get(); 503 } 504 505 QualType Ty = E->getType(); 506 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 507 508 if (Ty->isFunctionType()) { 509 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 510 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 511 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 512 return ExprError(); 513 514 E = ImpCastExprToType(E, Context.getPointerType(Ty), 515 CK_FunctionToPointerDecay).get(); 516 } else if (Ty->isArrayType()) { 517 // In C90 mode, arrays only promote to pointers if the array expression is 518 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 519 // type 'array of type' is converted to an expression that has type 'pointer 520 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 521 // that has type 'array of type' ...". The relevant change is "an lvalue" 522 // (C90) to "an expression" (C99). 523 // 524 // C++ 4.2p1: 525 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 526 // T" can be converted to an rvalue of type "pointer to T". 527 // 528 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { 529 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 530 CK_ArrayToPointerDecay); 531 if (Res.isInvalid()) 532 return ExprError(); 533 E = Res.get(); 534 } 535 } 536 return E; 537 } 538 539 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 540 // Check to see if we are dereferencing a null pointer. If so, 541 // and if not volatile-qualified, this is undefined behavior that the 542 // optimizer will delete, so warn about it. People sometimes try to use this 543 // to get a deterministic trap and are surprised by clang's behavior. This 544 // only handles the pattern "*null", which is a very syntactic check. 545 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 546 if (UO && UO->getOpcode() == UO_Deref && 547 UO->getSubExpr()->getType()->isPointerType()) { 548 const LangAS AS = 549 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 550 if ((!isTargetAddressSpace(AS) || 551 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 552 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 553 S.Context, Expr::NPC_ValueDependentIsNotNull) && 554 !UO->getType().isVolatileQualified()) { 555 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 556 S.PDiag(diag::warn_indirection_through_null) 557 << UO->getSubExpr()->getSourceRange()); 558 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 559 S.PDiag(diag::note_indirection_through_null)); 560 } 561 } 562 } 563 564 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 565 SourceLocation AssignLoc, 566 const Expr* RHS) { 567 const ObjCIvarDecl *IV = OIRE->getDecl(); 568 if (!IV) 569 return; 570 571 DeclarationName MemberName = IV->getDeclName(); 572 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 573 if (!Member || !Member->isStr("isa")) 574 return; 575 576 const Expr *Base = OIRE->getBase(); 577 QualType BaseType = Base->getType(); 578 if (OIRE->isArrow()) 579 BaseType = BaseType->getPointeeType(); 580 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 581 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 582 ObjCInterfaceDecl *ClassDeclared = nullptr; 583 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 584 if (!ClassDeclared->getSuperClass() 585 && (*ClassDeclared->ivar_begin()) == IV) { 586 if (RHS) { 587 NamedDecl *ObjectSetClass = 588 S.LookupSingleName(S.TUScope, 589 &S.Context.Idents.get("object_setClass"), 590 SourceLocation(), S.LookupOrdinaryName); 591 if (ObjectSetClass) { 592 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 593 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 594 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 595 "object_setClass(") 596 << FixItHint::CreateReplacement( 597 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 598 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 599 } 600 else 601 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 602 } else { 603 NamedDecl *ObjectGetClass = 604 S.LookupSingleName(S.TUScope, 605 &S.Context.Idents.get("object_getClass"), 606 SourceLocation(), S.LookupOrdinaryName); 607 if (ObjectGetClass) 608 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 609 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 610 "object_getClass(") 611 << FixItHint::CreateReplacement( 612 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 613 else 614 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 615 } 616 S.Diag(IV->getLocation(), diag::note_ivar_decl); 617 } 618 } 619 } 620 621 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 622 // Handle any placeholder expressions which made it here. 623 if (E->getType()->isPlaceholderType()) { 624 ExprResult result = CheckPlaceholderExpr(E); 625 if (result.isInvalid()) return ExprError(); 626 E = result.get(); 627 } 628 629 // C++ [conv.lval]p1: 630 // A glvalue of a non-function, non-array type T can be 631 // converted to a prvalue. 632 if (!E->isGLValue()) return E; 633 634 QualType T = E->getType(); 635 assert(!T.isNull() && "r-value conversion on typeless expression?"); 636 637 // lvalue-to-rvalue conversion cannot be applied to function or array types. 638 if (T->isFunctionType() || T->isArrayType()) 639 return E; 640 641 // We don't want to throw lvalue-to-rvalue casts on top of 642 // expressions of certain types in C++. 643 if (getLangOpts().CPlusPlus && 644 (E->getType() == Context.OverloadTy || 645 T->isDependentType() || 646 T->isRecordType())) 647 return E; 648 649 // The C standard is actually really unclear on this point, and 650 // DR106 tells us what the result should be but not why. It's 651 // generally best to say that void types just doesn't undergo 652 // lvalue-to-rvalue at all. Note that expressions of unqualified 653 // 'void' type are never l-values, but qualified void can be. 654 if (T->isVoidType()) 655 return E; 656 657 // OpenCL usually rejects direct accesses to values of 'half' type. 658 if (getLangOpts().OpenCL && 659 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 660 T->isHalfType()) { 661 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 662 << 0 << T; 663 return ExprError(); 664 } 665 666 CheckForNullPointerDereference(*this, E); 667 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 668 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 669 &Context.Idents.get("object_getClass"), 670 SourceLocation(), LookupOrdinaryName); 671 if (ObjectGetClass) 672 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 673 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 674 << FixItHint::CreateReplacement( 675 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 676 else 677 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 678 } 679 else if (const ObjCIvarRefExpr *OIRE = 680 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 681 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 682 683 // C++ [conv.lval]p1: 684 // [...] If T is a non-class type, the type of the prvalue is the 685 // cv-unqualified version of T. Otherwise, the type of the 686 // rvalue is T. 687 // 688 // C99 6.3.2.1p2: 689 // If the lvalue has qualified type, the value has the unqualified 690 // version of the type of the lvalue; otherwise, the value has the 691 // type of the lvalue. 692 if (T.hasQualifiers()) 693 T = T.getUnqualifiedType(); 694 695 // Under the MS ABI, lock down the inheritance model now. 696 if (T->isMemberPointerType() && 697 Context.getTargetInfo().getCXXABI().isMicrosoft()) 698 (void)isCompleteType(E->getExprLoc(), T); 699 700 ExprResult Res = CheckLValueToRValueConversionOperand(E); 701 if (Res.isInvalid()) 702 return Res; 703 E = Res.get(); 704 705 // Loading a __weak object implicitly retains the value, so we need a cleanup to 706 // balance that. 707 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 708 Cleanup.setExprNeedsCleanups(true); 709 710 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 711 Cleanup.setExprNeedsCleanups(true); 712 713 // C++ [conv.lval]p3: 714 // If T is cv std::nullptr_t, the result is a null pointer constant. 715 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 716 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, 717 CurFPFeatureOverrides()); 718 719 // C11 6.3.2.1p2: 720 // ... if the lvalue has atomic type, the value has the non-atomic version 721 // of the type of the lvalue ... 722 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 723 T = Atomic->getValueType().getUnqualifiedType(); 724 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 725 nullptr, VK_PRValue, FPOptionsOverride()); 726 } 727 728 return Res; 729 } 730 731 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 732 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 733 if (Res.isInvalid()) 734 return ExprError(); 735 Res = DefaultLvalueConversion(Res.get()); 736 if (Res.isInvalid()) 737 return ExprError(); 738 return Res; 739 } 740 741 /// CallExprUnaryConversions - a special case of an unary conversion 742 /// performed on a function designator of a call expression. 743 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 744 QualType Ty = E->getType(); 745 ExprResult Res = E; 746 // Only do implicit cast for a function type, but not for a pointer 747 // to function type. 748 if (Ty->isFunctionType()) { 749 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 750 CK_FunctionToPointerDecay); 751 if (Res.isInvalid()) 752 return ExprError(); 753 } 754 Res = DefaultLvalueConversion(Res.get()); 755 if (Res.isInvalid()) 756 return ExprError(); 757 return Res.get(); 758 } 759 760 /// UsualUnaryConversions - Performs various conversions that are common to most 761 /// operators (C99 6.3). The conversions of array and function types are 762 /// sometimes suppressed. For example, the array->pointer conversion doesn't 763 /// apply if the array is an argument to the sizeof or address (&) operators. 764 /// In these instances, this routine should *not* be called. 765 ExprResult Sema::UsualUnaryConversions(Expr *E) { 766 // First, convert to an r-value. 767 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 768 if (Res.isInvalid()) 769 return ExprError(); 770 E = Res.get(); 771 772 QualType Ty = E->getType(); 773 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 774 775 // Half FP have to be promoted to float unless it is natively supported 776 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 777 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 778 779 // Try to perform integral promotions if the object has a theoretically 780 // promotable type. 781 if (Ty->isIntegralOrUnscopedEnumerationType()) { 782 // C99 6.3.1.1p2: 783 // 784 // The following may be used in an expression wherever an int or 785 // unsigned int may be used: 786 // - an object or expression with an integer type whose integer 787 // conversion rank is less than or equal to the rank of int 788 // and unsigned int. 789 // - A bit-field of type _Bool, int, signed int, or unsigned int. 790 // 791 // If an int can represent all values of the original type, the 792 // value is converted to an int; otherwise, it is converted to an 793 // unsigned int. These are called the integer promotions. All 794 // other types are unchanged by the integer promotions. 795 796 QualType PTy = Context.isPromotableBitField(E); 797 if (!PTy.isNull()) { 798 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 799 return E; 800 } 801 if (Ty->isPromotableIntegerType()) { 802 QualType PT = Context.getPromotedIntegerType(Ty); 803 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 804 return E; 805 } 806 } 807 return E; 808 } 809 810 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 811 /// do not have a prototype. Arguments that have type float or __fp16 812 /// are promoted to double. All other argument types are converted by 813 /// UsualUnaryConversions(). 814 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 815 QualType Ty = E->getType(); 816 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 817 818 ExprResult Res = UsualUnaryConversions(E); 819 if (Res.isInvalid()) 820 return ExprError(); 821 E = Res.get(); 822 823 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 824 // promote to double. 825 // Note that default argument promotion applies only to float (and 826 // half/fp16); it does not apply to _Float16. 827 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 828 if (BTy && (BTy->getKind() == BuiltinType::Half || 829 BTy->getKind() == BuiltinType::Float)) { 830 if (getLangOpts().OpenCL && 831 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 832 if (BTy->getKind() == BuiltinType::Half) { 833 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 834 } 835 } else { 836 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 837 } 838 } 839 if (BTy && 840 getLangOpts().getExtendIntArgs() == 841 LangOptions::ExtendArgsKind::ExtendTo64 && 842 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && 843 Context.getTypeSizeInChars(BTy) < 844 Context.getTypeSizeInChars(Context.LongLongTy)) { 845 E = (Ty->isUnsignedIntegerType()) 846 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) 847 .get() 848 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); 849 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && 850 "Unexpected typesize for LongLongTy"); 851 } 852 853 // C++ performs lvalue-to-rvalue conversion as a default argument 854 // promotion, even on class types, but note: 855 // C++11 [conv.lval]p2: 856 // When an lvalue-to-rvalue conversion occurs in an unevaluated 857 // operand or a subexpression thereof the value contained in the 858 // referenced object is not accessed. Otherwise, if the glvalue 859 // has a class type, the conversion copy-initializes a temporary 860 // of type T from the glvalue and the result of the conversion 861 // is a prvalue for the temporary. 862 // FIXME: add some way to gate this entire thing for correctness in 863 // potentially potentially evaluated contexts. 864 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 865 ExprResult Temp = PerformCopyInitialization( 866 InitializedEntity::InitializeTemporary(E->getType()), 867 E->getExprLoc(), E); 868 if (Temp.isInvalid()) 869 return ExprError(); 870 E = Temp.get(); 871 } 872 873 return E; 874 } 875 876 /// Determine the degree of POD-ness for an expression. 877 /// Incomplete types are considered POD, since this check can be performed 878 /// when we're in an unevaluated context. 879 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 880 if (Ty->isIncompleteType()) { 881 // C++11 [expr.call]p7: 882 // After these conversions, if the argument does not have arithmetic, 883 // enumeration, pointer, pointer to member, or class type, the program 884 // is ill-formed. 885 // 886 // Since we've already performed array-to-pointer and function-to-pointer 887 // decay, the only such type in C++ is cv void. This also handles 888 // initializer lists as variadic arguments. 889 if (Ty->isVoidType()) 890 return VAK_Invalid; 891 892 if (Ty->isObjCObjectType()) 893 return VAK_Invalid; 894 return VAK_Valid; 895 } 896 897 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 898 return VAK_Invalid; 899 900 if (Ty.isCXX98PODType(Context)) 901 return VAK_Valid; 902 903 // C++11 [expr.call]p7: 904 // Passing a potentially-evaluated argument of class type (Clause 9) 905 // having a non-trivial copy constructor, a non-trivial move constructor, 906 // or a non-trivial destructor, with no corresponding parameter, 907 // is conditionally-supported with implementation-defined semantics. 908 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 909 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 910 if (!Record->hasNonTrivialCopyConstructor() && 911 !Record->hasNonTrivialMoveConstructor() && 912 !Record->hasNonTrivialDestructor()) 913 return VAK_ValidInCXX11; 914 915 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 916 return VAK_Valid; 917 918 if (Ty->isObjCObjectType()) 919 return VAK_Invalid; 920 921 if (getLangOpts().MSVCCompat) 922 return VAK_MSVCUndefined; 923 924 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 925 // permitted to reject them. We should consider doing so. 926 return VAK_Undefined; 927 } 928 929 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 930 // Don't allow one to pass an Objective-C interface to a vararg. 931 const QualType &Ty = E->getType(); 932 VarArgKind VAK = isValidVarArgType(Ty); 933 934 // Complain about passing non-POD types through varargs. 935 switch (VAK) { 936 case VAK_ValidInCXX11: 937 DiagRuntimeBehavior( 938 E->getBeginLoc(), nullptr, 939 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 940 LLVM_FALLTHROUGH; 941 case VAK_Valid: 942 if (Ty->isRecordType()) { 943 // This is unlikely to be what the user intended. If the class has a 944 // 'c_str' member function, the user probably meant to call that. 945 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 946 PDiag(diag::warn_pass_class_arg_to_vararg) 947 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 948 } 949 break; 950 951 case VAK_Undefined: 952 case VAK_MSVCUndefined: 953 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 954 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 955 << getLangOpts().CPlusPlus11 << Ty << CT); 956 break; 957 958 case VAK_Invalid: 959 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 960 Diag(E->getBeginLoc(), 961 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 962 << Ty << CT; 963 else if (Ty->isObjCObjectType()) 964 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 965 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 966 << Ty << CT); 967 else 968 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 969 << isa<InitListExpr>(E) << Ty << CT; 970 break; 971 } 972 } 973 974 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 975 /// will create a trap if the resulting type is not a POD type. 976 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 977 FunctionDecl *FDecl) { 978 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 979 // Strip the unbridged-cast placeholder expression off, if applicable. 980 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 981 (CT == VariadicMethod || 982 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 983 E = stripARCUnbridgedCast(E); 984 985 // Otherwise, do normal placeholder checking. 986 } else { 987 ExprResult ExprRes = CheckPlaceholderExpr(E); 988 if (ExprRes.isInvalid()) 989 return ExprError(); 990 E = ExprRes.get(); 991 } 992 } 993 994 ExprResult ExprRes = DefaultArgumentPromotion(E); 995 if (ExprRes.isInvalid()) 996 return ExprError(); 997 998 // Copy blocks to the heap. 999 if (ExprRes.get()->getType()->isBlockPointerType()) 1000 maybeExtendBlockObject(ExprRes); 1001 1002 E = ExprRes.get(); 1003 1004 // Diagnostics regarding non-POD argument types are 1005 // emitted along with format string checking in Sema::CheckFunctionCall(). 1006 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 1007 // Turn this into a trap. 1008 CXXScopeSpec SS; 1009 SourceLocation TemplateKWLoc; 1010 UnqualifiedId Name; 1011 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1012 E->getBeginLoc()); 1013 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1014 /*HasTrailingLParen=*/true, 1015 /*IsAddressOfOperand=*/false); 1016 if (TrapFn.isInvalid()) 1017 return ExprError(); 1018 1019 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1020 None, E->getEndLoc()); 1021 if (Call.isInvalid()) 1022 return ExprError(); 1023 1024 ExprResult Comma = 1025 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1026 if (Comma.isInvalid()) 1027 return ExprError(); 1028 return Comma.get(); 1029 } 1030 1031 if (!getLangOpts().CPlusPlus && 1032 RequireCompleteType(E->getExprLoc(), E->getType(), 1033 diag::err_call_incomplete_argument)) 1034 return ExprError(); 1035 1036 return E; 1037 } 1038 1039 /// Converts an integer to complex float type. Helper function of 1040 /// UsualArithmeticConversions() 1041 /// 1042 /// \return false if the integer expression is an integer type and is 1043 /// successfully converted to the complex type. 1044 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1045 ExprResult &ComplexExpr, 1046 QualType IntTy, 1047 QualType ComplexTy, 1048 bool SkipCast) { 1049 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1050 if (SkipCast) return false; 1051 if (IntTy->isIntegerType()) { 1052 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1053 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1054 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1055 CK_FloatingRealToComplex); 1056 } else { 1057 assert(IntTy->isComplexIntegerType()); 1058 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1059 CK_IntegralComplexToFloatingComplex); 1060 } 1061 return false; 1062 } 1063 1064 /// Handle arithmetic conversion with complex types. Helper function of 1065 /// UsualArithmeticConversions() 1066 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1067 ExprResult &RHS, QualType LHSType, 1068 QualType RHSType, 1069 bool IsCompAssign) { 1070 // if we have an integer operand, the result is the complex type. 1071 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1072 /*skipCast*/false)) 1073 return LHSType; 1074 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1075 /*skipCast*/IsCompAssign)) 1076 return RHSType; 1077 1078 // This handles complex/complex, complex/float, or float/complex. 1079 // When both operands are complex, the shorter operand is converted to the 1080 // type of the longer, and that is the type of the result. This corresponds 1081 // to what is done when combining two real floating-point operands. 1082 // The fun begins when size promotion occur across type domains. 1083 // From H&S 6.3.4: When one operand is complex and the other is a real 1084 // floating-point type, the less precise type is converted, within it's 1085 // real or complex domain, to the precision of the other type. For example, 1086 // when combining a "long double" with a "double _Complex", the 1087 // "double _Complex" is promoted to "long double _Complex". 1088 1089 // Compute the rank of the two types, regardless of whether they are complex. 1090 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1091 1092 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1093 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1094 QualType LHSElementType = 1095 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1096 QualType RHSElementType = 1097 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1098 1099 QualType ResultType = S.Context.getComplexType(LHSElementType); 1100 if (Order < 0) { 1101 // Promote the precision of the LHS if not an assignment. 1102 ResultType = S.Context.getComplexType(RHSElementType); 1103 if (!IsCompAssign) { 1104 if (LHSComplexType) 1105 LHS = 1106 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1107 else 1108 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1109 } 1110 } else if (Order > 0) { 1111 // Promote the precision of the RHS. 1112 if (RHSComplexType) 1113 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1114 else 1115 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1116 } 1117 return ResultType; 1118 } 1119 1120 /// Handle arithmetic conversion from integer to float. Helper function 1121 /// of UsualArithmeticConversions() 1122 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1123 ExprResult &IntExpr, 1124 QualType FloatTy, QualType IntTy, 1125 bool ConvertFloat, bool ConvertInt) { 1126 if (IntTy->isIntegerType()) { 1127 if (ConvertInt) 1128 // Convert intExpr to the lhs floating point type. 1129 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1130 CK_IntegralToFloating); 1131 return FloatTy; 1132 } 1133 1134 // Convert both sides to the appropriate complex float. 1135 assert(IntTy->isComplexIntegerType()); 1136 QualType result = S.Context.getComplexType(FloatTy); 1137 1138 // _Complex int -> _Complex float 1139 if (ConvertInt) 1140 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1141 CK_IntegralComplexToFloatingComplex); 1142 1143 // float -> _Complex float 1144 if (ConvertFloat) 1145 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1146 CK_FloatingRealToComplex); 1147 1148 return result; 1149 } 1150 1151 /// Handle arithmethic conversion with floating point types. Helper 1152 /// function of UsualArithmeticConversions() 1153 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1154 ExprResult &RHS, QualType LHSType, 1155 QualType RHSType, bool IsCompAssign) { 1156 bool LHSFloat = LHSType->isRealFloatingType(); 1157 bool RHSFloat = RHSType->isRealFloatingType(); 1158 1159 // N1169 4.1.4: If one of the operands has a floating type and the other 1160 // operand has a fixed-point type, the fixed-point operand 1161 // is converted to the floating type [...] 1162 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1163 if (LHSFloat) 1164 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1165 else if (!IsCompAssign) 1166 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1167 return LHSFloat ? LHSType : RHSType; 1168 } 1169 1170 // If we have two real floating types, convert the smaller operand 1171 // to the bigger result. 1172 if (LHSFloat && RHSFloat) { 1173 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1174 if (order > 0) { 1175 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1176 return LHSType; 1177 } 1178 1179 assert(order < 0 && "illegal float comparison"); 1180 if (!IsCompAssign) 1181 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1182 return RHSType; 1183 } 1184 1185 if (LHSFloat) { 1186 // Half FP has to be promoted to float unless it is natively supported 1187 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1188 LHSType = S.Context.FloatTy; 1189 1190 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1191 /*ConvertFloat=*/!IsCompAssign, 1192 /*ConvertInt=*/ true); 1193 } 1194 assert(RHSFloat); 1195 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1196 /*ConvertFloat=*/ true, 1197 /*ConvertInt=*/!IsCompAssign); 1198 } 1199 1200 /// Diagnose attempts to convert between __float128, __ibm128 and 1201 /// long double if there is no support for such conversion. 1202 /// Helper function of UsualArithmeticConversions(). 1203 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1204 QualType RHSType) { 1205 // No issue if either is not a floating point type. 1206 if (!LHSType->isFloatingType() || !RHSType->isFloatingType()) 1207 return false; 1208 1209 // No issue if both have the same 128-bit float semantics. 1210 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1211 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1212 1213 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType; 1214 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType; 1215 1216 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem); 1217 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem); 1218 1219 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() || 1220 &RHSSem != &llvm::APFloat::IEEEquad()) && 1221 (&LHSSem != &llvm::APFloat::IEEEquad() || 1222 &RHSSem != &llvm::APFloat::PPCDoubleDouble())) 1223 return false; 1224 1225 return true; 1226 } 1227 1228 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1229 1230 namespace { 1231 /// These helper callbacks are placed in an anonymous namespace to 1232 /// permit their use as function template parameters. 1233 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1234 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1235 } 1236 1237 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1238 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1239 CK_IntegralComplexCast); 1240 } 1241 } 1242 1243 /// Handle integer arithmetic conversions. Helper function of 1244 /// UsualArithmeticConversions() 1245 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1246 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1247 ExprResult &RHS, QualType LHSType, 1248 QualType RHSType, bool IsCompAssign) { 1249 // The rules for this case are in C99 6.3.1.8 1250 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1251 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1252 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1253 if (LHSSigned == RHSSigned) { 1254 // Same signedness; use the higher-ranked type 1255 if (order >= 0) { 1256 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1257 return LHSType; 1258 } else if (!IsCompAssign) 1259 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1260 return RHSType; 1261 } else if (order != (LHSSigned ? 1 : -1)) { 1262 // The unsigned type has greater than or equal rank to the 1263 // signed type, so use the unsigned type 1264 if (RHSSigned) { 1265 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1266 return LHSType; 1267 } else if (!IsCompAssign) 1268 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1269 return RHSType; 1270 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1271 // The two types are different widths; if we are here, that 1272 // means the signed type is larger than the unsigned type, so 1273 // use the signed type. 1274 if (LHSSigned) { 1275 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1276 return LHSType; 1277 } else if (!IsCompAssign) 1278 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1279 return RHSType; 1280 } else { 1281 // The signed type is higher-ranked than the unsigned type, 1282 // but isn't actually any bigger (like unsigned int and long 1283 // on most 32-bit systems). Use the unsigned type corresponding 1284 // to the signed type. 1285 QualType result = 1286 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1287 RHS = (*doRHSCast)(S, RHS.get(), result); 1288 if (!IsCompAssign) 1289 LHS = (*doLHSCast)(S, LHS.get(), result); 1290 return result; 1291 } 1292 } 1293 1294 /// Handle conversions with GCC complex int extension. Helper function 1295 /// of UsualArithmeticConversions() 1296 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1297 ExprResult &RHS, QualType LHSType, 1298 QualType RHSType, 1299 bool IsCompAssign) { 1300 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1301 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1302 1303 if (LHSComplexInt && RHSComplexInt) { 1304 QualType LHSEltType = LHSComplexInt->getElementType(); 1305 QualType RHSEltType = RHSComplexInt->getElementType(); 1306 QualType ScalarType = 1307 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1308 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1309 1310 return S.Context.getComplexType(ScalarType); 1311 } 1312 1313 if (LHSComplexInt) { 1314 QualType LHSEltType = LHSComplexInt->getElementType(); 1315 QualType ScalarType = 1316 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1317 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1318 QualType ComplexType = S.Context.getComplexType(ScalarType); 1319 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1320 CK_IntegralRealToComplex); 1321 1322 return ComplexType; 1323 } 1324 1325 assert(RHSComplexInt); 1326 1327 QualType RHSEltType = RHSComplexInt->getElementType(); 1328 QualType ScalarType = 1329 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1330 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1331 QualType ComplexType = S.Context.getComplexType(ScalarType); 1332 1333 if (!IsCompAssign) 1334 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1335 CK_IntegralRealToComplex); 1336 return ComplexType; 1337 } 1338 1339 /// Return the rank of a given fixed point or integer type. The value itself 1340 /// doesn't matter, but the values must be increasing with proper increasing 1341 /// rank as described in N1169 4.1.1. 1342 static unsigned GetFixedPointRank(QualType Ty) { 1343 const auto *BTy = Ty->getAs<BuiltinType>(); 1344 assert(BTy && "Expected a builtin type."); 1345 1346 switch (BTy->getKind()) { 1347 case BuiltinType::ShortFract: 1348 case BuiltinType::UShortFract: 1349 case BuiltinType::SatShortFract: 1350 case BuiltinType::SatUShortFract: 1351 return 1; 1352 case BuiltinType::Fract: 1353 case BuiltinType::UFract: 1354 case BuiltinType::SatFract: 1355 case BuiltinType::SatUFract: 1356 return 2; 1357 case BuiltinType::LongFract: 1358 case BuiltinType::ULongFract: 1359 case BuiltinType::SatLongFract: 1360 case BuiltinType::SatULongFract: 1361 return 3; 1362 case BuiltinType::ShortAccum: 1363 case BuiltinType::UShortAccum: 1364 case BuiltinType::SatShortAccum: 1365 case BuiltinType::SatUShortAccum: 1366 return 4; 1367 case BuiltinType::Accum: 1368 case BuiltinType::UAccum: 1369 case BuiltinType::SatAccum: 1370 case BuiltinType::SatUAccum: 1371 return 5; 1372 case BuiltinType::LongAccum: 1373 case BuiltinType::ULongAccum: 1374 case BuiltinType::SatLongAccum: 1375 case BuiltinType::SatULongAccum: 1376 return 6; 1377 default: 1378 if (BTy->isInteger()) 1379 return 0; 1380 llvm_unreachable("Unexpected fixed point or integer type"); 1381 } 1382 } 1383 1384 /// handleFixedPointConversion - Fixed point operations between fixed 1385 /// point types and integers or other fixed point types do not fall under 1386 /// usual arithmetic conversion since these conversions could result in loss 1387 /// of precsision (N1169 4.1.4). These operations should be calculated with 1388 /// the full precision of their result type (N1169 4.1.6.2.1). 1389 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1390 QualType RHSTy) { 1391 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1392 "Expected at least one of the operands to be a fixed point type"); 1393 assert((LHSTy->isFixedPointOrIntegerType() || 1394 RHSTy->isFixedPointOrIntegerType()) && 1395 "Special fixed point arithmetic operation conversions are only " 1396 "applied to ints or other fixed point types"); 1397 1398 // If one operand has signed fixed-point type and the other operand has 1399 // unsigned fixed-point type, then the unsigned fixed-point operand is 1400 // converted to its corresponding signed fixed-point type and the resulting 1401 // type is the type of the converted operand. 1402 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1403 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1404 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1405 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1406 1407 // The result type is the type with the highest rank, whereby a fixed-point 1408 // conversion rank is always greater than an integer conversion rank; if the 1409 // type of either of the operands is a saturating fixedpoint type, the result 1410 // type shall be the saturating fixed-point type corresponding to the type 1411 // with the highest rank; the resulting value is converted (taking into 1412 // account rounding and overflow) to the precision of the resulting type. 1413 // Same ranks between signed and unsigned types are resolved earlier, so both 1414 // types are either signed or both unsigned at this point. 1415 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1416 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1417 1418 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1419 1420 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1421 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1422 1423 return ResultTy; 1424 } 1425 1426 /// Check that the usual arithmetic conversions can be performed on this pair of 1427 /// expressions that might be of enumeration type. 1428 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1429 SourceLocation Loc, 1430 Sema::ArithConvKind ACK) { 1431 // C++2a [expr.arith.conv]p1: 1432 // If one operand is of enumeration type and the other operand is of a 1433 // different enumeration type or a floating-point type, this behavior is 1434 // deprecated ([depr.arith.conv.enum]). 1435 // 1436 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1437 // Eventually we will presumably reject these cases (in C++23 onwards?). 1438 QualType L = LHS->getType(), R = RHS->getType(); 1439 bool LEnum = L->isUnscopedEnumerationType(), 1440 REnum = R->isUnscopedEnumerationType(); 1441 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1442 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1443 (REnum && L->isFloatingType())) { 1444 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1445 ? diag::warn_arith_conv_enum_float_cxx20 1446 : diag::warn_arith_conv_enum_float) 1447 << LHS->getSourceRange() << RHS->getSourceRange() 1448 << (int)ACK << LEnum << L << R; 1449 } else if (!IsCompAssign && LEnum && REnum && 1450 !S.Context.hasSameUnqualifiedType(L, R)) { 1451 unsigned DiagID; 1452 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1453 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1454 // If either enumeration type is unnamed, it's less likely that the 1455 // user cares about this, but this situation is still deprecated in 1456 // C++2a. Use a different warning group. 1457 DiagID = S.getLangOpts().CPlusPlus20 1458 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1459 : diag::warn_arith_conv_mixed_anon_enum_types; 1460 } else if (ACK == Sema::ACK_Conditional) { 1461 // Conditional expressions are separated out because they have 1462 // historically had a different warning flag. 1463 DiagID = S.getLangOpts().CPlusPlus20 1464 ? diag::warn_conditional_mixed_enum_types_cxx20 1465 : diag::warn_conditional_mixed_enum_types; 1466 } else if (ACK == Sema::ACK_Comparison) { 1467 // Comparison expressions are separated out because they have 1468 // historically had a different warning flag. 1469 DiagID = S.getLangOpts().CPlusPlus20 1470 ? diag::warn_comparison_mixed_enum_types_cxx20 1471 : diag::warn_comparison_mixed_enum_types; 1472 } else { 1473 DiagID = S.getLangOpts().CPlusPlus20 1474 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1475 : diag::warn_arith_conv_mixed_enum_types; 1476 } 1477 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1478 << (int)ACK << L << R; 1479 } 1480 } 1481 1482 /// UsualArithmeticConversions - Performs various conversions that are common to 1483 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1484 /// routine returns the first non-arithmetic type found. The client is 1485 /// responsible for emitting appropriate error diagnostics. 1486 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1487 SourceLocation Loc, 1488 ArithConvKind ACK) { 1489 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1490 1491 if (ACK != ACK_CompAssign) { 1492 LHS = UsualUnaryConversions(LHS.get()); 1493 if (LHS.isInvalid()) 1494 return QualType(); 1495 } 1496 1497 RHS = UsualUnaryConversions(RHS.get()); 1498 if (RHS.isInvalid()) 1499 return QualType(); 1500 1501 // For conversion purposes, we ignore any qualifiers. 1502 // For example, "const float" and "float" are equivalent. 1503 QualType LHSType = 1504 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1505 QualType RHSType = 1506 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1507 1508 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1509 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1510 LHSType = AtomicLHS->getValueType(); 1511 1512 // If both types are identical, no conversion is needed. 1513 if (LHSType == RHSType) 1514 return LHSType; 1515 1516 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1517 // The caller can deal with this (e.g. pointer + int). 1518 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1519 return QualType(); 1520 1521 // Apply unary and bitfield promotions to the LHS's type. 1522 QualType LHSUnpromotedType = LHSType; 1523 if (LHSType->isPromotableIntegerType()) 1524 LHSType = Context.getPromotedIntegerType(LHSType); 1525 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1526 if (!LHSBitfieldPromoteTy.isNull()) 1527 LHSType = LHSBitfieldPromoteTy; 1528 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1529 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1530 1531 // If both types are identical, no conversion is needed. 1532 if (LHSType == RHSType) 1533 return LHSType; 1534 1535 // At this point, we have two different arithmetic types. 1536 1537 // Diagnose attempts to convert between __ibm128, __float128 and long double 1538 // where such conversions currently can't be handled. 1539 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1540 return QualType(); 1541 1542 // Handle complex types first (C99 6.3.1.8p1). 1543 if (LHSType->isComplexType() || RHSType->isComplexType()) 1544 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1545 ACK == ACK_CompAssign); 1546 1547 // Now handle "real" floating types (i.e. float, double, long double). 1548 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1549 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1550 ACK == ACK_CompAssign); 1551 1552 // Handle GCC complex int extension. 1553 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1554 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1555 ACK == ACK_CompAssign); 1556 1557 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1558 return handleFixedPointConversion(*this, LHSType, RHSType); 1559 1560 // Finally, we have two differing integer types. 1561 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1562 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1563 } 1564 1565 //===----------------------------------------------------------------------===// 1566 // Semantic Analysis for various Expression Types 1567 //===----------------------------------------------------------------------===// 1568 1569 1570 ExprResult 1571 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1572 SourceLocation DefaultLoc, 1573 SourceLocation RParenLoc, 1574 Expr *ControllingExpr, 1575 ArrayRef<ParsedType> ArgTypes, 1576 ArrayRef<Expr *> ArgExprs) { 1577 unsigned NumAssocs = ArgTypes.size(); 1578 assert(NumAssocs == ArgExprs.size()); 1579 1580 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1581 for (unsigned i = 0; i < NumAssocs; ++i) { 1582 if (ArgTypes[i]) 1583 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1584 else 1585 Types[i] = nullptr; 1586 } 1587 1588 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1589 ControllingExpr, 1590 llvm::makeArrayRef(Types, NumAssocs), 1591 ArgExprs); 1592 delete [] Types; 1593 return ER; 1594 } 1595 1596 ExprResult 1597 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1598 SourceLocation DefaultLoc, 1599 SourceLocation RParenLoc, 1600 Expr *ControllingExpr, 1601 ArrayRef<TypeSourceInfo *> Types, 1602 ArrayRef<Expr *> Exprs) { 1603 unsigned NumAssocs = Types.size(); 1604 assert(NumAssocs == Exprs.size()); 1605 1606 // Decay and strip qualifiers for the controlling expression type, and handle 1607 // placeholder type replacement. See committee discussion from WG14 DR423. 1608 { 1609 EnterExpressionEvaluationContext Unevaluated( 1610 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1611 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1612 if (R.isInvalid()) 1613 return ExprError(); 1614 ControllingExpr = R.get(); 1615 } 1616 1617 // The controlling expression is an unevaluated operand, so side effects are 1618 // likely unintended. 1619 if (!inTemplateInstantiation() && 1620 ControllingExpr->HasSideEffects(Context, false)) 1621 Diag(ControllingExpr->getExprLoc(), 1622 diag::warn_side_effects_unevaluated_context); 1623 1624 bool TypeErrorFound = false, 1625 IsResultDependent = ControllingExpr->isTypeDependent(), 1626 ContainsUnexpandedParameterPack 1627 = ControllingExpr->containsUnexpandedParameterPack(); 1628 1629 for (unsigned i = 0; i < NumAssocs; ++i) { 1630 if (Exprs[i]->containsUnexpandedParameterPack()) 1631 ContainsUnexpandedParameterPack = true; 1632 1633 if (Types[i]) { 1634 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1635 ContainsUnexpandedParameterPack = true; 1636 1637 if (Types[i]->getType()->isDependentType()) { 1638 IsResultDependent = true; 1639 } else { 1640 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1641 // complete object type other than a variably modified type." 1642 unsigned D = 0; 1643 if (Types[i]->getType()->isIncompleteType()) 1644 D = diag::err_assoc_type_incomplete; 1645 else if (!Types[i]->getType()->isObjectType()) 1646 D = diag::err_assoc_type_nonobject; 1647 else if (Types[i]->getType()->isVariablyModifiedType()) 1648 D = diag::err_assoc_type_variably_modified; 1649 1650 if (D != 0) { 1651 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1652 << Types[i]->getTypeLoc().getSourceRange() 1653 << Types[i]->getType(); 1654 TypeErrorFound = true; 1655 } 1656 1657 // C11 6.5.1.1p2 "No two generic associations in the same generic 1658 // selection shall specify compatible types." 1659 for (unsigned j = i+1; j < NumAssocs; ++j) 1660 if (Types[j] && !Types[j]->getType()->isDependentType() && 1661 Context.typesAreCompatible(Types[i]->getType(), 1662 Types[j]->getType())) { 1663 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1664 diag::err_assoc_compatible_types) 1665 << Types[j]->getTypeLoc().getSourceRange() 1666 << Types[j]->getType() 1667 << Types[i]->getType(); 1668 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1669 diag::note_compat_assoc) 1670 << Types[i]->getTypeLoc().getSourceRange() 1671 << Types[i]->getType(); 1672 TypeErrorFound = true; 1673 } 1674 } 1675 } 1676 } 1677 if (TypeErrorFound) 1678 return ExprError(); 1679 1680 // If we determined that the generic selection is result-dependent, don't 1681 // try to compute the result expression. 1682 if (IsResultDependent) 1683 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1684 Exprs, DefaultLoc, RParenLoc, 1685 ContainsUnexpandedParameterPack); 1686 1687 SmallVector<unsigned, 1> CompatIndices; 1688 unsigned DefaultIndex = -1U; 1689 for (unsigned i = 0; i < NumAssocs; ++i) { 1690 if (!Types[i]) 1691 DefaultIndex = i; 1692 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1693 Types[i]->getType())) 1694 CompatIndices.push_back(i); 1695 } 1696 1697 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1698 // type compatible with at most one of the types named in its generic 1699 // association list." 1700 if (CompatIndices.size() > 1) { 1701 // We strip parens here because the controlling expression is typically 1702 // parenthesized in macro definitions. 1703 ControllingExpr = ControllingExpr->IgnoreParens(); 1704 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1705 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1706 << (unsigned)CompatIndices.size(); 1707 for (unsigned I : CompatIndices) { 1708 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1709 diag::note_compat_assoc) 1710 << Types[I]->getTypeLoc().getSourceRange() 1711 << Types[I]->getType(); 1712 } 1713 return ExprError(); 1714 } 1715 1716 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1717 // its controlling expression shall have type compatible with exactly one of 1718 // the types named in its generic association list." 1719 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1720 // We strip parens here because the controlling expression is typically 1721 // parenthesized in macro definitions. 1722 ControllingExpr = ControllingExpr->IgnoreParens(); 1723 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1724 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1725 return ExprError(); 1726 } 1727 1728 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1729 // type name that is compatible with the type of the controlling expression, 1730 // then the result expression of the generic selection is the expression 1731 // in that generic association. Otherwise, the result expression of the 1732 // generic selection is the expression in the default generic association." 1733 unsigned ResultIndex = 1734 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1735 1736 return GenericSelectionExpr::Create( 1737 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1738 ContainsUnexpandedParameterPack, ResultIndex); 1739 } 1740 1741 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1742 /// location of the token and the offset of the ud-suffix within it. 1743 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1744 unsigned Offset) { 1745 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1746 S.getLangOpts()); 1747 } 1748 1749 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1750 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1751 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1752 IdentifierInfo *UDSuffix, 1753 SourceLocation UDSuffixLoc, 1754 ArrayRef<Expr*> Args, 1755 SourceLocation LitEndLoc) { 1756 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1757 1758 QualType ArgTy[2]; 1759 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1760 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1761 if (ArgTy[ArgIdx]->isArrayType()) 1762 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1763 } 1764 1765 DeclarationName OpName = 1766 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1767 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1768 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1769 1770 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1771 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1772 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1773 /*AllowStringTemplatePack*/ false, 1774 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1775 return ExprError(); 1776 1777 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1778 } 1779 1780 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1781 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1782 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1783 /// multiple tokens. However, the common case is that StringToks points to one 1784 /// string. 1785 /// 1786 ExprResult 1787 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1788 assert(!StringToks.empty() && "Must have at least one string!"); 1789 1790 StringLiteralParser Literal(StringToks, PP); 1791 if (Literal.hadError) 1792 return ExprError(); 1793 1794 SmallVector<SourceLocation, 4> StringTokLocs; 1795 for (const Token &Tok : StringToks) 1796 StringTokLocs.push_back(Tok.getLocation()); 1797 1798 QualType CharTy = Context.CharTy; 1799 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1800 if (Literal.isWide()) { 1801 CharTy = Context.getWideCharType(); 1802 Kind = StringLiteral::Wide; 1803 } else if (Literal.isUTF8()) { 1804 if (getLangOpts().Char8) 1805 CharTy = Context.Char8Ty; 1806 Kind = StringLiteral::UTF8; 1807 } else if (Literal.isUTF16()) { 1808 CharTy = Context.Char16Ty; 1809 Kind = StringLiteral::UTF16; 1810 } else if (Literal.isUTF32()) { 1811 CharTy = Context.Char32Ty; 1812 Kind = StringLiteral::UTF32; 1813 } else if (Literal.isPascal()) { 1814 CharTy = Context.UnsignedCharTy; 1815 } 1816 1817 // Warn on initializing an array of char from a u8 string literal; this 1818 // becomes ill-formed in C++2a. 1819 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1820 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1821 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1822 1823 // Create removals for all 'u8' prefixes in the string literal(s). This 1824 // ensures C++2a compatibility (but may change the program behavior when 1825 // built by non-Clang compilers for which the execution character set is 1826 // not always UTF-8). 1827 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1828 SourceLocation RemovalDiagLoc; 1829 for (const Token &Tok : StringToks) { 1830 if (Tok.getKind() == tok::utf8_string_literal) { 1831 if (RemovalDiagLoc.isInvalid()) 1832 RemovalDiagLoc = Tok.getLocation(); 1833 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1834 Tok.getLocation(), 1835 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1836 getSourceManager(), getLangOpts()))); 1837 } 1838 } 1839 Diag(RemovalDiagLoc, RemovalDiag); 1840 } 1841 1842 QualType StrTy = 1843 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1844 1845 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1846 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1847 Kind, Literal.Pascal, StrTy, 1848 &StringTokLocs[0], 1849 StringTokLocs.size()); 1850 if (Literal.getUDSuffix().empty()) 1851 return Lit; 1852 1853 // We're building a user-defined literal. 1854 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1855 SourceLocation UDSuffixLoc = 1856 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1857 Literal.getUDSuffixOffset()); 1858 1859 // Make sure we're allowed user-defined literals here. 1860 if (!UDLScope) 1861 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1862 1863 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1864 // operator "" X (str, len) 1865 QualType SizeType = Context.getSizeType(); 1866 1867 DeclarationName OpName = 1868 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1869 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1870 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1871 1872 QualType ArgTy[] = { 1873 Context.getArrayDecayedType(StrTy), SizeType 1874 }; 1875 1876 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1877 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1878 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1879 /*AllowStringTemplatePack*/ true, 1880 /*DiagnoseMissing*/ true, Lit)) { 1881 1882 case LOLR_Cooked: { 1883 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1884 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1885 StringTokLocs[0]); 1886 Expr *Args[] = { Lit, LenArg }; 1887 1888 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1889 } 1890 1891 case LOLR_Template: { 1892 TemplateArgumentListInfo ExplicitArgs; 1893 TemplateArgument Arg(Lit); 1894 TemplateArgumentLocInfo ArgInfo(Lit); 1895 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1896 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1897 &ExplicitArgs); 1898 } 1899 1900 case LOLR_StringTemplatePack: { 1901 TemplateArgumentListInfo ExplicitArgs; 1902 1903 unsigned CharBits = Context.getIntWidth(CharTy); 1904 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1905 llvm::APSInt Value(CharBits, CharIsUnsigned); 1906 1907 TemplateArgument TypeArg(CharTy); 1908 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1909 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1910 1911 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1912 Value = Lit->getCodeUnit(I); 1913 TemplateArgument Arg(Context, Value, CharTy); 1914 TemplateArgumentLocInfo ArgInfo; 1915 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1916 } 1917 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1918 &ExplicitArgs); 1919 } 1920 case LOLR_Raw: 1921 case LOLR_ErrorNoDiagnostic: 1922 llvm_unreachable("unexpected literal operator lookup result"); 1923 case LOLR_Error: 1924 return ExprError(); 1925 } 1926 llvm_unreachable("unexpected literal operator lookup result"); 1927 } 1928 1929 DeclRefExpr * 1930 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1931 SourceLocation Loc, 1932 const CXXScopeSpec *SS) { 1933 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1934 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1935 } 1936 1937 DeclRefExpr * 1938 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1939 const DeclarationNameInfo &NameInfo, 1940 const CXXScopeSpec *SS, NamedDecl *FoundD, 1941 SourceLocation TemplateKWLoc, 1942 const TemplateArgumentListInfo *TemplateArgs) { 1943 NestedNameSpecifierLoc NNS = 1944 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1945 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1946 TemplateArgs); 1947 } 1948 1949 // CUDA/HIP: Check whether a captured reference variable is referencing a 1950 // host variable in a device or host device lambda. 1951 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1952 VarDecl *VD) { 1953 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1954 return false; 1955 assert(VD->getType()->isReferenceType()); 1956 1957 // Check whether the reference variable is referencing a host variable. 1958 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1959 if (!DRE) 1960 return false; 1961 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 1962 if (!Referee || !Referee->hasGlobalStorage() || 1963 Referee->hasAttr<CUDADeviceAttr>()) 1964 return false; 1965 1966 // Check whether the current function is a device or host device lambda. 1967 // Check whether the reference variable is a capture by getDeclContext() 1968 // since refersToEnclosingVariableOrCapture() is not ready at this point. 1969 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 1970 if (MD && MD->getParent()->isLambda() && 1971 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 1972 VD->getDeclContext() != MD) 1973 return true; 1974 1975 return false; 1976 } 1977 1978 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1979 // A declaration named in an unevaluated operand never constitutes an odr-use. 1980 if (isUnevaluatedContext()) 1981 return NOUR_Unevaluated; 1982 1983 // C++2a [basic.def.odr]p4: 1984 // A variable x whose name appears as a potentially-evaluated expression e 1985 // is odr-used by e unless [...] x is a reference that is usable in 1986 // constant expressions. 1987 // CUDA/HIP: 1988 // If a reference variable referencing a host variable is captured in a 1989 // device or host device lambda, the value of the referee must be copied 1990 // to the capture and the reference variable must be treated as odr-use 1991 // since the value of the referee is not known at compile time and must 1992 // be loaded from the captured. 1993 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1994 if (VD->getType()->isReferenceType() && 1995 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1996 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 1997 VD->isUsableInConstantExpressions(Context)) 1998 return NOUR_Constant; 1999 } 2000 2001 // All remaining non-variable cases constitute an odr-use. For variables, we 2002 // need to wait and see how the expression is used. 2003 return NOUR_None; 2004 } 2005 2006 /// BuildDeclRefExpr - Build an expression that references a 2007 /// declaration that does not require a closure capture. 2008 DeclRefExpr * 2009 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2010 const DeclarationNameInfo &NameInfo, 2011 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2012 SourceLocation TemplateKWLoc, 2013 const TemplateArgumentListInfo *TemplateArgs) { 2014 bool RefersToCapturedVariable = 2015 isa<VarDecl>(D) && 2016 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2017 2018 DeclRefExpr *E = DeclRefExpr::Create( 2019 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2020 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2021 MarkDeclRefReferenced(E); 2022 2023 // C++ [except.spec]p17: 2024 // An exception-specification is considered to be needed when: 2025 // - in an expression, the function is the unique lookup result or 2026 // the selected member of a set of overloaded functions. 2027 // 2028 // We delay doing this until after we've built the function reference and 2029 // marked it as used so that: 2030 // a) if the function is defaulted, we get errors from defining it before / 2031 // instead of errors from computing its exception specification, and 2032 // b) if the function is a defaulted comparison, we can use the body we 2033 // build when defining it as input to the exception specification 2034 // computation rather than computing a new body. 2035 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2036 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2037 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2038 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2039 } 2040 } 2041 2042 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2043 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2044 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2045 getCurFunction()->recordUseOfWeak(E); 2046 2047 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2048 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2049 FD = IFD->getAnonField(); 2050 if (FD) { 2051 UnusedPrivateFields.remove(FD); 2052 // Just in case we're building an illegal pointer-to-member. 2053 if (FD->isBitField()) 2054 E->setObjectKind(OK_BitField); 2055 } 2056 2057 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2058 // designates a bit-field. 2059 if (auto *BD = dyn_cast<BindingDecl>(D)) 2060 if (auto *BE = BD->getBinding()) 2061 E->setObjectKind(BE->getObjectKind()); 2062 2063 return E; 2064 } 2065 2066 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2067 /// possibly a list of template arguments. 2068 /// 2069 /// If this produces template arguments, it is permitted to call 2070 /// DecomposeTemplateName. 2071 /// 2072 /// This actually loses a lot of source location information for 2073 /// non-standard name kinds; we should consider preserving that in 2074 /// some way. 2075 void 2076 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2077 TemplateArgumentListInfo &Buffer, 2078 DeclarationNameInfo &NameInfo, 2079 const TemplateArgumentListInfo *&TemplateArgs) { 2080 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2081 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2082 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2083 2084 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2085 Id.TemplateId->NumArgs); 2086 translateTemplateArguments(TemplateArgsPtr, Buffer); 2087 2088 TemplateName TName = Id.TemplateId->Template.get(); 2089 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2090 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2091 TemplateArgs = &Buffer; 2092 } else { 2093 NameInfo = GetNameFromUnqualifiedId(Id); 2094 TemplateArgs = nullptr; 2095 } 2096 } 2097 2098 static void emitEmptyLookupTypoDiagnostic( 2099 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2100 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2101 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2102 DeclContext *Ctx = 2103 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2104 if (!TC) { 2105 // Emit a special diagnostic for failed member lookups. 2106 // FIXME: computing the declaration context might fail here (?) 2107 if (Ctx) 2108 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2109 << SS.getRange(); 2110 else 2111 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2112 return; 2113 } 2114 2115 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2116 bool DroppedSpecifier = 2117 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2118 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2119 ? diag::note_implicit_param_decl 2120 : diag::note_previous_decl; 2121 if (!Ctx) 2122 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2123 SemaRef.PDiag(NoteID)); 2124 else 2125 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2126 << Typo << Ctx << DroppedSpecifier 2127 << SS.getRange(), 2128 SemaRef.PDiag(NoteID)); 2129 } 2130 2131 /// Diagnose a lookup that found results in an enclosing class during error 2132 /// recovery. This usually indicates that the results were found in a dependent 2133 /// base class that could not be searched as part of a template definition. 2134 /// Always issues a diagnostic (though this may be only a warning in MS 2135 /// compatibility mode). 2136 /// 2137 /// Return \c true if the error is unrecoverable, or \c false if the caller 2138 /// should attempt to recover using these lookup results. 2139 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2140 // During a default argument instantiation the CurContext points 2141 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2142 // function parameter list, hence add an explicit check. 2143 bool isDefaultArgument = 2144 !CodeSynthesisContexts.empty() && 2145 CodeSynthesisContexts.back().Kind == 2146 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2147 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2148 bool isInstance = CurMethod && CurMethod->isInstance() && 2149 R.getNamingClass() == CurMethod->getParent() && 2150 !isDefaultArgument; 2151 2152 // There are two ways we can find a class-scope declaration during template 2153 // instantiation that we did not find in the template definition: if it is a 2154 // member of a dependent base class, or if it is declared after the point of 2155 // use in the same class. Distinguish these by comparing the class in which 2156 // the member was found to the naming class of the lookup. 2157 unsigned DiagID = diag::err_found_in_dependent_base; 2158 unsigned NoteID = diag::note_member_declared_at; 2159 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2160 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2161 : diag::err_found_later_in_class; 2162 } else if (getLangOpts().MSVCCompat) { 2163 DiagID = diag::ext_found_in_dependent_base; 2164 NoteID = diag::note_dependent_member_use; 2165 } 2166 2167 if (isInstance) { 2168 // Give a code modification hint to insert 'this->'. 2169 Diag(R.getNameLoc(), DiagID) 2170 << R.getLookupName() 2171 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2172 CheckCXXThisCapture(R.getNameLoc()); 2173 } else { 2174 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2175 // they're not shadowed). 2176 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2177 } 2178 2179 for (NamedDecl *D : R) 2180 Diag(D->getLocation(), NoteID); 2181 2182 // Return true if we are inside a default argument instantiation 2183 // and the found name refers to an instance member function, otherwise 2184 // the caller will try to create an implicit member call and this is wrong 2185 // for default arguments. 2186 // 2187 // FIXME: Is this special case necessary? We could allow the caller to 2188 // diagnose this. 2189 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2190 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2191 return true; 2192 } 2193 2194 // Tell the callee to try to recover. 2195 return false; 2196 } 2197 2198 /// Diagnose an empty lookup. 2199 /// 2200 /// \return false if new lookup candidates were found 2201 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2202 CorrectionCandidateCallback &CCC, 2203 TemplateArgumentListInfo *ExplicitTemplateArgs, 2204 ArrayRef<Expr *> Args, TypoExpr **Out) { 2205 DeclarationName Name = R.getLookupName(); 2206 2207 unsigned diagnostic = diag::err_undeclared_var_use; 2208 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2209 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2210 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2211 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2212 diagnostic = diag::err_undeclared_use; 2213 diagnostic_suggest = diag::err_undeclared_use_suggest; 2214 } 2215 2216 // If the original lookup was an unqualified lookup, fake an 2217 // unqualified lookup. This is useful when (for example) the 2218 // original lookup would not have found something because it was a 2219 // dependent name. 2220 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2221 while (DC) { 2222 if (isa<CXXRecordDecl>(DC)) { 2223 LookupQualifiedName(R, DC); 2224 2225 if (!R.empty()) { 2226 // Don't give errors about ambiguities in this lookup. 2227 R.suppressDiagnostics(); 2228 2229 // If there's a best viable function among the results, only mention 2230 // that one in the notes. 2231 OverloadCandidateSet Candidates(R.getNameLoc(), 2232 OverloadCandidateSet::CSK_Normal); 2233 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2234 OverloadCandidateSet::iterator Best; 2235 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2236 OR_Success) { 2237 R.clear(); 2238 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2239 R.resolveKind(); 2240 } 2241 2242 return DiagnoseDependentMemberLookup(R); 2243 } 2244 2245 R.clear(); 2246 } 2247 2248 DC = DC->getLookupParent(); 2249 } 2250 2251 // We didn't find anything, so try to correct for a typo. 2252 TypoCorrection Corrected; 2253 if (S && Out) { 2254 SourceLocation TypoLoc = R.getNameLoc(); 2255 assert(!ExplicitTemplateArgs && 2256 "Diagnosing an empty lookup with explicit template args!"); 2257 *Out = CorrectTypoDelayed( 2258 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2259 [=](const TypoCorrection &TC) { 2260 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2261 diagnostic, diagnostic_suggest); 2262 }, 2263 nullptr, CTK_ErrorRecovery); 2264 if (*Out) 2265 return true; 2266 } else if (S && 2267 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2268 S, &SS, CCC, CTK_ErrorRecovery))) { 2269 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2270 bool DroppedSpecifier = 2271 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2272 R.setLookupName(Corrected.getCorrection()); 2273 2274 bool AcceptableWithRecovery = false; 2275 bool AcceptableWithoutRecovery = false; 2276 NamedDecl *ND = Corrected.getFoundDecl(); 2277 if (ND) { 2278 if (Corrected.isOverloaded()) { 2279 OverloadCandidateSet OCS(R.getNameLoc(), 2280 OverloadCandidateSet::CSK_Normal); 2281 OverloadCandidateSet::iterator Best; 2282 for (NamedDecl *CD : Corrected) { 2283 if (FunctionTemplateDecl *FTD = 2284 dyn_cast<FunctionTemplateDecl>(CD)) 2285 AddTemplateOverloadCandidate( 2286 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2287 Args, OCS); 2288 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2289 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2290 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2291 Args, OCS); 2292 } 2293 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2294 case OR_Success: 2295 ND = Best->FoundDecl; 2296 Corrected.setCorrectionDecl(ND); 2297 break; 2298 default: 2299 // FIXME: Arbitrarily pick the first declaration for the note. 2300 Corrected.setCorrectionDecl(ND); 2301 break; 2302 } 2303 } 2304 R.addDecl(ND); 2305 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2306 CXXRecordDecl *Record = nullptr; 2307 if (Corrected.getCorrectionSpecifier()) { 2308 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2309 Record = Ty->getAsCXXRecordDecl(); 2310 } 2311 if (!Record) 2312 Record = cast<CXXRecordDecl>( 2313 ND->getDeclContext()->getRedeclContext()); 2314 R.setNamingClass(Record); 2315 } 2316 2317 auto *UnderlyingND = ND->getUnderlyingDecl(); 2318 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2319 isa<FunctionTemplateDecl>(UnderlyingND); 2320 // FIXME: If we ended up with a typo for a type name or 2321 // Objective-C class name, we're in trouble because the parser 2322 // is in the wrong place to recover. Suggest the typo 2323 // correction, but don't make it a fix-it since we're not going 2324 // to recover well anyway. 2325 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2326 getAsTypeTemplateDecl(UnderlyingND) || 2327 isa<ObjCInterfaceDecl>(UnderlyingND); 2328 } else { 2329 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2330 // because we aren't able to recover. 2331 AcceptableWithoutRecovery = true; 2332 } 2333 2334 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2335 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2336 ? diag::note_implicit_param_decl 2337 : diag::note_previous_decl; 2338 if (SS.isEmpty()) 2339 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2340 PDiag(NoteID), AcceptableWithRecovery); 2341 else 2342 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2343 << Name << computeDeclContext(SS, false) 2344 << DroppedSpecifier << SS.getRange(), 2345 PDiag(NoteID), AcceptableWithRecovery); 2346 2347 // Tell the callee whether to try to recover. 2348 return !AcceptableWithRecovery; 2349 } 2350 } 2351 R.clear(); 2352 2353 // Emit a special diagnostic for failed member lookups. 2354 // FIXME: computing the declaration context might fail here (?) 2355 if (!SS.isEmpty()) { 2356 Diag(R.getNameLoc(), diag::err_no_member) 2357 << Name << computeDeclContext(SS, false) 2358 << SS.getRange(); 2359 return true; 2360 } 2361 2362 // Give up, we can't recover. 2363 Diag(R.getNameLoc(), diagnostic) << Name; 2364 return true; 2365 } 2366 2367 /// In Microsoft mode, if we are inside a template class whose parent class has 2368 /// dependent base classes, and we can't resolve an unqualified identifier, then 2369 /// assume the identifier is a member of a dependent base class. We can only 2370 /// recover successfully in static methods, instance methods, and other contexts 2371 /// where 'this' is available. This doesn't precisely match MSVC's 2372 /// instantiation model, but it's close enough. 2373 static Expr * 2374 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2375 DeclarationNameInfo &NameInfo, 2376 SourceLocation TemplateKWLoc, 2377 const TemplateArgumentListInfo *TemplateArgs) { 2378 // Only try to recover from lookup into dependent bases in static methods or 2379 // contexts where 'this' is available. 2380 QualType ThisType = S.getCurrentThisType(); 2381 const CXXRecordDecl *RD = nullptr; 2382 if (!ThisType.isNull()) 2383 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2384 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2385 RD = MD->getParent(); 2386 if (!RD || !RD->hasAnyDependentBases()) 2387 return nullptr; 2388 2389 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2390 // is available, suggest inserting 'this->' as a fixit. 2391 SourceLocation Loc = NameInfo.getLoc(); 2392 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2393 DB << NameInfo.getName() << RD; 2394 2395 if (!ThisType.isNull()) { 2396 DB << FixItHint::CreateInsertion(Loc, "this->"); 2397 return CXXDependentScopeMemberExpr::Create( 2398 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2399 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2400 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2401 } 2402 2403 // Synthesize a fake NNS that points to the derived class. This will 2404 // perform name lookup during template instantiation. 2405 CXXScopeSpec SS; 2406 auto *NNS = 2407 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2408 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2409 return DependentScopeDeclRefExpr::Create( 2410 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2411 TemplateArgs); 2412 } 2413 2414 ExprResult 2415 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2416 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2417 bool HasTrailingLParen, bool IsAddressOfOperand, 2418 CorrectionCandidateCallback *CCC, 2419 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2420 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2421 "cannot be direct & operand and have a trailing lparen"); 2422 if (SS.isInvalid()) 2423 return ExprError(); 2424 2425 TemplateArgumentListInfo TemplateArgsBuffer; 2426 2427 // Decompose the UnqualifiedId into the following data. 2428 DeclarationNameInfo NameInfo; 2429 const TemplateArgumentListInfo *TemplateArgs; 2430 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2431 2432 DeclarationName Name = NameInfo.getName(); 2433 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2434 SourceLocation NameLoc = NameInfo.getLoc(); 2435 2436 if (II && II->isEditorPlaceholder()) { 2437 // FIXME: When typed placeholders are supported we can create a typed 2438 // placeholder expression node. 2439 return ExprError(); 2440 } 2441 2442 // C++ [temp.dep.expr]p3: 2443 // An id-expression is type-dependent if it contains: 2444 // -- an identifier that was declared with a dependent type, 2445 // (note: handled after lookup) 2446 // -- a template-id that is dependent, 2447 // (note: handled in BuildTemplateIdExpr) 2448 // -- a conversion-function-id that specifies a dependent type, 2449 // -- a nested-name-specifier that contains a class-name that 2450 // names a dependent type. 2451 // Determine whether this is a member of an unknown specialization; 2452 // we need to handle these differently. 2453 bool DependentID = false; 2454 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2455 Name.getCXXNameType()->isDependentType()) { 2456 DependentID = true; 2457 } else if (SS.isSet()) { 2458 if (DeclContext *DC = computeDeclContext(SS, false)) { 2459 if (RequireCompleteDeclContext(SS, DC)) 2460 return ExprError(); 2461 } else { 2462 DependentID = true; 2463 } 2464 } 2465 2466 if (DependentID) 2467 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2468 IsAddressOfOperand, TemplateArgs); 2469 2470 // Perform the required lookup. 2471 LookupResult R(*this, NameInfo, 2472 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2473 ? LookupObjCImplicitSelfParam 2474 : LookupOrdinaryName); 2475 if (TemplateKWLoc.isValid() || TemplateArgs) { 2476 // Lookup the template name again to correctly establish the context in 2477 // which it was found. This is really unfortunate as we already did the 2478 // lookup to determine that it was a template name in the first place. If 2479 // this becomes a performance hit, we can work harder to preserve those 2480 // results until we get here but it's likely not worth it. 2481 bool MemberOfUnknownSpecialization; 2482 AssumedTemplateKind AssumedTemplate; 2483 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2484 MemberOfUnknownSpecialization, TemplateKWLoc, 2485 &AssumedTemplate)) 2486 return ExprError(); 2487 2488 if (MemberOfUnknownSpecialization || 2489 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2490 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2491 IsAddressOfOperand, TemplateArgs); 2492 } else { 2493 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2494 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2495 2496 // If the result might be in a dependent base class, this is a dependent 2497 // id-expression. 2498 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2499 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2500 IsAddressOfOperand, TemplateArgs); 2501 2502 // If this reference is in an Objective-C method, then we need to do 2503 // some special Objective-C lookup, too. 2504 if (IvarLookupFollowUp) { 2505 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2506 if (E.isInvalid()) 2507 return ExprError(); 2508 2509 if (Expr *Ex = E.getAs<Expr>()) 2510 return Ex; 2511 } 2512 } 2513 2514 if (R.isAmbiguous()) 2515 return ExprError(); 2516 2517 // This could be an implicitly declared function reference (legal in C90, 2518 // extension in C99, forbidden in C++). 2519 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2520 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2521 if (D) R.addDecl(D); 2522 } 2523 2524 // Determine whether this name might be a candidate for 2525 // argument-dependent lookup. 2526 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2527 2528 if (R.empty() && !ADL) { 2529 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2530 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2531 TemplateKWLoc, TemplateArgs)) 2532 return E; 2533 } 2534 2535 // Don't diagnose an empty lookup for inline assembly. 2536 if (IsInlineAsmIdentifier) 2537 return ExprError(); 2538 2539 // If this name wasn't predeclared and if this is not a function 2540 // call, diagnose the problem. 2541 TypoExpr *TE = nullptr; 2542 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2543 : nullptr); 2544 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2545 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2546 "Typo correction callback misconfigured"); 2547 if (CCC) { 2548 // Make sure the callback knows what the typo being diagnosed is. 2549 CCC->setTypoName(II); 2550 if (SS.isValid()) 2551 CCC->setTypoNNS(SS.getScopeRep()); 2552 } 2553 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2554 // a template name, but we happen to have always already looked up the name 2555 // before we get here if it must be a template name. 2556 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2557 None, &TE)) { 2558 if (TE && KeywordReplacement) { 2559 auto &State = getTypoExprState(TE); 2560 auto BestTC = State.Consumer->getNextCorrection(); 2561 if (BestTC.isKeyword()) { 2562 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2563 if (State.DiagHandler) 2564 State.DiagHandler(BestTC); 2565 KeywordReplacement->startToken(); 2566 KeywordReplacement->setKind(II->getTokenID()); 2567 KeywordReplacement->setIdentifierInfo(II); 2568 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2569 // Clean up the state associated with the TypoExpr, since it has 2570 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2571 clearDelayedTypo(TE); 2572 // Signal that a correction to a keyword was performed by returning a 2573 // valid-but-null ExprResult. 2574 return (Expr*)nullptr; 2575 } 2576 State.Consumer->resetCorrectionStream(); 2577 } 2578 return TE ? TE : ExprError(); 2579 } 2580 2581 assert(!R.empty() && 2582 "DiagnoseEmptyLookup returned false but added no results"); 2583 2584 // If we found an Objective-C instance variable, let 2585 // LookupInObjCMethod build the appropriate expression to 2586 // reference the ivar. 2587 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2588 R.clear(); 2589 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2590 // In a hopelessly buggy code, Objective-C instance variable 2591 // lookup fails and no expression will be built to reference it. 2592 if (!E.isInvalid() && !E.get()) 2593 return ExprError(); 2594 return E; 2595 } 2596 } 2597 2598 // This is guaranteed from this point on. 2599 assert(!R.empty() || ADL); 2600 2601 // Check whether this might be a C++ implicit instance member access. 2602 // C++ [class.mfct.non-static]p3: 2603 // When an id-expression that is not part of a class member access 2604 // syntax and not used to form a pointer to member is used in the 2605 // body of a non-static member function of class X, if name lookup 2606 // resolves the name in the id-expression to a non-static non-type 2607 // member of some class C, the id-expression is transformed into a 2608 // class member access expression using (*this) as the 2609 // postfix-expression to the left of the . operator. 2610 // 2611 // But we don't actually need to do this for '&' operands if R 2612 // resolved to a function or overloaded function set, because the 2613 // expression is ill-formed if it actually works out to be a 2614 // non-static member function: 2615 // 2616 // C++ [expr.ref]p4: 2617 // Otherwise, if E1.E2 refers to a non-static member function. . . 2618 // [t]he expression can be used only as the left-hand operand of a 2619 // member function call. 2620 // 2621 // There are other safeguards against such uses, but it's important 2622 // to get this right here so that we don't end up making a 2623 // spuriously dependent expression if we're inside a dependent 2624 // instance method. 2625 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2626 bool MightBeImplicitMember; 2627 if (!IsAddressOfOperand) 2628 MightBeImplicitMember = true; 2629 else if (!SS.isEmpty()) 2630 MightBeImplicitMember = false; 2631 else if (R.isOverloadedResult()) 2632 MightBeImplicitMember = false; 2633 else if (R.isUnresolvableResult()) 2634 MightBeImplicitMember = true; 2635 else 2636 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2637 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2638 isa<MSPropertyDecl>(R.getFoundDecl()); 2639 2640 if (MightBeImplicitMember) 2641 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2642 R, TemplateArgs, S); 2643 } 2644 2645 if (TemplateArgs || TemplateKWLoc.isValid()) { 2646 2647 // In C++1y, if this is a variable template id, then check it 2648 // in BuildTemplateIdExpr(). 2649 // The single lookup result must be a variable template declaration. 2650 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2651 Id.TemplateId->Kind == TNK_Var_template) { 2652 assert(R.getAsSingle<VarTemplateDecl>() && 2653 "There should only be one declaration found."); 2654 } 2655 2656 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2657 } 2658 2659 return BuildDeclarationNameExpr(SS, R, ADL); 2660 } 2661 2662 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2663 /// declaration name, generally during template instantiation. 2664 /// There's a large number of things which don't need to be done along 2665 /// this path. 2666 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2667 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2668 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2669 DeclContext *DC = computeDeclContext(SS, false); 2670 if (!DC) 2671 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2672 NameInfo, /*TemplateArgs=*/nullptr); 2673 2674 if (RequireCompleteDeclContext(SS, DC)) 2675 return ExprError(); 2676 2677 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2678 LookupQualifiedName(R, DC); 2679 2680 if (R.isAmbiguous()) 2681 return ExprError(); 2682 2683 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2684 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2685 NameInfo, /*TemplateArgs=*/nullptr); 2686 2687 if (R.empty()) { 2688 // Don't diagnose problems with invalid record decl, the secondary no_member 2689 // diagnostic during template instantiation is likely bogus, e.g. if a class 2690 // is invalid because it's derived from an invalid base class, then missing 2691 // members were likely supposed to be inherited. 2692 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2693 if (CD->isInvalidDecl()) 2694 return ExprError(); 2695 Diag(NameInfo.getLoc(), diag::err_no_member) 2696 << NameInfo.getName() << DC << SS.getRange(); 2697 return ExprError(); 2698 } 2699 2700 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2701 // Diagnose a missing typename if this resolved unambiguously to a type in 2702 // a dependent context. If we can recover with a type, downgrade this to 2703 // a warning in Microsoft compatibility mode. 2704 unsigned DiagID = diag::err_typename_missing; 2705 if (RecoveryTSI && getLangOpts().MSVCCompat) 2706 DiagID = diag::ext_typename_missing; 2707 SourceLocation Loc = SS.getBeginLoc(); 2708 auto D = Diag(Loc, DiagID); 2709 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2710 << SourceRange(Loc, NameInfo.getEndLoc()); 2711 2712 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2713 // context. 2714 if (!RecoveryTSI) 2715 return ExprError(); 2716 2717 // Only issue the fixit if we're prepared to recover. 2718 D << FixItHint::CreateInsertion(Loc, "typename "); 2719 2720 // Recover by pretending this was an elaborated type. 2721 QualType Ty = Context.getTypeDeclType(TD); 2722 TypeLocBuilder TLB; 2723 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2724 2725 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2726 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2727 QTL.setElaboratedKeywordLoc(SourceLocation()); 2728 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2729 2730 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2731 2732 return ExprEmpty(); 2733 } 2734 2735 // Defend against this resolving to an implicit member access. We usually 2736 // won't get here if this might be a legitimate a class member (we end up in 2737 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2738 // a pointer-to-member or in an unevaluated context in C++11. 2739 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2740 return BuildPossibleImplicitMemberExpr(SS, 2741 /*TemplateKWLoc=*/SourceLocation(), 2742 R, /*TemplateArgs=*/nullptr, S); 2743 2744 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2745 } 2746 2747 /// The parser has read a name in, and Sema has detected that we're currently 2748 /// inside an ObjC method. Perform some additional checks and determine if we 2749 /// should form a reference to an ivar. 2750 /// 2751 /// Ideally, most of this would be done by lookup, but there's 2752 /// actually quite a lot of extra work involved. 2753 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2754 IdentifierInfo *II) { 2755 SourceLocation Loc = Lookup.getNameLoc(); 2756 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2757 2758 // Check for error condition which is already reported. 2759 if (!CurMethod) 2760 return DeclResult(true); 2761 2762 // There are two cases to handle here. 1) scoped lookup could have failed, 2763 // in which case we should look for an ivar. 2) scoped lookup could have 2764 // found a decl, but that decl is outside the current instance method (i.e. 2765 // a global variable). In these two cases, we do a lookup for an ivar with 2766 // this name, if the lookup sucedes, we replace it our current decl. 2767 2768 // If we're in a class method, we don't normally want to look for 2769 // ivars. But if we don't find anything else, and there's an 2770 // ivar, that's an error. 2771 bool IsClassMethod = CurMethod->isClassMethod(); 2772 2773 bool LookForIvars; 2774 if (Lookup.empty()) 2775 LookForIvars = true; 2776 else if (IsClassMethod) 2777 LookForIvars = false; 2778 else 2779 LookForIvars = (Lookup.isSingleResult() && 2780 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2781 ObjCInterfaceDecl *IFace = nullptr; 2782 if (LookForIvars) { 2783 IFace = CurMethod->getClassInterface(); 2784 ObjCInterfaceDecl *ClassDeclared; 2785 ObjCIvarDecl *IV = nullptr; 2786 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2787 // Diagnose using an ivar in a class method. 2788 if (IsClassMethod) { 2789 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2790 return DeclResult(true); 2791 } 2792 2793 // Diagnose the use of an ivar outside of the declaring class. 2794 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2795 !declaresSameEntity(ClassDeclared, IFace) && 2796 !getLangOpts().DebuggerSupport) 2797 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2798 2799 // Success. 2800 return IV; 2801 } 2802 } else if (CurMethod->isInstanceMethod()) { 2803 // We should warn if a local variable hides an ivar. 2804 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2805 ObjCInterfaceDecl *ClassDeclared; 2806 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2807 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2808 declaresSameEntity(IFace, ClassDeclared)) 2809 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2810 } 2811 } 2812 } else if (Lookup.isSingleResult() && 2813 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2814 // If accessing a stand-alone ivar in a class method, this is an error. 2815 if (const ObjCIvarDecl *IV = 2816 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2817 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2818 return DeclResult(true); 2819 } 2820 } 2821 2822 // Didn't encounter an error, didn't find an ivar. 2823 return DeclResult(false); 2824 } 2825 2826 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2827 ObjCIvarDecl *IV) { 2828 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2829 assert(CurMethod && CurMethod->isInstanceMethod() && 2830 "should not reference ivar from this context"); 2831 2832 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2833 assert(IFace && "should not reference ivar from this context"); 2834 2835 // If we're referencing an invalid decl, just return this as a silent 2836 // error node. The error diagnostic was already emitted on the decl. 2837 if (IV->isInvalidDecl()) 2838 return ExprError(); 2839 2840 // Check if referencing a field with __attribute__((deprecated)). 2841 if (DiagnoseUseOfDecl(IV, Loc)) 2842 return ExprError(); 2843 2844 // FIXME: This should use a new expr for a direct reference, don't 2845 // turn this into Self->ivar, just return a BareIVarExpr or something. 2846 IdentifierInfo &II = Context.Idents.get("self"); 2847 UnqualifiedId SelfName; 2848 SelfName.setImplicitSelfParam(&II); 2849 CXXScopeSpec SelfScopeSpec; 2850 SourceLocation TemplateKWLoc; 2851 ExprResult SelfExpr = 2852 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2853 /*HasTrailingLParen=*/false, 2854 /*IsAddressOfOperand=*/false); 2855 if (SelfExpr.isInvalid()) 2856 return ExprError(); 2857 2858 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2859 if (SelfExpr.isInvalid()) 2860 return ExprError(); 2861 2862 MarkAnyDeclReferenced(Loc, IV, true); 2863 2864 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2865 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2866 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2867 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2868 2869 ObjCIvarRefExpr *Result = new (Context) 2870 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2871 IV->getLocation(), SelfExpr.get(), true, true); 2872 2873 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2874 if (!isUnevaluatedContext() && 2875 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2876 getCurFunction()->recordUseOfWeak(Result); 2877 } 2878 if (getLangOpts().ObjCAutoRefCount) 2879 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2880 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2881 2882 return Result; 2883 } 2884 2885 /// The parser has read a name in, and Sema has detected that we're currently 2886 /// inside an ObjC method. Perform some additional checks and determine if we 2887 /// should form a reference to an ivar. If so, build an expression referencing 2888 /// that ivar. 2889 ExprResult 2890 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2891 IdentifierInfo *II, bool AllowBuiltinCreation) { 2892 // FIXME: Integrate this lookup step into LookupParsedName. 2893 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2894 if (Ivar.isInvalid()) 2895 return ExprError(); 2896 if (Ivar.isUsable()) 2897 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2898 cast<ObjCIvarDecl>(Ivar.get())); 2899 2900 if (Lookup.empty() && II && AllowBuiltinCreation) 2901 LookupBuiltin(Lookup); 2902 2903 // Sentinel value saying that we didn't do anything special. 2904 return ExprResult(false); 2905 } 2906 2907 /// Cast a base object to a member's actual type. 2908 /// 2909 /// There are two relevant checks: 2910 /// 2911 /// C++ [class.access.base]p7: 2912 /// 2913 /// If a class member access operator [...] is used to access a non-static 2914 /// data member or non-static member function, the reference is ill-formed if 2915 /// the left operand [...] cannot be implicitly converted to a pointer to the 2916 /// naming class of the right operand. 2917 /// 2918 /// C++ [expr.ref]p7: 2919 /// 2920 /// If E2 is a non-static data member or a non-static member function, the 2921 /// program is ill-formed if the class of which E2 is directly a member is an 2922 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2923 /// 2924 /// Note that the latter check does not consider access; the access of the 2925 /// "real" base class is checked as appropriate when checking the access of the 2926 /// member name. 2927 ExprResult 2928 Sema::PerformObjectMemberConversion(Expr *From, 2929 NestedNameSpecifier *Qualifier, 2930 NamedDecl *FoundDecl, 2931 NamedDecl *Member) { 2932 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2933 if (!RD) 2934 return From; 2935 2936 QualType DestRecordType; 2937 QualType DestType; 2938 QualType FromRecordType; 2939 QualType FromType = From->getType(); 2940 bool PointerConversions = false; 2941 if (isa<FieldDecl>(Member)) { 2942 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2943 auto FromPtrType = FromType->getAs<PointerType>(); 2944 DestRecordType = Context.getAddrSpaceQualType( 2945 DestRecordType, FromPtrType 2946 ? FromType->getPointeeType().getAddressSpace() 2947 : FromType.getAddressSpace()); 2948 2949 if (FromPtrType) { 2950 DestType = Context.getPointerType(DestRecordType); 2951 FromRecordType = FromPtrType->getPointeeType(); 2952 PointerConversions = true; 2953 } else { 2954 DestType = DestRecordType; 2955 FromRecordType = FromType; 2956 } 2957 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2958 if (Method->isStatic()) 2959 return From; 2960 2961 DestType = Method->getThisType(); 2962 DestRecordType = DestType->getPointeeType(); 2963 2964 if (FromType->getAs<PointerType>()) { 2965 FromRecordType = FromType->getPointeeType(); 2966 PointerConversions = true; 2967 } else { 2968 FromRecordType = FromType; 2969 DestType = DestRecordType; 2970 } 2971 2972 LangAS FromAS = FromRecordType.getAddressSpace(); 2973 LangAS DestAS = DestRecordType.getAddressSpace(); 2974 if (FromAS != DestAS) { 2975 QualType FromRecordTypeWithoutAS = 2976 Context.removeAddrSpaceQualType(FromRecordType); 2977 QualType FromTypeWithDestAS = 2978 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2979 if (PointerConversions) 2980 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2981 From = ImpCastExprToType(From, FromTypeWithDestAS, 2982 CK_AddressSpaceConversion, From->getValueKind()) 2983 .get(); 2984 } 2985 } else { 2986 // No conversion necessary. 2987 return From; 2988 } 2989 2990 if (DestType->isDependentType() || FromType->isDependentType()) 2991 return From; 2992 2993 // If the unqualified types are the same, no conversion is necessary. 2994 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2995 return From; 2996 2997 SourceRange FromRange = From->getSourceRange(); 2998 SourceLocation FromLoc = FromRange.getBegin(); 2999 3000 ExprValueKind VK = From->getValueKind(); 3001 3002 // C++ [class.member.lookup]p8: 3003 // [...] Ambiguities can often be resolved by qualifying a name with its 3004 // class name. 3005 // 3006 // If the member was a qualified name and the qualified referred to a 3007 // specific base subobject type, we'll cast to that intermediate type 3008 // first and then to the object in which the member is declared. That allows 3009 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3010 // 3011 // class Base { public: int x; }; 3012 // class Derived1 : public Base { }; 3013 // class Derived2 : public Base { }; 3014 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3015 // 3016 // void VeryDerived::f() { 3017 // x = 17; // error: ambiguous base subobjects 3018 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3019 // } 3020 if (Qualifier && Qualifier->getAsType()) { 3021 QualType QType = QualType(Qualifier->getAsType(), 0); 3022 assert(QType->isRecordType() && "lookup done with non-record type"); 3023 3024 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3025 3026 // In C++98, the qualifier type doesn't actually have to be a base 3027 // type of the object type, in which case we just ignore it. 3028 // Otherwise build the appropriate casts. 3029 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3030 CXXCastPath BasePath; 3031 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3032 FromLoc, FromRange, &BasePath)) 3033 return ExprError(); 3034 3035 if (PointerConversions) 3036 QType = Context.getPointerType(QType); 3037 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3038 VK, &BasePath).get(); 3039 3040 FromType = QType; 3041 FromRecordType = QRecordType; 3042 3043 // If the qualifier type was the same as the destination type, 3044 // we're done. 3045 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3046 return From; 3047 } 3048 } 3049 3050 CXXCastPath BasePath; 3051 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3052 FromLoc, FromRange, &BasePath, 3053 /*IgnoreAccess=*/true)) 3054 return ExprError(); 3055 3056 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3057 VK, &BasePath); 3058 } 3059 3060 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3061 const LookupResult &R, 3062 bool HasTrailingLParen) { 3063 // Only when used directly as the postfix-expression of a call. 3064 if (!HasTrailingLParen) 3065 return false; 3066 3067 // Never if a scope specifier was provided. 3068 if (SS.isSet()) 3069 return false; 3070 3071 // Only in C++ or ObjC++. 3072 if (!getLangOpts().CPlusPlus) 3073 return false; 3074 3075 // Turn off ADL when we find certain kinds of declarations during 3076 // normal lookup: 3077 for (NamedDecl *D : R) { 3078 // C++0x [basic.lookup.argdep]p3: 3079 // -- a declaration of a class member 3080 // Since using decls preserve this property, we check this on the 3081 // original decl. 3082 if (D->isCXXClassMember()) 3083 return false; 3084 3085 // C++0x [basic.lookup.argdep]p3: 3086 // -- a block-scope function declaration that is not a 3087 // using-declaration 3088 // NOTE: we also trigger this for function templates (in fact, we 3089 // don't check the decl type at all, since all other decl types 3090 // turn off ADL anyway). 3091 if (isa<UsingShadowDecl>(D)) 3092 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3093 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3094 return false; 3095 3096 // C++0x [basic.lookup.argdep]p3: 3097 // -- a declaration that is neither a function or a function 3098 // template 3099 // And also for builtin functions. 3100 if (isa<FunctionDecl>(D)) { 3101 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3102 3103 // But also builtin functions. 3104 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3105 return false; 3106 } else if (!isa<FunctionTemplateDecl>(D)) 3107 return false; 3108 } 3109 3110 return true; 3111 } 3112 3113 3114 /// Diagnoses obvious problems with the use of the given declaration 3115 /// as an expression. This is only actually called for lookups that 3116 /// were not overloaded, and it doesn't promise that the declaration 3117 /// will in fact be used. 3118 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3119 if (D->isInvalidDecl()) 3120 return true; 3121 3122 if (isa<TypedefNameDecl>(D)) { 3123 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3124 return true; 3125 } 3126 3127 if (isa<ObjCInterfaceDecl>(D)) { 3128 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3129 return true; 3130 } 3131 3132 if (isa<NamespaceDecl>(D)) { 3133 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3134 return true; 3135 } 3136 3137 return false; 3138 } 3139 3140 // Certain multiversion types should be treated as overloaded even when there is 3141 // only one result. 3142 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3143 assert(R.isSingleResult() && "Expected only a single result"); 3144 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3145 return FD && 3146 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3147 } 3148 3149 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3150 LookupResult &R, bool NeedsADL, 3151 bool AcceptInvalidDecl) { 3152 // If this is a single, fully-resolved result and we don't need ADL, 3153 // just build an ordinary singleton decl ref. 3154 if (!NeedsADL && R.isSingleResult() && 3155 !R.getAsSingle<FunctionTemplateDecl>() && 3156 !ShouldLookupResultBeMultiVersionOverload(R)) 3157 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3158 R.getRepresentativeDecl(), nullptr, 3159 AcceptInvalidDecl); 3160 3161 // We only need to check the declaration if there's exactly one 3162 // result, because in the overloaded case the results can only be 3163 // functions and function templates. 3164 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3165 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3166 return ExprError(); 3167 3168 // Otherwise, just build an unresolved lookup expression. Suppress 3169 // any lookup-related diagnostics; we'll hash these out later, when 3170 // we've picked a target. 3171 R.suppressDiagnostics(); 3172 3173 UnresolvedLookupExpr *ULE 3174 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3175 SS.getWithLocInContext(Context), 3176 R.getLookupNameInfo(), 3177 NeedsADL, R.isOverloadedResult(), 3178 R.begin(), R.end()); 3179 3180 return ULE; 3181 } 3182 3183 static void 3184 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3185 ValueDecl *var, DeclContext *DC); 3186 3187 /// Complete semantic analysis for a reference to the given declaration. 3188 ExprResult Sema::BuildDeclarationNameExpr( 3189 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3190 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3191 bool AcceptInvalidDecl) { 3192 assert(D && "Cannot refer to a NULL declaration"); 3193 assert(!isa<FunctionTemplateDecl>(D) && 3194 "Cannot refer unambiguously to a function template"); 3195 3196 SourceLocation Loc = NameInfo.getLoc(); 3197 if (CheckDeclInExpr(*this, Loc, D)) 3198 return ExprError(); 3199 3200 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3201 // Specifically diagnose references to class templates that are missing 3202 // a template argument list. 3203 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3204 return ExprError(); 3205 } 3206 3207 // Make sure that we're referring to a value. 3208 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { 3209 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange(); 3210 Diag(D->getLocation(), diag::note_declared_at); 3211 return ExprError(); 3212 } 3213 3214 // Check whether this declaration can be used. Note that we suppress 3215 // this check when we're going to perform argument-dependent lookup 3216 // on this function name, because this might not be the function 3217 // that overload resolution actually selects. 3218 if (DiagnoseUseOfDecl(D, Loc)) 3219 return ExprError(); 3220 3221 auto *VD = cast<ValueDecl>(D); 3222 3223 // Only create DeclRefExpr's for valid Decl's. 3224 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3225 return ExprError(); 3226 3227 // Handle members of anonymous structs and unions. If we got here, 3228 // and the reference is to a class member indirect field, then this 3229 // must be the subject of a pointer-to-member expression. 3230 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3231 if (!indirectField->isCXXClassMember()) 3232 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3233 indirectField); 3234 3235 QualType type = VD->getType(); 3236 if (type.isNull()) 3237 return ExprError(); 3238 ExprValueKind valueKind = VK_PRValue; 3239 3240 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3241 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3242 // is expanded by some outer '...' in the context of the use. 3243 type = type.getNonPackExpansionType(); 3244 3245 switch (D->getKind()) { 3246 // Ignore all the non-ValueDecl kinds. 3247 #define ABSTRACT_DECL(kind) 3248 #define VALUE(type, base) 3249 #define DECL(type, base) case Decl::type: 3250 #include "clang/AST/DeclNodes.inc" 3251 llvm_unreachable("invalid value decl kind"); 3252 3253 // These shouldn't make it here. 3254 case Decl::ObjCAtDefsField: 3255 llvm_unreachable("forming non-member reference to ivar?"); 3256 3257 // Enum constants are always r-values and never references. 3258 // Unresolved using declarations are dependent. 3259 case Decl::EnumConstant: 3260 case Decl::UnresolvedUsingValue: 3261 case Decl::OMPDeclareReduction: 3262 case Decl::OMPDeclareMapper: 3263 valueKind = VK_PRValue; 3264 break; 3265 3266 // Fields and indirect fields that got here must be for 3267 // pointer-to-member expressions; we just call them l-values for 3268 // internal consistency, because this subexpression doesn't really 3269 // exist in the high-level semantics. 3270 case Decl::Field: 3271 case Decl::IndirectField: 3272 case Decl::ObjCIvar: 3273 assert(getLangOpts().CPlusPlus && "building reference to field in C?"); 3274 3275 // These can't have reference type in well-formed programs, but 3276 // for internal consistency we do this anyway. 3277 type = type.getNonReferenceType(); 3278 valueKind = VK_LValue; 3279 break; 3280 3281 // Non-type template parameters are either l-values or r-values 3282 // depending on the type. 3283 case Decl::NonTypeTemplateParm: { 3284 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3285 type = reftype->getPointeeType(); 3286 valueKind = VK_LValue; // even if the parameter is an r-value reference 3287 break; 3288 } 3289 3290 // [expr.prim.id.unqual]p2: 3291 // If the entity is a template parameter object for a template 3292 // parameter of type T, the type of the expression is const T. 3293 // [...] The expression is an lvalue if the entity is a [...] template 3294 // parameter object. 3295 if (type->isRecordType()) { 3296 type = type.getUnqualifiedType().withConst(); 3297 valueKind = VK_LValue; 3298 break; 3299 } 3300 3301 // For non-references, we need to strip qualifiers just in case 3302 // the template parameter was declared as 'const int' or whatever. 3303 valueKind = VK_PRValue; 3304 type = type.getUnqualifiedType(); 3305 break; 3306 } 3307 3308 case Decl::Var: 3309 case Decl::VarTemplateSpecialization: 3310 case Decl::VarTemplatePartialSpecialization: 3311 case Decl::Decomposition: 3312 case Decl::OMPCapturedExpr: 3313 // In C, "extern void blah;" is valid and is an r-value. 3314 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && 3315 type->isVoidType()) { 3316 valueKind = VK_PRValue; 3317 break; 3318 } 3319 LLVM_FALLTHROUGH; 3320 3321 case Decl::ImplicitParam: 3322 case Decl::ParmVar: { 3323 // These are always l-values. 3324 valueKind = VK_LValue; 3325 type = type.getNonReferenceType(); 3326 3327 // FIXME: Does the addition of const really only apply in 3328 // potentially-evaluated contexts? Since the variable isn't actually 3329 // captured in an unevaluated context, it seems that the answer is no. 3330 if (!isUnevaluatedContext()) { 3331 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3332 if (!CapturedType.isNull()) 3333 type = CapturedType; 3334 } 3335 3336 break; 3337 } 3338 3339 case Decl::Binding: { 3340 // These are always lvalues. 3341 valueKind = VK_LValue; 3342 type = type.getNonReferenceType(); 3343 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3344 // decides how that's supposed to work. 3345 auto *BD = cast<BindingDecl>(VD); 3346 if (BD->getDeclContext() != CurContext) { 3347 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3348 if (DD && DD->hasLocalStorage()) 3349 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3350 } 3351 break; 3352 } 3353 3354 case Decl::Function: { 3355 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3356 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3357 type = Context.BuiltinFnTy; 3358 valueKind = VK_PRValue; 3359 break; 3360 } 3361 } 3362 3363 const FunctionType *fty = type->castAs<FunctionType>(); 3364 3365 // If we're referring to a function with an __unknown_anytype 3366 // result type, make the entire expression __unknown_anytype. 3367 if (fty->getReturnType() == Context.UnknownAnyTy) { 3368 type = Context.UnknownAnyTy; 3369 valueKind = VK_PRValue; 3370 break; 3371 } 3372 3373 // Functions are l-values in C++. 3374 if (getLangOpts().CPlusPlus) { 3375 valueKind = VK_LValue; 3376 break; 3377 } 3378 3379 // C99 DR 316 says that, if a function type comes from a 3380 // function definition (without a prototype), that type is only 3381 // used for checking compatibility. Therefore, when referencing 3382 // the function, we pretend that we don't have the full function 3383 // type. 3384 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty)) 3385 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3386 fty->getExtInfo()); 3387 3388 // Functions are r-values in C. 3389 valueKind = VK_PRValue; 3390 break; 3391 } 3392 3393 case Decl::CXXDeductionGuide: 3394 llvm_unreachable("building reference to deduction guide"); 3395 3396 case Decl::MSProperty: 3397 case Decl::MSGuid: 3398 case Decl::TemplateParamObject: 3399 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3400 // capture in OpenMP, or duplicated between host and device? 3401 valueKind = VK_LValue; 3402 break; 3403 3404 case Decl::CXXMethod: 3405 // If we're referring to a method with an __unknown_anytype 3406 // result type, make the entire expression __unknown_anytype. 3407 // This should only be possible with a type written directly. 3408 if (const FunctionProtoType *proto = 3409 dyn_cast<FunctionProtoType>(VD->getType())) 3410 if (proto->getReturnType() == Context.UnknownAnyTy) { 3411 type = Context.UnknownAnyTy; 3412 valueKind = VK_PRValue; 3413 break; 3414 } 3415 3416 // C++ methods are l-values if static, r-values if non-static. 3417 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3418 valueKind = VK_LValue; 3419 break; 3420 } 3421 LLVM_FALLTHROUGH; 3422 3423 case Decl::CXXConversion: 3424 case Decl::CXXDestructor: 3425 case Decl::CXXConstructor: 3426 valueKind = VK_PRValue; 3427 break; 3428 } 3429 3430 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3431 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3432 TemplateArgs); 3433 } 3434 3435 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3436 SmallString<32> &Target) { 3437 Target.resize(CharByteWidth * (Source.size() + 1)); 3438 char *ResultPtr = &Target[0]; 3439 const llvm::UTF8 *ErrorPtr; 3440 bool success = 3441 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3442 (void)success; 3443 assert(success); 3444 Target.resize(ResultPtr - &Target[0]); 3445 } 3446 3447 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3448 PredefinedExpr::IdentKind IK) { 3449 // Pick the current block, lambda, captured statement or function. 3450 Decl *currentDecl = nullptr; 3451 if (const BlockScopeInfo *BSI = getCurBlock()) 3452 currentDecl = BSI->TheDecl; 3453 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3454 currentDecl = LSI->CallOperator; 3455 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3456 currentDecl = CSI->TheCapturedDecl; 3457 else 3458 currentDecl = getCurFunctionOrMethodDecl(); 3459 3460 if (!currentDecl) { 3461 Diag(Loc, diag::ext_predef_outside_function); 3462 currentDecl = Context.getTranslationUnitDecl(); 3463 } 3464 3465 QualType ResTy; 3466 StringLiteral *SL = nullptr; 3467 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3468 ResTy = Context.DependentTy; 3469 else { 3470 // Pre-defined identifiers are of type char[x], where x is the length of 3471 // the string. 3472 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3473 unsigned Length = Str.length(); 3474 3475 llvm::APInt LengthI(32, Length + 1); 3476 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3477 ResTy = 3478 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3479 SmallString<32> RawChars; 3480 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3481 Str, RawChars); 3482 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3483 ArrayType::Normal, 3484 /*IndexTypeQuals*/ 0); 3485 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3486 /*Pascal*/ false, ResTy, Loc); 3487 } else { 3488 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3489 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3490 ArrayType::Normal, 3491 /*IndexTypeQuals*/ 0); 3492 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3493 /*Pascal*/ false, ResTy, Loc); 3494 } 3495 } 3496 3497 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3498 } 3499 3500 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3501 SourceLocation LParen, 3502 SourceLocation RParen, 3503 TypeSourceInfo *TSI) { 3504 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); 3505 } 3506 3507 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3508 SourceLocation LParen, 3509 SourceLocation RParen, 3510 ParsedType ParsedTy) { 3511 TypeSourceInfo *TSI = nullptr; 3512 QualType Ty = GetTypeFromParser(ParsedTy, &TSI); 3513 3514 if (Ty.isNull()) 3515 return ExprError(); 3516 if (!TSI) 3517 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); 3518 3519 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); 3520 } 3521 3522 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3523 PredefinedExpr::IdentKind IK; 3524 3525 switch (Kind) { 3526 default: llvm_unreachable("Unknown simple primary expr!"); 3527 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3528 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3529 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3530 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3531 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3532 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3533 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3534 } 3535 3536 return BuildPredefinedExpr(Loc, IK); 3537 } 3538 3539 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3540 SmallString<16> CharBuffer; 3541 bool Invalid = false; 3542 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3543 if (Invalid) 3544 return ExprError(); 3545 3546 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3547 PP, Tok.getKind()); 3548 if (Literal.hadError()) 3549 return ExprError(); 3550 3551 QualType Ty; 3552 if (Literal.isWide()) 3553 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3554 else if (Literal.isUTF8() && getLangOpts().Char8) 3555 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3556 else if (Literal.isUTF16()) 3557 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3558 else if (Literal.isUTF32()) 3559 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3560 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3561 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3562 else 3563 Ty = Context.CharTy; // 'x' -> char in C++ 3564 3565 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3566 if (Literal.isWide()) 3567 Kind = CharacterLiteral::Wide; 3568 else if (Literal.isUTF16()) 3569 Kind = CharacterLiteral::UTF16; 3570 else if (Literal.isUTF32()) 3571 Kind = CharacterLiteral::UTF32; 3572 else if (Literal.isUTF8()) 3573 Kind = CharacterLiteral::UTF8; 3574 3575 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3576 Tok.getLocation()); 3577 3578 if (Literal.getUDSuffix().empty()) 3579 return Lit; 3580 3581 // We're building a user-defined literal. 3582 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3583 SourceLocation UDSuffixLoc = 3584 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3585 3586 // Make sure we're allowed user-defined literals here. 3587 if (!UDLScope) 3588 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3589 3590 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3591 // operator "" X (ch) 3592 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3593 Lit, Tok.getLocation()); 3594 } 3595 3596 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3597 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3598 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3599 Context.IntTy, Loc); 3600 } 3601 3602 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3603 QualType Ty, SourceLocation Loc) { 3604 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3605 3606 using llvm::APFloat; 3607 APFloat Val(Format); 3608 3609 APFloat::opStatus result = Literal.GetFloatValue(Val); 3610 3611 // Overflow is always an error, but underflow is only an error if 3612 // we underflowed to zero (APFloat reports denormals as underflow). 3613 if ((result & APFloat::opOverflow) || 3614 ((result & APFloat::opUnderflow) && Val.isZero())) { 3615 unsigned diagnostic; 3616 SmallString<20> buffer; 3617 if (result & APFloat::opOverflow) { 3618 diagnostic = diag::warn_float_overflow; 3619 APFloat::getLargest(Format).toString(buffer); 3620 } else { 3621 diagnostic = diag::warn_float_underflow; 3622 APFloat::getSmallest(Format).toString(buffer); 3623 } 3624 3625 S.Diag(Loc, diagnostic) 3626 << Ty 3627 << StringRef(buffer.data(), buffer.size()); 3628 } 3629 3630 bool isExact = (result == APFloat::opOK); 3631 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3632 } 3633 3634 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3635 assert(E && "Invalid expression"); 3636 3637 if (E->isValueDependent()) 3638 return false; 3639 3640 QualType QT = E->getType(); 3641 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3642 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3643 return true; 3644 } 3645 3646 llvm::APSInt ValueAPS; 3647 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3648 3649 if (R.isInvalid()) 3650 return true; 3651 3652 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3653 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3654 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3655 << toString(ValueAPS, 10) << ValueIsPositive; 3656 return true; 3657 } 3658 3659 return false; 3660 } 3661 3662 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3663 // Fast path for a single digit (which is quite common). A single digit 3664 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3665 if (Tok.getLength() == 1) { 3666 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3667 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3668 } 3669 3670 SmallString<128> SpellingBuffer; 3671 // NumericLiteralParser wants to overread by one character. Add padding to 3672 // the buffer in case the token is copied to the buffer. If getSpelling() 3673 // returns a StringRef to the memory buffer, it should have a null char at 3674 // the EOF, so it is also safe. 3675 SpellingBuffer.resize(Tok.getLength() + 1); 3676 3677 // Get the spelling of the token, which eliminates trigraphs, etc. 3678 bool Invalid = false; 3679 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3680 if (Invalid) 3681 return ExprError(); 3682 3683 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3684 PP.getSourceManager(), PP.getLangOpts(), 3685 PP.getTargetInfo(), PP.getDiagnostics()); 3686 if (Literal.hadError) 3687 return ExprError(); 3688 3689 if (Literal.hasUDSuffix()) { 3690 // We're building a user-defined literal. 3691 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3692 SourceLocation UDSuffixLoc = 3693 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3694 3695 // Make sure we're allowed user-defined literals here. 3696 if (!UDLScope) 3697 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3698 3699 QualType CookedTy; 3700 if (Literal.isFloatingLiteral()) { 3701 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3702 // long double, the literal is treated as a call of the form 3703 // operator "" X (f L) 3704 CookedTy = Context.LongDoubleTy; 3705 } else { 3706 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3707 // unsigned long long, the literal is treated as a call of the form 3708 // operator "" X (n ULL) 3709 CookedTy = Context.UnsignedLongLongTy; 3710 } 3711 3712 DeclarationName OpName = 3713 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3714 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3715 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3716 3717 SourceLocation TokLoc = Tok.getLocation(); 3718 3719 // Perform literal operator lookup to determine if we're building a raw 3720 // literal or a cooked one. 3721 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3722 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3723 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3724 /*AllowStringTemplatePack*/ false, 3725 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3726 case LOLR_ErrorNoDiagnostic: 3727 // Lookup failure for imaginary constants isn't fatal, there's still the 3728 // GNU extension producing _Complex types. 3729 break; 3730 case LOLR_Error: 3731 return ExprError(); 3732 case LOLR_Cooked: { 3733 Expr *Lit; 3734 if (Literal.isFloatingLiteral()) { 3735 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3736 } else { 3737 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3738 if (Literal.GetIntegerValue(ResultVal)) 3739 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3740 << /* Unsigned */ 1; 3741 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3742 Tok.getLocation()); 3743 } 3744 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3745 } 3746 3747 case LOLR_Raw: { 3748 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3749 // literal is treated as a call of the form 3750 // operator "" X ("n") 3751 unsigned Length = Literal.getUDSuffixOffset(); 3752 QualType StrTy = Context.getConstantArrayType( 3753 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3754 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3755 Expr *Lit = StringLiteral::Create( 3756 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3757 /*Pascal*/false, StrTy, &TokLoc, 1); 3758 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3759 } 3760 3761 case LOLR_Template: { 3762 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3763 // template), L is treated as a call fo the form 3764 // operator "" X <'c1', 'c2', ... 'ck'>() 3765 // where n is the source character sequence c1 c2 ... ck. 3766 TemplateArgumentListInfo ExplicitArgs; 3767 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3768 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3769 llvm::APSInt Value(CharBits, CharIsUnsigned); 3770 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3771 Value = TokSpelling[I]; 3772 TemplateArgument Arg(Context, Value, Context.CharTy); 3773 TemplateArgumentLocInfo ArgInfo; 3774 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3775 } 3776 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3777 &ExplicitArgs); 3778 } 3779 case LOLR_StringTemplatePack: 3780 llvm_unreachable("unexpected literal operator lookup result"); 3781 } 3782 } 3783 3784 Expr *Res; 3785 3786 if (Literal.isFixedPointLiteral()) { 3787 QualType Ty; 3788 3789 if (Literal.isAccum) { 3790 if (Literal.isHalf) { 3791 Ty = Context.ShortAccumTy; 3792 } else if (Literal.isLong) { 3793 Ty = Context.LongAccumTy; 3794 } else { 3795 Ty = Context.AccumTy; 3796 } 3797 } else if (Literal.isFract) { 3798 if (Literal.isHalf) { 3799 Ty = Context.ShortFractTy; 3800 } else if (Literal.isLong) { 3801 Ty = Context.LongFractTy; 3802 } else { 3803 Ty = Context.FractTy; 3804 } 3805 } 3806 3807 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3808 3809 bool isSigned = !Literal.isUnsigned; 3810 unsigned scale = Context.getFixedPointScale(Ty); 3811 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3812 3813 llvm::APInt Val(bit_width, 0, isSigned); 3814 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3815 bool ValIsZero = Val.isNullValue() && !Overflowed; 3816 3817 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3818 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3819 // Clause 6.4.4 - The value of a constant shall be in the range of 3820 // representable values for its type, with exception for constants of a 3821 // fract type with a value of exactly 1; such a constant shall denote 3822 // the maximal value for the type. 3823 --Val; 3824 else if (Val.ugt(MaxVal) || Overflowed) 3825 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3826 3827 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3828 Tok.getLocation(), scale); 3829 } else if (Literal.isFloatingLiteral()) { 3830 QualType Ty; 3831 if (Literal.isHalf){ 3832 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3833 Ty = Context.HalfTy; 3834 else { 3835 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3836 return ExprError(); 3837 } 3838 } else if (Literal.isFloat) 3839 Ty = Context.FloatTy; 3840 else if (Literal.isLong) 3841 Ty = Context.LongDoubleTy; 3842 else if (Literal.isFloat16) 3843 Ty = Context.Float16Ty; 3844 else if (Literal.isFloat128) 3845 Ty = Context.Float128Ty; 3846 else 3847 Ty = Context.DoubleTy; 3848 3849 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3850 3851 if (Ty == Context.DoubleTy) { 3852 if (getLangOpts().SinglePrecisionConstants) { 3853 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3854 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3855 } 3856 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3857 "cl_khr_fp64", getLangOpts())) { 3858 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3859 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) 3860 << (getLangOpts().getOpenCLCompatibleVersion() >= 300); 3861 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3862 } 3863 } 3864 } else if (!Literal.isIntegerLiteral()) { 3865 return ExprError(); 3866 } else { 3867 QualType Ty; 3868 3869 // 'long long' is a C99 or C++11 feature. 3870 if (!getLangOpts().C99 && Literal.isLongLong) { 3871 if (getLangOpts().CPlusPlus) 3872 Diag(Tok.getLocation(), 3873 getLangOpts().CPlusPlus11 ? 3874 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3875 else 3876 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3877 } 3878 3879 // 'z/uz' literals are a C++2b feature. 3880 if (Literal.isSizeT) 3881 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3882 ? getLangOpts().CPlusPlus2b 3883 ? diag::warn_cxx20_compat_size_t_suffix 3884 : diag::ext_cxx2b_size_t_suffix 3885 : diag::err_cxx2b_size_t_suffix); 3886 3887 // Get the value in the widest-possible width. 3888 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3889 llvm::APInt ResultVal(MaxWidth, 0); 3890 3891 if (Literal.GetIntegerValue(ResultVal)) { 3892 // If this value didn't fit into uintmax_t, error and force to ull. 3893 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3894 << /* Unsigned */ 1; 3895 Ty = Context.UnsignedLongLongTy; 3896 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3897 "long long is not intmax_t?"); 3898 } else { 3899 // If this value fits into a ULL, try to figure out what else it fits into 3900 // according to the rules of C99 6.4.4.1p5. 3901 3902 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3903 // be an unsigned int. 3904 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3905 3906 // Check from smallest to largest, picking the smallest type we can. 3907 unsigned Width = 0; 3908 3909 // Microsoft specific integer suffixes are explicitly sized. 3910 if (Literal.MicrosoftInteger) { 3911 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3912 Width = 8; 3913 Ty = Context.CharTy; 3914 } else { 3915 Width = Literal.MicrosoftInteger; 3916 Ty = Context.getIntTypeForBitwidth(Width, 3917 /*Signed=*/!Literal.isUnsigned); 3918 } 3919 } 3920 3921 // Check C++2b size_t literals. 3922 if (Literal.isSizeT) { 3923 assert(!Literal.MicrosoftInteger && 3924 "size_t literals can't be Microsoft literals"); 3925 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 3926 Context.getTargetInfo().getSizeType()); 3927 3928 // Does it fit in size_t? 3929 if (ResultVal.isIntN(SizeTSize)) { 3930 // Does it fit in ssize_t? 3931 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 3932 Ty = Context.getSignedSizeType(); 3933 else if (AllowUnsigned) 3934 Ty = Context.getSizeType(); 3935 Width = SizeTSize; 3936 } 3937 } 3938 3939 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 3940 !Literal.isSizeT) { 3941 // Are int/unsigned possibilities? 3942 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3943 3944 // Does it fit in a unsigned int? 3945 if (ResultVal.isIntN(IntSize)) { 3946 // Does it fit in a signed int? 3947 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3948 Ty = Context.IntTy; 3949 else if (AllowUnsigned) 3950 Ty = Context.UnsignedIntTy; 3951 Width = IntSize; 3952 } 3953 } 3954 3955 // Are long/unsigned long possibilities? 3956 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 3957 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3958 3959 // Does it fit in a unsigned long? 3960 if (ResultVal.isIntN(LongSize)) { 3961 // Does it fit in a signed long? 3962 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3963 Ty = Context.LongTy; 3964 else if (AllowUnsigned) 3965 Ty = Context.UnsignedLongTy; 3966 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3967 // is compatible. 3968 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3969 const unsigned LongLongSize = 3970 Context.getTargetInfo().getLongLongWidth(); 3971 Diag(Tok.getLocation(), 3972 getLangOpts().CPlusPlus 3973 ? Literal.isLong 3974 ? diag::warn_old_implicitly_unsigned_long_cxx 3975 : /*C++98 UB*/ diag:: 3976 ext_old_implicitly_unsigned_long_cxx 3977 : diag::warn_old_implicitly_unsigned_long) 3978 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3979 : /*will be ill-formed*/ 1); 3980 Ty = Context.UnsignedLongTy; 3981 } 3982 Width = LongSize; 3983 } 3984 } 3985 3986 // Check long long if needed. 3987 if (Ty.isNull() && !Literal.isSizeT) { 3988 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3989 3990 // Does it fit in a unsigned long long? 3991 if (ResultVal.isIntN(LongLongSize)) { 3992 // Does it fit in a signed long long? 3993 // To be compatible with MSVC, hex integer literals ending with the 3994 // LL or i64 suffix are always signed in Microsoft mode. 3995 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3996 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3997 Ty = Context.LongLongTy; 3998 else if (AllowUnsigned) 3999 Ty = Context.UnsignedLongLongTy; 4000 Width = LongLongSize; 4001 } 4002 } 4003 4004 // If we still couldn't decide a type, we either have 'size_t' literal 4005 // that is out of range, or a decimal literal that does not fit in a 4006 // signed long long and has no U suffix. 4007 if (Ty.isNull()) { 4008 if (Literal.isSizeT) 4009 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 4010 << Literal.isUnsigned; 4011 else 4012 Diag(Tok.getLocation(), 4013 diag::ext_integer_literal_too_large_for_signed); 4014 Ty = Context.UnsignedLongLongTy; 4015 Width = Context.getTargetInfo().getLongLongWidth(); 4016 } 4017 4018 if (ResultVal.getBitWidth() != Width) 4019 ResultVal = ResultVal.trunc(Width); 4020 } 4021 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 4022 } 4023 4024 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 4025 if (Literal.isImaginary) { 4026 Res = new (Context) ImaginaryLiteral(Res, 4027 Context.getComplexType(Res->getType())); 4028 4029 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4030 } 4031 return Res; 4032 } 4033 4034 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4035 assert(E && "ActOnParenExpr() missing expr"); 4036 QualType ExprTy = E->getType(); 4037 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && 4038 !E->isLValue() && ExprTy->hasFloatingRepresentation()) 4039 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); 4040 return new (Context) ParenExpr(L, R, E); 4041 } 4042 4043 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4044 SourceLocation Loc, 4045 SourceRange ArgRange) { 4046 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4047 // scalar or vector data type argument..." 4048 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4049 // type (C99 6.2.5p18) or void. 4050 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4051 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4052 << T << ArgRange; 4053 return true; 4054 } 4055 4056 assert((T->isVoidType() || !T->isIncompleteType()) && 4057 "Scalar types should always be complete"); 4058 return false; 4059 } 4060 4061 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4062 SourceLocation Loc, 4063 SourceRange ArgRange, 4064 UnaryExprOrTypeTrait TraitKind) { 4065 // Invalid types must be hard errors for SFINAE in C++. 4066 if (S.LangOpts.CPlusPlus) 4067 return true; 4068 4069 // C99 6.5.3.4p1: 4070 if (T->isFunctionType() && 4071 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4072 TraitKind == UETT_PreferredAlignOf)) { 4073 // sizeof(function)/alignof(function) is allowed as an extension. 4074 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4075 << getTraitSpelling(TraitKind) << ArgRange; 4076 return false; 4077 } 4078 4079 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4080 // this is an error (OpenCL v1.1 s6.3.k) 4081 if (T->isVoidType()) { 4082 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4083 : diag::ext_sizeof_alignof_void_type; 4084 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4085 return false; 4086 } 4087 4088 return true; 4089 } 4090 4091 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4092 SourceLocation Loc, 4093 SourceRange ArgRange, 4094 UnaryExprOrTypeTrait TraitKind) { 4095 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4096 // runtime doesn't allow it. 4097 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4098 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4099 << T << (TraitKind == UETT_SizeOf) 4100 << ArgRange; 4101 return true; 4102 } 4103 4104 return false; 4105 } 4106 4107 /// Check whether E is a pointer from a decayed array type (the decayed 4108 /// pointer type is equal to T) and emit a warning if it is. 4109 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4110 Expr *E) { 4111 // Don't warn if the operation changed the type. 4112 if (T != E->getType()) 4113 return; 4114 4115 // Now look for array decays. 4116 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4117 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4118 return; 4119 4120 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4121 << ICE->getType() 4122 << ICE->getSubExpr()->getType(); 4123 } 4124 4125 /// Check the constraints on expression operands to unary type expression 4126 /// and type traits. 4127 /// 4128 /// Completes any types necessary and validates the constraints on the operand 4129 /// expression. The logic mostly mirrors the type-based overload, but may modify 4130 /// the expression as it completes the type for that expression through template 4131 /// instantiation, etc. 4132 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4133 UnaryExprOrTypeTrait ExprKind) { 4134 QualType ExprTy = E->getType(); 4135 assert(!ExprTy->isReferenceType()); 4136 4137 bool IsUnevaluatedOperand = 4138 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4139 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4140 if (IsUnevaluatedOperand) { 4141 ExprResult Result = CheckUnevaluatedOperand(E); 4142 if (Result.isInvalid()) 4143 return true; 4144 E = Result.get(); 4145 } 4146 4147 // The operand for sizeof and alignof is in an unevaluated expression context, 4148 // so side effects could result in unintended consequences. 4149 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4150 // used to build SFINAE gadgets. 4151 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4152 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4153 !E->isInstantiationDependent() && 4154 E->HasSideEffects(Context, false)) 4155 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4156 4157 if (ExprKind == UETT_VecStep) 4158 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4159 E->getSourceRange()); 4160 4161 // Explicitly list some types as extensions. 4162 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4163 E->getSourceRange(), ExprKind)) 4164 return false; 4165 4166 // 'alignof' applied to an expression only requires the base element type of 4167 // the expression to be complete. 'sizeof' requires the expression's type to 4168 // be complete (and will attempt to complete it if it's an array of unknown 4169 // bound). 4170 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4171 if (RequireCompleteSizedType( 4172 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4173 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4174 getTraitSpelling(ExprKind), E->getSourceRange())) 4175 return true; 4176 } else { 4177 if (RequireCompleteSizedExprType( 4178 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4179 getTraitSpelling(ExprKind), E->getSourceRange())) 4180 return true; 4181 } 4182 4183 // Completing the expression's type may have changed it. 4184 ExprTy = E->getType(); 4185 assert(!ExprTy->isReferenceType()); 4186 4187 if (ExprTy->isFunctionType()) { 4188 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4189 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4190 return true; 4191 } 4192 4193 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4194 E->getSourceRange(), ExprKind)) 4195 return true; 4196 4197 if (ExprKind == UETT_SizeOf) { 4198 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4199 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4200 QualType OType = PVD->getOriginalType(); 4201 QualType Type = PVD->getType(); 4202 if (Type->isPointerType() && OType->isArrayType()) { 4203 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4204 << Type << OType; 4205 Diag(PVD->getLocation(), diag::note_declared_at); 4206 } 4207 } 4208 } 4209 4210 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4211 // decays into a pointer and returns an unintended result. This is most 4212 // likely a typo for "sizeof(array) op x". 4213 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4214 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4215 BO->getLHS()); 4216 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4217 BO->getRHS()); 4218 } 4219 } 4220 4221 return false; 4222 } 4223 4224 /// Check the constraints on operands to unary expression and type 4225 /// traits. 4226 /// 4227 /// This will complete any types necessary, and validate the various constraints 4228 /// on those operands. 4229 /// 4230 /// The UsualUnaryConversions() function is *not* called by this routine. 4231 /// C99 6.3.2.1p[2-4] all state: 4232 /// Except when it is the operand of the sizeof operator ... 4233 /// 4234 /// C++ [expr.sizeof]p4 4235 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4236 /// standard conversions are not applied to the operand of sizeof. 4237 /// 4238 /// This policy is followed for all of the unary trait expressions. 4239 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4240 SourceLocation OpLoc, 4241 SourceRange ExprRange, 4242 UnaryExprOrTypeTrait ExprKind) { 4243 if (ExprType->isDependentType()) 4244 return false; 4245 4246 // C++ [expr.sizeof]p2: 4247 // When applied to a reference or a reference type, the result 4248 // is the size of the referenced type. 4249 // C++11 [expr.alignof]p3: 4250 // When alignof is applied to a reference type, the result 4251 // shall be the alignment of the referenced type. 4252 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4253 ExprType = Ref->getPointeeType(); 4254 4255 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4256 // When alignof or _Alignof is applied to an array type, the result 4257 // is the alignment of the element type. 4258 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4259 ExprKind == UETT_OpenMPRequiredSimdAlign) 4260 ExprType = Context.getBaseElementType(ExprType); 4261 4262 if (ExprKind == UETT_VecStep) 4263 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4264 4265 // Explicitly list some types as extensions. 4266 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4267 ExprKind)) 4268 return false; 4269 4270 if (RequireCompleteSizedType( 4271 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4272 getTraitSpelling(ExprKind), ExprRange)) 4273 return true; 4274 4275 if (ExprType->isFunctionType()) { 4276 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4277 << getTraitSpelling(ExprKind) << ExprRange; 4278 return true; 4279 } 4280 4281 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4282 ExprKind)) 4283 return true; 4284 4285 return false; 4286 } 4287 4288 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4289 // Cannot know anything else if the expression is dependent. 4290 if (E->isTypeDependent()) 4291 return false; 4292 4293 if (E->getObjectKind() == OK_BitField) { 4294 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4295 << 1 << E->getSourceRange(); 4296 return true; 4297 } 4298 4299 ValueDecl *D = nullptr; 4300 Expr *Inner = E->IgnoreParens(); 4301 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4302 D = DRE->getDecl(); 4303 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4304 D = ME->getMemberDecl(); 4305 } 4306 4307 // If it's a field, require the containing struct to have a 4308 // complete definition so that we can compute the layout. 4309 // 4310 // This can happen in C++11 onwards, either by naming the member 4311 // in a way that is not transformed into a member access expression 4312 // (in an unevaluated operand, for instance), or by naming the member 4313 // in a trailing-return-type. 4314 // 4315 // For the record, since __alignof__ on expressions is a GCC 4316 // extension, GCC seems to permit this but always gives the 4317 // nonsensical answer 0. 4318 // 4319 // We don't really need the layout here --- we could instead just 4320 // directly check for all the appropriate alignment-lowing 4321 // attributes --- but that would require duplicating a lot of 4322 // logic that just isn't worth duplicating for such a marginal 4323 // use-case. 4324 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4325 // Fast path this check, since we at least know the record has a 4326 // definition if we can find a member of it. 4327 if (!FD->getParent()->isCompleteDefinition()) { 4328 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4329 << E->getSourceRange(); 4330 return true; 4331 } 4332 4333 // Otherwise, if it's a field, and the field doesn't have 4334 // reference type, then it must have a complete type (or be a 4335 // flexible array member, which we explicitly want to 4336 // white-list anyway), which makes the following checks trivial. 4337 if (!FD->getType()->isReferenceType()) 4338 return false; 4339 } 4340 4341 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4342 } 4343 4344 bool Sema::CheckVecStepExpr(Expr *E) { 4345 E = E->IgnoreParens(); 4346 4347 // Cannot know anything else if the expression is dependent. 4348 if (E->isTypeDependent()) 4349 return false; 4350 4351 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4352 } 4353 4354 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4355 CapturingScopeInfo *CSI) { 4356 assert(T->isVariablyModifiedType()); 4357 assert(CSI != nullptr); 4358 4359 // We're going to walk down into the type and look for VLA expressions. 4360 do { 4361 const Type *Ty = T.getTypePtr(); 4362 switch (Ty->getTypeClass()) { 4363 #define TYPE(Class, Base) 4364 #define ABSTRACT_TYPE(Class, Base) 4365 #define NON_CANONICAL_TYPE(Class, Base) 4366 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4367 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4368 #include "clang/AST/TypeNodes.inc" 4369 T = QualType(); 4370 break; 4371 // These types are never variably-modified. 4372 case Type::Builtin: 4373 case Type::Complex: 4374 case Type::Vector: 4375 case Type::ExtVector: 4376 case Type::ConstantMatrix: 4377 case Type::Record: 4378 case Type::Enum: 4379 case Type::Elaborated: 4380 case Type::TemplateSpecialization: 4381 case Type::ObjCObject: 4382 case Type::ObjCInterface: 4383 case Type::ObjCObjectPointer: 4384 case Type::ObjCTypeParam: 4385 case Type::Pipe: 4386 case Type::ExtInt: 4387 llvm_unreachable("type class is never variably-modified!"); 4388 case Type::Adjusted: 4389 T = cast<AdjustedType>(Ty)->getOriginalType(); 4390 break; 4391 case Type::Decayed: 4392 T = cast<DecayedType>(Ty)->getPointeeType(); 4393 break; 4394 case Type::Pointer: 4395 T = cast<PointerType>(Ty)->getPointeeType(); 4396 break; 4397 case Type::BlockPointer: 4398 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4399 break; 4400 case Type::LValueReference: 4401 case Type::RValueReference: 4402 T = cast<ReferenceType>(Ty)->getPointeeType(); 4403 break; 4404 case Type::MemberPointer: 4405 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4406 break; 4407 case Type::ConstantArray: 4408 case Type::IncompleteArray: 4409 // Losing element qualification here is fine. 4410 T = cast<ArrayType>(Ty)->getElementType(); 4411 break; 4412 case Type::VariableArray: { 4413 // Losing element qualification here is fine. 4414 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4415 4416 // Unknown size indication requires no size computation. 4417 // Otherwise, evaluate and record it. 4418 auto Size = VAT->getSizeExpr(); 4419 if (Size && !CSI->isVLATypeCaptured(VAT) && 4420 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4421 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4422 4423 T = VAT->getElementType(); 4424 break; 4425 } 4426 case Type::FunctionProto: 4427 case Type::FunctionNoProto: 4428 T = cast<FunctionType>(Ty)->getReturnType(); 4429 break; 4430 case Type::Paren: 4431 case Type::TypeOf: 4432 case Type::UnaryTransform: 4433 case Type::Attributed: 4434 case Type::SubstTemplateTypeParm: 4435 case Type::MacroQualified: 4436 // Keep walking after single level desugaring. 4437 T = T.getSingleStepDesugaredType(Context); 4438 break; 4439 case Type::Typedef: 4440 T = cast<TypedefType>(Ty)->desugar(); 4441 break; 4442 case Type::Decltype: 4443 T = cast<DecltypeType>(Ty)->desugar(); 4444 break; 4445 case Type::Auto: 4446 case Type::DeducedTemplateSpecialization: 4447 T = cast<DeducedType>(Ty)->getDeducedType(); 4448 break; 4449 case Type::TypeOfExpr: 4450 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4451 break; 4452 case Type::Atomic: 4453 T = cast<AtomicType>(Ty)->getValueType(); 4454 break; 4455 } 4456 } while (!T.isNull() && T->isVariablyModifiedType()); 4457 } 4458 4459 /// Build a sizeof or alignof expression given a type operand. 4460 ExprResult 4461 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4462 SourceLocation OpLoc, 4463 UnaryExprOrTypeTrait ExprKind, 4464 SourceRange R) { 4465 if (!TInfo) 4466 return ExprError(); 4467 4468 QualType T = TInfo->getType(); 4469 4470 if (!T->isDependentType() && 4471 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4472 return ExprError(); 4473 4474 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4475 if (auto *TT = T->getAs<TypedefType>()) { 4476 for (auto I = FunctionScopes.rbegin(), 4477 E = std::prev(FunctionScopes.rend()); 4478 I != E; ++I) { 4479 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4480 if (CSI == nullptr) 4481 break; 4482 DeclContext *DC = nullptr; 4483 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4484 DC = LSI->CallOperator; 4485 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4486 DC = CRSI->TheCapturedDecl; 4487 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4488 DC = BSI->TheDecl; 4489 if (DC) { 4490 if (DC->containsDecl(TT->getDecl())) 4491 break; 4492 captureVariablyModifiedType(Context, T, CSI); 4493 } 4494 } 4495 } 4496 } 4497 4498 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4499 return new (Context) UnaryExprOrTypeTraitExpr( 4500 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4501 } 4502 4503 /// Build a sizeof or alignof expression given an expression 4504 /// operand. 4505 ExprResult 4506 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4507 UnaryExprOrTypeTrait ExprKind) { 4508 ExprResult PE = CheckPlaceholderExpr(E); 4509 if (PE.isInvalid()) 4510 return ExprError(); 4511 4512 E = PE.get(); 4513 4514 // Verify that the operand is valid. 4515 bool isInvalid = false; 4516 if (E->isTypeDependent()) { 4517 // Delay type-checking for type-dependent expressions. 4518 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4519 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4520 } else if (ExprKind == UETT_VecStep) { 4521 isInvalid = CheckVecStepExpr(E); 4522 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4523 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4524 isInvalid = true; 4525 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4526 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4527 isInvalid = true; 4528 } else { 4529 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4530 } 4531 4532 if (isInvalid) 4533 return ExprError(); 4534 4535 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4536 PE = TransformToPotentiallyEvaluated(E); 4537 if (PE.isInvalid()) return ExprError(); 4538 E = PE.get(); 4539 } 4540 4541 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4542 return new (Context) UnaryExprOrTypeTraitExpr( 4543 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4544 } 4545 4546 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4547 /// expr and the same for @c alignof and @c __alignof 4548 /// Note that the ArgRange is invalid if isType is false. 4549 ExprResult 4550 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4551 UnaryExprOrTypeTrait ExprKind, bool IsType, 4552 void *TyOrEx, SourceRange ArgRange) { 4553 // If error parsing type, ignore. 4554 if (!TyOrEx) return ExprError(); 4555 4556 if (IsType) { 4557 TypeSourceInfo *TInfo; 4558 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4559 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4560 } 4561 4562 Expr *ArgEx = (Expr *)TyOrEx; 4563 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4564 return Result; 4565 } 4566 4567 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4568 bool IsReal) { 4569 if (V.get()->isTypeDependent()) 4570 return S.Context.DependentTy; 4571 4572 // _Real and _Imag are only l-values for normal l-values. 4573 if (V.get()->getObjectKind() != OK_Ordinary) { 4574 V = S.DefaultLvalueConversion(V.get()); 4575 if (V.isInvalid()) 4576 return QualType(); 4577 } 4578 4579 // These operators return the element type of a complex type. 4580 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4581 return CT->getElementType(); 4582 4583 // Otherwise they pass through real integer and floating point types here. 4584 if (V.get()->getType()->isArithmeticType()) 4585 return V.get()->getType(); 4586 4587 // Test for placeholders. 4588 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4589 if (PR.isInvalid()) return QualType(); 4590 if (PR.get() != V.get()) { 4591 V = PR; 4592 return CheckRealImagOperand(S, V, Loc, IsReal); 4593 } 4594 4595 // Reject anything else. 4596 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4597 << (IsReal ? "__real" : "__imag"); 4598 return QualType(); 4599 } 4600 4601 4602 4603 ExprResult 4604 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4605 tok::TokenKind Kind, Expr *Input) { 4606 UnaryOperatorKind Opc; 4607 switch (Kind) { 4608 default: llvm_unreachable("Unknown unary op!"); 4609 case tok::plusplus: Opc = UO_PostInc; break; 4610 case tok::minusminus: Opc = UO_PostDec; break; 4611 } 4612 4613 // Since this might is a postfix expression, get rid of ParenListExprs. 4614 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4615 if (Result.isInvalid()) return ExprError(); 4616 Input = Result.get(); 4617 4618 return BuildUnaryOp(S, OpLoc, Opc, Input); 4619 } 4620 4621 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4622 /// 4623 /// \return true on error 4624 static bool checkArithmeticOnObjCPointer(Sema &S, 4625 SourceLocation opLoc, 4626 Expr *op) { 4627 assert(op->getType()->isObjCObjectPointerType()); 4628 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4629 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4630 return false; 4631 4632 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4633 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4634 << op->getSourceRange(); 4635 return true; 4636 } 4637 4638 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4639 auto *BaseNoParens = Base->IgnoreParens(); 4640 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4641 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4642 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4643 } 4644 4645 ExprResult 4646 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4647 Expr *idx, SourceLocation rbLoc) { 4648 if (base && !base->getType().isNull() && 4649 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4650 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4651 SourceLocation(), /*Length*/ nullptr, 4652 /*Stride=*/nullptr, rbLoc); 4653 4654 // Since this might be a postfix expression, get rid of ParenListExprs. 4655 if (isa<ParenListExpr>(base)) { 4656 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4657 if (result.isInvalid()) return ExprError(); 4658 base = result.get(); 4659 } 4660 4661 // Check if base and idx form a MatrixSubscriptExpr. 4662 // 4663 // Helper to check for comma expressions, which are not allowed as indices for 4664 // matrix subscript expressions. 4665 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4666 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4667 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4668 << SourceRange(base->getBeginLoc(), rbLoc); 4669 return true; 4670 } 4671 return false; 4672 }; 4673 // The matrix subscript operator ([][])is considered a single operator. 4674 // Separating the index expressions by parenthesis is not allowed. 4675 if (base->getType()->isSpecificPlaceholderType( 4676 BuiltinType::IncompleteMatrixIdx) && 4677 !isa<MatrixSubscriptExpr>(base)) { 4678 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4679 << SourceRange(base->getBeginLoc(), rbLoc); 4680 return ExprError(); 4681 } 4682 // If the base is a MatrixSubscriptExpr, try to create a new 4683 // MatrixSubscriptExpr. 4684 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4685 if (matSubscriptE) { 4686 if (CheckAndReportCommaError(idx)) 4687 return ExprError(); 4688 4689 assert(matSubscriptE->isIncomplete() && 4690 "base has to be an incomplete matrix subscript"); 4691 return CreateBuiltinMatrixSubscriptExpr( 4692 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4693 } 4694 4695 // Handle any non-overload placeholder types in the base and index 4696 // expressions. We can't handle overloads here because the other 4697 // operand might be an overloadable type, in which case the overload 4698 // resolution for the operator overload should get the first crack 4699 // at the overload. 4700 bool IsMSPropertySubscript = false; 4701 if (base->getType()->isNonOverloadPlaceholderType()) { 4702 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4703 if (!IsMSPropertySubscript) { 4704 ExprResult result = CheckPlaceholderExpr(base); 4705 if (result.isInvalid()) 4706 return ExprError(); 4707 base = result.get(); 4708 } 4709 } 4710 4711 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4712 if (base->getType()->isMatrixType()) { 4713 if (CheckAndReportCommaError(idx)) 4714 return ExprError(); 4715 4716 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4717 } 4718 4719 // A comma-expression as the index is deprecated in C++2a onwards. 4720 if (getLangOpts().CPlusPlus20 && 4721 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4722 (isa<CXXOperatorCallExpr>(idx) && 4723 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4724 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4725 << SourceRange(base->getBeginLoc(), rbLoc); 4726 } 4727 4728 if (idx->getType()->isNonOverloadPlaceholderType()) { 4729 ExprResult result = CheckPlaceholderExpr(idx); 4730 if (result.isInvalid()) return ExprError(); 4731 idx = result.get(); 4732 } 4733 4734 // Build an unanalyzed expression if either operand is type-dependent. 4735 if (getLangOpts().CPlusPlus && 4736 (base->isTypeDependent() || idx->isTypeDependent())) { 4737 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4738 VK_LValue, OK_Ordinary, rbLoc); 4739 } 4740 4741 // MSDN, property (C++) 4742 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4743 // This attribute can also be used in the declaration of an empty array in a 4744 // class or structure definition. For example: 4745 // __declspec(property(get=GetX, put=PutX)) int x[]; 4746 // The above statement indicates that x[] can be used with one or more array 4747 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4748 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4749 if (IsMSPropertySubscript) { 4750 // Build MS property subscript expression if base is MS property reference 4751 // or MS property subscript. 4752 return new (Context) MSPropertySubscriptExpr( 4753 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4754 } 4755 4756 // Use C++ overloaded-operator rules if either operand has record 4757 // type. The spec says to do this if either type is *overloadable*, 4758 // but enum types can't declare subscript operators or conversion 4759 // operators, so there's nothing interesting for overload resolution 4760 // to do if there aren't any record types involved. 4761 // 4762 // ObjC pointers have their own subscripting logic that is not tied 4763 // to overload resolution and so should not take this path. 4764 if (getLangOpts().CPlusPlus && 4765 (base->getType()->isRecordType() || 4766 (!base->getType()->isObjCObjectPointerType() && 4767 idx->getType()->isRecordType()))) { 4768 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4769 } 4770 4771 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4772 4773 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4774 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4775 4776 return Res; 4777 } 4778 4779 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4780 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4781 InitializationKind Kind = 4782 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4783 InitializationSequence InitSeq(*this, Entity, Kind, E); 4784 return InitSeq.Perform(*this, Entity, Kind, E); 4785 } 4786 4787 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4788 Expr *ColumnIdx, 4789 SourceLocation RBLoc) { 4790 ExprResult BaseR = CheckPlaceholderExpr(Base); 4791 if (BaseR.isInvalid()) 4792 return BaseR; 4793 Base = BaseR.get(); 4794 4795 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4796 if (RowR.isInvalid()) 4797 return RowR; 4798 RowIdx = RowR.get(); 4799 4800 if (!ColumnIdx) 4801 return new (Context) MatrixSubscriptExpr( 4802 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4803 4804 // Build an unanalyzed expression if any of the operands is type-dependent. 4805 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4806 ColumnIdx->isTypeDependent()) 4807 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4808 Context.DependentTy, RBLoc); 4809 4810 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4811 if (ColumnR.isInvalid()) 4812 return ColumnR; 4813 ColumnIdx = ColumnR.get(); 4814 4815 // Check that IndexExpr is an integer expression. If it is a constant 4816 // expression, check that it is less than Dim (= the number of elements in the 4817 // corresponding dimension). 4818 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4819 bool IsColumnIdx) -> Expr * { 4820 if (!IndexExpr->getType()->isIntegerType() && 4821 !IndexExpr->isTypeDependent()) { 4822 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4823 << IsColumnIdx; 4824 return nullptr; 4825 } 4826 4827 if (Optional<llvm::APSInt> Idx = 4828 IndexExpr->getIntegerConstantExpr(Context)) { 4829 if ((*Idx < 0 || *Idx >= Dim)) { 4830 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4831 << IsColumnIdx << Dim; 4832 return nullptr; 4833 } 4834 } 4835 4836 ExprResult ConvExpr = 4837 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4838 assert(!ConvExpr.isInvalid() && 4839 "should be able to convert any integer type to size type"); 4840 return ConvExpr.get(); 4841 }; 4842 4843 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4844 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4845 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4846 if (!RowIdx || !ColumnIdx) 4847 return ExprError(); 4848 4849 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4850 MTy->getElementType(), RBLoc); 4851 } 4852 4853 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4854 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4855 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4856 4857 // For expressions like `&(*s).b`, the base is recorded and what should be 4858 // checked. 4859 const MemberExpr *Member = nullptr; 4860 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4861 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4862 4863 LastRecord.PossibleDerefs.erase(StrippedExpr); 4864 } 4865 4866 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4867 if (isUnevaluatedContext()) 4868 return; 4869 4870 QualType ResultTy = E->getType(); 4871 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4872 4873 // Bail if the element is an array since it is not memory access. 4874 if (isa<ArrayType>(ResultTy)) 4875 return; 4876 4877 if (ResultTy->hasAttr(attr::NoDeref)) { 4878 LastRecord.PossibleDerefs.insert(E); 4879 return; 4880 } 4881 4882 // Check if the base type is a pointer to a member access of a struct 4883 // marked with noderef. 4884 const Expr *Base = E->getBase(); 4885 QualType BaseTy = Base->getType(); 4886 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4887 // Not a pointer access 4888 return; 4889 4890 const MemberExpr *Member = nullptr; 4891 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4892 Member->isArrow()) 4893 Base = Member->getBase(); 4894 4895 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4896 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4897 LastRecord.PossibleDerefs.insert(E); 4898 } 4899 } 4900 4901 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4902 Expr *LowerBound, 4903 SourceLocation ColonLocFirst, 4904 SourceLocation ColonLocSecond, 4905 Expr *Length, Expr *Stride, 4906 SourceLocation RBLoc) { 4907 if (Base->getType()->isPlaceholderType() && 4908 !Base->getType()->isSpecificPlaceholderType( 4909 BuiltinType::OMPArraySection)) { 4910 ExprResult Result = CheckPlaceholderExpr(Base); 4911 if (Result.isInvalid()) 4912 return ExprError(); 4913 Base = Result.get(); 4914 } 4915 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4916 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4917 if (Result.isInvalid()) 4918 return ExprError(); 4919 Result = DefaultLvalueConversion(Result.get()); 4920 if (Result.isInvalid()) 4921 return ExprError(); 4922 LowerBound = Result.get(); 4923 } 4924 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4925 ExprResult Result = CheckPlaceholderExpr(Length); 4926 if (Result.isInvalid()) 4927 return ExprError(); 4928 Result = DefaultLvalueConversion(Result.get()); 4929 if (Result.isInvalid()) 4930 return ExprError(); 4931 Length = Result.get(); 4932 } 4933 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4934 ExprResult Result = CheckPlaceholderExpr(Stride); 4935 if (Result.isInvalid()) 4936 return ExprError(); 4937 Result = DefaultLvalueConversion(Result.get()); 4938 if (Result.isInvalid()) 4939 return ExprError(); 4940 Stride = Result.get(); 4941 } 4942 4943 // Build an unanalyzed expression if either operand is type-dependent. 4944 if (Base->isTypeDependent() || 4945 (LowerBound && 4946 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4947 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4948 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4949 return new (Context) OMPArraySectionExpr( 4950 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4951 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4952 } 4953 4954 // Perform default conversions. 4955 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4956 QualType ResultTy; 4957 if (OriginalTy->isAnyPointerType()) { 4958 ResultTy = OriginalTy->getPointeeType(); 4959 } else if (OriginalTy->isArrayType()) { 4960 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4961 } else { 4962 return ExprError( 4963 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4964 << Base->getSourceRange()); 4965 } 4966 // C99 6.5.2.1p1 4967 if (LowerBound) { 4968 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4969 LowerBound); 4970 if (Res.isInvalid()) 4971 return ExprError(Diag(LowerBound->getExprLoc(), 4972 diag::err_omp_typecheck_section_not_integer) 4973 << 0 << LowerBound->getSourceRange()); 4974 LowerBound = Res.get(); 4975 4976 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4977 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4978 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4979 << 0 << LowerBound->getSourceRange(); 4980 } 4981 if (Length) { 4982 auto Res = 4983 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4984 if (Res.isInvalid()) 4985 return ExprError(Diag(Length->getExprLoc(), 4986 diag::err_omp_typecheck_section_not_integer) 4987 << 1 << Length->getSourceRange()); 4988 Length = Res.get(); 4989 4990 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4991 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4992 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4993 << 1 << Length->getSourceRange(); 4994 } 4995 if (Stride) { 4996 ExprResult Res = 4997 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 4998 if (Res.isInvalid()) 4999 return ExprError(Diag(Stride->getExprLoc(), 5000 diag::err_omp_typecheck_section_not_integer) 5001 << 1 << Stride->getSourceRange()); 5002 Stride = Res.get(); 5003 5004 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5005 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5006 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5007 << 1 << Stride->getSourceRange(); 5008 } 5009 5010 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5011 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5012 // type. Note that functions are not objects, and that (in C99 parlance) 5013 // incomplete types are not object types. 5014 if (ResultTy->isFunctionType()) { 5015 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5016 << ResultTy << Base->getSourceRange(); 5017 return ExprError(); 5018 } 5019 5020 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5021 diag::err_omp_section_incomplete_type, Base)) 5022 return ExprError(); 5023 5024 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5025 Expr::EvalResult Result; 5026 if (LowerBound->EvaluateAsInt(Result, Context)) { 5027 // OpenMP 5.0, [2.1.5 Array Sections] 5028 // The array section must be a subset of the original array. 5029 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5030 if (LowerBoundValue.isNegative()) { 5031 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5032 << LowerBound->getSourceRange(); 5033 return ExprError(); 5034 } 5035 } 5036 } 5037 5038 if (Length) { 5039 Expr::EvalResult Result; 5040 if (Length->EvaluateAsInt(Result, Context)) { 5041 // OpenMP 5.0, [2.1.5 Array Sections] 5042 // The length must evaluate to non-negative integers. 5043 llvm::APSInt LengthValue = Result.Val.getInt(); 5044 if (LengthValue.isNegative()) { 5045 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5046 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5047 << Length->getSourceRange(); 5048 return ExprError(); 5049 } 5050 } 5051 } else if (ColonLocFirst.isValid() && 5052 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5053 !OriginalTy->isVariableArrayType()))) { 5054 // OpenMP 5.0, [2.1.5 Array Sections] 5055 // When the size of the array dimension is not known, the length must be 5056 // specified explicitly. 5057 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5058 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5059 return ExprError(); 5060 } 5061 5062 if (Stride) { 5063 Expr::EvalResult Result; 5064 if (Stride->EvaluateAsInt(Result, Context)) { 5065 // OpenMP 5.0, [2.1.5 Array Sections] 5066 // The stride must evaluate to a positive integer. 5067 llvm::APSInt StrideValue = Result.Val.getInt(); 5068 if (!StrideValue.isStrictlyPositive()) { 5069 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5070 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5071 << Stride->getSourceRange(); 5072 return ExprError(); 5073 } 5074 } 5075 } 5076 5077 if (!Base->getType()->isSpecificPlaceholderType( 5078 BuiltinType::OMPArraySection)) { 5079 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5080 if (Result.isInvalid()) 5081 return ExprError(); 5082 Base = Result.get(); 5083 } 5084 return new (Context) OMPArraySectionExpr( 5085 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5086 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5087 } 5088 5089 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5090 SourceLocation RParenLoc, 5091 ArrayRef<Expr *> Dims, 5092 ArrayRef<SourceRange> Brackets) { 5093 if (Base->getType()->isPlaceholderType()) { 5094 ExprResult Result = CheckPlaceholderExpr(Base); 5095 if (Result.isInvalid()) 5096 return ExprError(); 5097 Result = DefaultLvalueConversion(Result.get()); 5098 if (Result.isInvalid()) 5099 return ExprError(); 5100 Base = Result.get(); 5101 } 5102 QualType BaseTy = Base->getType(); 5103 // Delay analysis of the types/expressions if instantiation/specialization is 5104 // required. 5105 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5106 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5107 LParenLoc, RParenLoc, Dims, Brackets); 5108 if (!BaseTy->isPointerType() || 5109 (!Base->isTypeDependent() && 5110 BaseTy->getPointeeType()->isIncompleteType())) 5111 return ExprError(Diag(Base->getExprLoc(), 5112 diag::err_omp_non_pointer_type_array_shaping_base) 5113 << Base->getSourceRange()); 5114 5115 SmallVector<Expr *, 4> NewDims; 5116 bool ErrorFound = false; 5117 for (Expr *Dim : Dims) { 5118 if (Dim->getType()->isPlaceholderType()) { 5119 ExprResult Result = CheckPlaceholderExpr(Dim); 5120 if (Result.isInvalid()) { 5121 ErrorFound = true; 5122 continue; 5123 } 5124 Result = DefaultLvalueConversion(Result.get()); 5125 if (Result.isInvalid()) { 5126 ErrorFound = true; 5127 continue; 5128 } 5129 Dim = Result.get(); 5130 } 5131 if (!Dim->isTypeDependent()) { 5132 ExprResult Result = 5133 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5134 if (Result.isInvalid()) { 5135 ErrorFound = true; 5136 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5137 << Dim->getSourceRange(); 5138 continue; 5139 } 5140 Dim = Result.get(); 5141 Expr::EvalResult EvResult; 5142 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5143 // OpenMP 5.0, [2.1.4 Array Shaping] 5144 // Each si is an integral type expression that must evaluate to a 5145 // positive integer. 5146 llvm::APSInt Value = EvResult.Val.getInt(); 5147 if (!Value.isStrictlyPositive()) { 5148 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5149 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5150 << Dim->getSourceRange(); 5151 ErrorFound = true; 5152 continue; 5153 } 5154 } 5155 } 5156 NewDims.push_back(Dim); 5157 } 5158 if (ErrorFound) 5159 return ExprError(); 5160 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5161 LParenLoc, RParenLoc, NewDims, Brackets); 5162 } 5163 5164 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5165 SourceLocation LLoc, SourceLocation RLoc, 5166 ArrayRef<OMPIteratorData> Data) { 5167 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5168 bool IsCorrect = true; 5169 for (const OMPIteratorData &D : Data) { 5170 TypeSourceInfo *TInfo = nullptr; 5171 SourceLocation StartLoc; 5172 QualType DeclTy; 5173 if (!D.Type.getAsOpaquePtr()) { 5174 // OpenMP 5.0, 2.1.6 Iterators 5175 // In an iterator-specifier, if the iterator-type is not specified then 5176 // the type of that iterator is of int type. 5177 DeclTy = Context.IntTy; 5178 StartLoc = D.DeclIdentLoc; 5179 } else { 5180 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5181 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5182 } 5183 5184 bool IsDeclTyDependent = DeclTy->isDependentType() || 5185 DeclTy->containsUnexpandedParameterPack() || 5186 DeclTy->isInstantiationDependentType(); 5187 if (!IsDeclTyDependent) { 5188 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5189 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5190 // The iterator-type must be an integral or pointer type. 5191 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5192 << DeclTy; 5193 IsCorrect = false; 5194 continue; 5195 } 5196 if (DeclTy.isConstant(Context)) { 5197 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5198 // The iterator-type must not be const qualified. 5199 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5200 << DeclTy; 5201 IsCorrect = false; 5202 continue; 5203 } 5204 } 5205 5206 // Iterator declaration. 5207 assert(D.DeclIdent && "Identifier expected."); 5208 // Always try to create iterator declarator to avoid extra error messages 5209 // about unknown declarations use. 5210 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5211 D.DeclIdent, DeclTy, TInfo, SC_None); 5212 VD->setImplicit(); 5213 if (S) { 5214 // Check for conflicting previous declaration. 5215 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5216 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5217 ForVisibleRedeclaration); 5218 Previous.suppressDiagnostics(); 5219 LookupName(Previous, S); 5220 5221 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5222 /*AllowInlineNamespace=*/false); 5223 if (!Previous.empty()) { 5224 NamedDecl *Old = Previous.getRepresentativeDecl(); 5225 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5226 Diag(Old->getLocation(), diag::note_previous_definition); 5227 } else { 5228 PushOnScopeChains(VD, S); 5229 } 5230 } else { 5231 CurContext->addDecl(VD); 5232 } 5233 Expr *Begin = D.Range.Begin; 5234 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5235 ExprResult BeginRes = 5236 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5237 Begin = BeginRes.get(); 5238 } 5239 Expr *End = D.Range.End; 5240 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5241 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5242 End = EndRes.get(); 5243 } 5244 Expr *Step = D.Range.Step; 5245 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5246 if (!Step->getType()->isIntegralType(Context)) { 5247 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5248 << Step << Step->getSourceRange(); 5249 IsCorrect = false; 5250 continue; 5251 } 5252 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5253 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5254 // If the step expression of a range-specification equals zero, the 5255 // behavior is unspecified. 5256 if (Result && Result->isNullValue()) { 5257 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5258 << Step << Step->getSourceRange(); 5259 IsCorrect = false; 5260 continue; 5261 } 5262 } 5263 if (!Begin || !End || !IsCorrect) { 5264 IsCorrect = false; 5265 continue; 5266 } 5267 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5268 IDElem.IteratorDecl = VD; 5269 IDElem.AssignmentLoc = D.AssignLoc; 5270 IDElem.Range.Begin = Begin; 5271 IDElem.Range.End = End; 5272 IDElem.Range.Step = Step; 5273 IDElem.ColonLoc = D.ColonLoc; 5274 IDElem.SecondColonLoc = D.SecColonLoc; 5275 } 5276 if (!IsCorrect) { 5277 // Invalidate all created iterator declarations if error is found. 5278 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5279 if (Decl *ID = D.IteratorDecl) 5280 ID->setInvalidDecl(); 5281 } 5282 return ExprError(); 5283 } 5284 SmallVector<OMPIteratorHelperData, 4> Helpers; 5285 if (!CurContext->isDependentContext()) { 5286 // Build number of ityeration for each iteration range. 5287 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5288 // ((Begini-Stepi-1-Endi) / -Stepi); 5289 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5290 // (Endi - Begini) 5291 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5292 D.Range.Begin); 5293 if(!Res.isUsable()) { 5294 IsCorrect = false; 5295 continue; 5296 } 5297 ExprResult St, St1; 5298 if (D.Range.Step) { 5299 St = D.Range.Step; 5300 // (Endi - Begini) + Stepi 5301 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5302 if (!Res.isUsable()) { 5303 IsCorrect = false; 5304 continue; 5305 } 5306 // (Endi - Begini) + Stepi - 1 5307 Res = 5308 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5309 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5310 if (!Res.isUsable()) { 5311 IsCorrect = false; 5312 continue; 5313 } 5314 // ((Endi - Begini) + Stepi - 1) / Stepi 5315 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5316 if (!Res.isUsable()) { 5317 IsCorrect = false; 5318 continue; 5319 } 5320 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5321 // (Begini - Endi) 5322 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5323 D.Range.Begin, D.Range.End); 5324 if (!Res1.isUsable()) { 5325 IsCorrect = false; 5326 continue; 5327 } 5328 // (Begini - Endi) - Stepi 5329 Res1 = 5330 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5331 if (!Res1.isUsable()) { 5332 IsCorrect = false; 5333 continue; 5334 } 5335 // (Begini - Endi) - Stepi - 1 5336 Res1 = 5337 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5338 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5339 if (!Res1.isUsable()) { 5340 IsCorrect = false; 5341 continue; 5342 } 5343 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5344 Res1 = 5345 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5346 if (!Res1.isUsable()) { 5347 IsCorrect = false; 5348 continue; 5349 } 5350 // Stepi > 0. 5351 ExprResult CmpRes = 5352 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5353 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5354 if (!CmpRes.isUsable()) { 5355 IsCorrect = false; 5356 continue; 5357 } 5358 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5359 Res.get(), Res1.get()); 5360 if (!Res.isUsable()) { 5361 IsCorrect = false; 5362 continue; 5363 } 5364 } 5365 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5366 if (!Res.isUsable()) { 5367 IsCorrect = false; 5368 continue; 5369 } 5370 5371 // Build counter update. 5372 // Build counter. 5373 auto *CounterVD = 5374 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5375 D.IteratorDecl->getBeginLoc(), nullptr, 5376 Res.get()->getType(), nullptr, SC_None); 5377 CounterVD->setImplicit(); 5378 ExprResult RefRes = 5379 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5380 D.IteratorDecl->getBeginLoc()); 5381 // Build counter update. 5382 // I = Begini + counter * Stepi; 5383 ExprResult UpdateRes; 5384 if (D.Range.Step) { 5385 UpdateRes = CreateBuiltinBinOp( 5386 D.AssignmentLoc, BO_Mul, 5387 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5388 } else { 5389 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5390 } 5391 if (!UpdateRes.isUsable()) { 5392 IsCorrect = false; 5393 continue; 5394 } 5395 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5396 UpdateRes.get()); 5397 if (!UpdateRes.isUsable()) { 5398 IsCorrect = false; 5399 continue; 5400 } 5401 ExprResult VDRes = 5402 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5403 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5404 D.IteratorDecl->getBeginLoc()); 5405 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5406 UpdateRes.get()); 5407 if (!UpdateRes.isUsable()) { 5408 IsCorrect = false; 5409 continue; 5410 } 5411 UpdateRes = 5412 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5413 if (!UpdateRes.isUsable()) { 5414 IsCorrect = false; 5415 continue; 5416 } 5417 ExprResult CounterUpdateRes = 5418 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5419 if (!CounterUpdateRes.isUsable()) { 5420 IsCorrect = false; 5421 continue; 5422 } 5423 CounterUpdateRes = 5424 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5425 if (!CounterUpdateRes.isUsable()) { 5426 IsCorrect = false; 5427 continue; 5428 } 5429 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5430 HD.CounterVD = CounterVD; 5431 HD.Upper = Res.get(); 5432 HD.Update = UpdateRes.get(); 5433 HD.CounterUpdate = CounterUpdateRes.get(); 5434 } 5435 } else { 5436 Helpers.assign(ID.size(), {}); 5437 } 5438 if (!IsCorrect) { 5439 // Invalidate all created iterator declarations if error is found. 5440 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5441 if (Decl *ID = D.IteratorDecl) 5442 ID->setInvalidDecl(); 5443 } 5444 return ExprError(); 5445 } 5446 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5447 LLoc, RLoc, ID, Helpers); 5448 } 5449 5450 ExprResult 5451 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5452 Expr *Idx, SourceLocation RLoc) { 5453 Expr *LHSExp = Base; 5454 Expr *RHSExp = Idx; 5455 5456 ExprValueKind VK = VK_LValue; 5457 ExprObjectKind OK = OK_Ordinary; 5458 5459 // Per C++ core issue 1213, the result is an xvalue if either operand is 5460 // a non-lvalue array, and an lvalue otherwise. 5461 if (getLangOpts().CPlusPlus11) { 5462 for (auto *Op : {LHSExp, RHSExp}) { 5463 Op = Op->IgnoreImplicit(); 5464 if (Op->getType()->isArrayType() && !Op->isLValue()) 5465 VK = VK_XValue; 5466 } 5467 } 5468 5469 // Perform default conversions. 5470 if (!LHSExp->getType()->getAs<VectorType>()) { 5471 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5472 if (Result.isInvalid()) 5473 return ExprError(); 5474 LHSExp = Result.get(); 5475 } 5476 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5477 if (Result.isInvalid()) 5478 return ExprError(); 5479 RHSExp = Result.get(); 5480 5481 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5482 5483 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5484 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5485 // in the subscript position. As a result, we need to derive the array base 5486 // and index from the expression types. 5487 Expr *BaseExpr, *IndexExpr; 5488 QualType ResultType; 5489 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5490 BaseExpr = LHSExp; 5491 IndexExpr = RHSExp; 5492 ResultType = Context.DependentTy; 5493 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5494 BaseExpr = LHSExp; 5495 IndexExpr = RHSExp; 5496 ResultType = PTy->getPointeeType(); 5497 } else if (const ObjCObjectPointerType *PTy = 5498 LHSTy->getAs<ObjCObjectPointerType>()) { 5499 BaseExpr = LHSExp; 5500 IndexExpr = RHSExp; 5501 5502 // Use custom logic if this should be the pseudo-object subscript 5503 // expression. 5504 if (!LangOpts.isSubscriptPointerArithmetic()) 5505 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5506 nullptr); 5507 5508 ResultType = PTy->getPointeeType(); 5509 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5510 // Handle the uncommon case of "123[Ptr]". 5511 BaseExpr = RHSExp; 5512 IndexExpr = LHSExp; 5513 ResultType = PTy->getPointeeType(); 5514 } else if (const ObjCObjectPointerType *PTy = 5515 RHSTy->getAs<ObjCObjectPointerType>()) { 5516 // Handle the uncommon case of "123[Ptr]". 5517 BaseExpr = RHSExp; 5518 IndexExpr = LHSExp; 5519 ResultType = PTy->getPointeeType(); 5520 if (!LangOpts.isSubscriptPointerArithmetic()) { 5521 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5522 << ResultType << BaseExpr->getSourceRange(); 5523 return ExprError(); 5524 } 5525 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5526 BaseExpr = LHSExp; // vectors: V[123] 5527 IndexExpr = RHSExp; 5528 // We apply C++ DR1213 to vector subscripting too. 5529 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5530 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5531 if (Materialized.isInvalid()) 5532 return ExprError(); 5533 LHSExp = Materialized.get(); 5534 } 5535 VK = LHSExp->getValueKind(); 5536 if (VK != VK_PRValue) 5537 OK = OK_VectorComponent; 5538 5539 ResultType = VTy->getElementType(); 5540 QualType BaseType = BaseExpr->getType(); 5541 Qualifiers BaseQuals = BaseType.getQualifiers(); 5542 Qualifiers MemberQuals = ResultType.getQualifiers(); 5543 Qualifiers Combined = BaseQuals + MemberQuals; 5544 if (Combined != MemberQuals) 5545 ResultType = Context.getQualifiedType(ResultType, Combined); 5546 } else if (LHSTy->isArrayType()) { 5547 // If we see an array that wasn't promoted by 5548 // DefaultFunctionArrayLvalueConversion, it must be an array that 5549 // wasn't promoted because of the C90 rule that doesn't 5550 // allow promoting non-lvalue arrays. Warn, then 5551 // force the promotion here. 5552 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5553 << LHSExp->getSourceRange(); 5554 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5555 CK_ArrayToPointerDecay).get(); 5556 LHSTy = LHSExp->getType(); 5557 5558 BaseExpr = LHSExp; 5559 IndexExpr = RHSExp; 5560 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5561 } else if (RHSTy->isArrayType()) { 5562 // Same as previous, except for 123[f().a] case 5563 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5564 << RHSExp->getSourceRange(); 5565 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5566 CK_ArrayToPointerDecay).get(); 5567 RHSTy = RHSExp->getType(); 5568 5569 BaseExpr = RHSExp; 5570 IndexExpr = LHSExp; 5571 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5572 } else { 5573 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5574 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5575 } 5576 // C99 6.5.2.1p1 5577 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5578 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5579 << IndexExpr->getSourceRange()); 5580 5581 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5582 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5583 && !IndexExpr->isTypeDependent()) 5584 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5585 5586 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5587 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5588 // type. Note that Functions are not objects, and that (in C99 parlance) 5589 // incomplete types are not object types. 5590 if (ResultType->isFunctionType()) { 5591 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5592 << ResultType << BaseExpr->getSourceRange(); 5593 return ExprError(); 5594 } 5595 5596 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5597 // GNU extension: subscripting on pointer to void 5598 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5599 << BaseExpr->getSourceRange(); 5600 5601 // C forbids expressions of unqualified void type from being l-values. 5602 // See IsCForbiddenLValueType. 5603 if (!ResultType.hasQualifiers()) 5604 VK = VK_PRValue; 5605 } else if (!ResultType->isDependentType() && 5606 RequireCompleteSizedType( 5607 LLoc, ResultType, 5608 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5609 return ExprError(); 5610 5611 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 5612 !ResultType.isCForbiddenLValueType()); 5613 5614 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5615 FunctionScopes.size() > 1) { 5616 if (auto *TT = 5617 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5618 for (auto I = FunctionScopes.rbegin(), 5619 E = std::prev(FunctionScopes.rend()); 5620 I != E; ++I) { 5621 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5622 if (CSI == nullptr) 5623 break; 5624 DeclContext *DC = nullptr; 5625 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5626 DC = LSI->CallOperator; 5627 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5628 DC = CRSI->TheCapturedDecl; 5629 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5630 DC = BSI->TheDecl; 5631 if (DC) { 5632 if (DC->containsDecl(TT->getDecl())) 5633 break; 5634 captureVariablyModifiedType( 5635 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5636 } 5637 } 5638 } 5639 } 5640 5641 return new (Context) 5642 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5643 } 5644 5645 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5646 ParmVarDecl *Param) { 5647 if (Param->hasUnparsedDefaultArg()) { 5648 // If we've already cleared out the location for the default argument, 5649 // that means we're parsing it right now. 5650 if (!UnparsedDefaultArgLocs.count(Param)) { 5651 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5652 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5653 Param->setInvalidDecl(); 5654 return true; 5655 } 5656 5657 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5658 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5659 Diag(UnparsedDefaultArgLocs[Param], 5660 diag::note_default_argument_declared_here); 5661 return true; 5662 } 5663 5664 if (Param->hasUninstantiatedDefaultArg() && 5665 InstantiateDefaultArgument(CallLoc, FD, Param)) 5666 return true; 5667 5668 assert(Param->hasInit() && "default argument but no initializer?"); 5669 5670 // If the default expression creates temporaries, we need to 5671 // push them to the current stack of expression temporaries so they'll 5672 // be properly destroyed. 5673 // FIXME: We should really be rebuilding the default argument with new 5674 // bound temporaries; see the comment in PR5810. 5675 // We don't need to do that with block decls, though, because 5676 // blocks in default argument expression can never capture anything. 5677 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5678 // Set the "needs cleanups" bit regardless of whether there are 5679 // any explicit objects. 5680 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5681 5682 // Append all the objects to the cleanup list. Right now, this 5683 // should always be a no-op, because blocks in default argument 5684 // expressions should never be able to capture anything. 5685 assert(!Init->getNumObjects() && 5686 "default argument expression has capturing blocks?"); 5687 } 5688 5689 // We already type-checked the argument, so we know it works. 5690 // Just mark all of the declarations in this potentially-evaluated expression 5691 // as being "referenced". 5692 EnterExpressionEvaluationContext EvalContext( 5693 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5694 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5695 /*SkipLocalVariables=*/true); 5696 return false; 5697 } 5698 5699 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5700 FunctionDecl *FD, ParmVarDecl *Param) { 5701 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5702 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5703 return ExprError(); 5704 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5705 } 5706 5707 Sema::VariadicCallType 5708 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5709 Expr *Fn) { 5710 if (Proto && Proto->isVariadic()) { 5711 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5712 return VariadicConstructor; 5713 else if (Fn && Fn->getType()->isBlockPointerType()) 5714 return VariadicBlock; 5715 else if (FDecl) { 5716 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5717 if (Method->isInstance()) 5718 return VariadicMethod; 5719 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5720 return VariadicMethod; 5721 return VariadicFunction; 5722 } 5723 return VariadicDoesNotApply; 5724 } 5725 5726 namespace { 5727 class FunctionCallCCC final : public FunctionCallFilterCCC { 5728 public: 5729 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5730 unsigned NumArgs, MemberExpr *ME) 5731 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5732 FunctionName(FuncName) {} 5733 5734 bool ValidateCandidate(const TypoCorrection &candidate) override { 5735 if (!candidate.getCorrectionSpecifier() || 5736 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5737 return false; 5738 } 5739 5740 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5741 } 5742 5743 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5744 return std::make_unique<FunctionCallCCC>(*this); 5745 } 5746 5747 private: 5748 const IdentifierInfo *const FunctionName; 5749 }; 5750 } 5751 5752 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5753 FunctionDecl *FDecl, 5754 ArrayRef<Expr *> Args) { 5755 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5756 DeclarationName FuncName = FDecl->getDeclName(); 5757 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5758 5759 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5760 if (TypoCorrection Corrected = S.CorrectTypo( 5761 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5762 S.getScopeForContext(S.CurContext), nullptr, CCC, 5763 Sema::CTK_ErrorRecovery)) { 5764 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5765 if (Corrected.isOverloaded()) { 5766 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5767 OverloadCandidateSet::iterator Best; 5768 for (NamedDecl *CD : Corrected) { 5769 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5770 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5771 OCS); 5772 } 5773 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5774 case OR_Success: 5775 ND = Best->FoundDecl; 5776 Corrected.setCorrectionDecl(ND); 5777 break; 5778 default: 5779 break; 5780 } 5781 } 5782 ND = ND->getUnderlyingDecl(); 5783 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5784 return Corrected; 5785 } 5786 } 5787 return TypoCorrection(); 5788 } 5789 5790 /// ConvertArgumentsForCall - Converts the arguments specified in 5791 /// Args/NumArgs to the parameter types of the function FDecl with 5792 /// function prototype Proto. Call is the call expression itself, and 5793 /// Fn is the function expression. For a C++ member function, this 5794 /// routine does not attempt to convert the object argument. Returns 5795 /// true if the call is ill-formed. 5796 bool 5797 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5798 FunctionDecl *FDecl, 5799 const FunctionProtoType *Proto, 5800 ArrayRef<Expr *> Args, 5801 SourceLocation RParenLoc, 5802 bool IsExecConfig) { 5803 // Bail out early if calling a builtin with custom typechecking. 5804 if (FDecl) 5805 if (unsigned ID = FDecl->getBuiltinID()) 5806 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5807 return false; 5808 5809 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5810 // assignment, to the types of the corresponding parameter, ... 5811 unsigned NumParams = Proto->getNumParams(); 5812 bool Invalid = false; 5813 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5814 unsigned FnKind = Fn->getType()->isBlockPointerType() 5815 ? 1 /* block */ 5816 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5817 : 0 /* function */); 5818 5819 // If too few arguments are available (and we don't have default 5820 // arguments for the remaining parameters), don't make the call. 5821 if (Args.size() < NumParams) { 5822 if (Args.size() < MinArgs) { 5823 TypoCorrection TC; 5824 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5825 unsigned diag_id = 5826 MinArgs == NumParams && !Proto->isVariadic() 5827 ? diag::err_typecheck_call_too_few_args_suggest 5828 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5829 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5830 << static_cast<unsigned>(Args.size()) 5831 << TC.getCorrectionRange()); 5832 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5833 Diag(RParenLoc, 5834 MinArgs == NumParams && !Proto->isVariadic() 5835 ? diag::err_typecheck_call_too_few_args_one 5836 : diag::err_typecheck_call_too_few_args_at_least_one) 5837 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5838 else 5839 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5840 ? diag::err_typecheck_call_too_few_args 5841 : diag::err_typecheck_call_too_few_args_at_least) 5842 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5843 << Fn->getSourceRange(); 5844 5845 // Emit the location of the prototype. 5846 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5847 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5848 5849 return true; 5850 } 5851 // We reserve space for the default arguments when we create 5852 // the call expression, before calling ConvertArgumentsForCall. 5853 assert((Call->getNumArgs() == NumParams) && 5854 "We should have reserved space for the default arguments before!"); 5855 } 5856 5857 // If too many are passed and not variadic, error on the extras and drop 5858 // them. 5859 if (Args.size() > NumParams) { 5860 if (!Proto->isVariadic()) { 5861 TypoCorrection TC; 5862 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5863 unsigned diag_id = 5864 MinArgs == NumParams && !Proto->isVariadic() 5865 ? diag::err_typecheck_call_too_many_args_suggest 5866 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5867 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5868 << static_cast<unsigned>(Args.size()) 5869 << TC.getCorrectionRange()); 5870 } else if (NumParams == 1 && FDecl && 5871 FDecl->getParamDecl(0)->getDeclName()) 5872 Diag(Args[NumParams]->getBeginLoc(), 5873 MinArgs == NumParams 5874 ? diag::err_typecheck_call_too_many_args_one 5875 : diag::err_typecheck_call_too_many_args_at_most_one) 5876 << FnKind << FDecl->getParamDecl(0) 5877 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5878 << SourceRange(Args[NumParams]->getBeginLoc(), 5879 Args.back()->getEndLoc()); 5880 else 5881 Diag(Args[NumParams]->getBeginLoc(), 5882 MinArgs == NumParams 5883 ? diag::err_typecheck_call_too_many_args 5884 : diag::err_typecheck_call_too_many_args_at_most) 5885 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5886 << Fn->getSourceRange() 5887 << SourceRange(Args[NumParams]->getBeginLoc(), 5888 Args.back()->getEndLoc()); 5889 5890 // Emit the location of the prototype. 5891 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5892 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5893 5894 // This deletes the extra arguments. 5895 Call->shrinkNumArgs(NumParams); 5896 return true; 5897 } 5898 } 5899 SmallVector<Expr *, 8> AllArgs; 5900 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5901 5902 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5903 AllArgs, CallType); 5904 if (Invalid) 5905 return true; 5906 unsigned TotalNumArgs = AllArgs.size(); 5907 for (unsigned i = 0; i < TotalNumArgs; ++i) 5908 Call->setArg(i, AllArgs[i]); 5909 5910 Call->computeDependence(); 5911 return false; 5912 } 5913 5914 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5915 const FunctionProtoType *Proto, 5916 unsigned FirstParam, ArrayRef<Expr *> Args, 5917 SmallVectorImpl<Expr *> &AllArgs, 5918 VariadicCallType CallType, bool AllowExplicit, 5919 bool IsListInitialization) { 5920 unsigned NumParams = Proto->getNumParams(); 5921 bool Invalid = false; 5922 size_t ArgIx = 0; 5923 // Continue to check argument types (even if we have too few/many args). 5924 for (unsigned i = FirstParam; i < NumParams; i++) { 5925 QualType ProtoArgType = Proto->getParamType(i); 5926 5927 Expr *Arg; 5928 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5929 if (ArgIx < Args.size()) { 5930 Arg = Args[ArgIx++]; 5931 5932 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5933 diag::err_call_incomplete_argument, Arg)) 5934 return true; 5935 5936 // Strip the unbridged-cast placeholder expression off, if applicable. 5937 bool CFAudited = false; 5938 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5939 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5940 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5941 Arg = stripARCUnbridgedCast(Arg); 5942 else if (getLangOpts().ObjCAutoRefCount && 5943 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5944 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5945 CFAudited = true; 5946 5947 if (Proto->getExtParameterInfo(i).isNoEscape() && 5948 ProtoArgType->isBlockPointerType()) 5949 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5950 BE->getBlockDecl()->setDoesNotEscape(); 5951 5952 InitializedEntity Entity = 5953 Param ? InitializedEntity::InitializeParameter(Context, Param, 5954 ProtoArgType) 5955 : InitializedEntity::InitializeParameter( 5956 Context, ProtoArgType, Proto->isParamConsumed(i)); 5957 5958 // Remember that parameter belongs to a CF audited API. 5959 if (CFAudited) 5960 Entity.setParameterCFAudited(); 5961 5962 ExprResult ArgE = PerformCopyInitialization( 5963 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5964 if (ArgE.isInvalid()) 5965 return true; 5966 5967 Arg = ArgE.getAs<Expr>(); 5968 } else { 5969 assert(Param && "can't use default arguments without a known callee"); 5970 5971 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5972 if (ArgExpr.isInvalid()) 5973 return true; 5974 5975 Arg = ArgExpr.getAs<Expr>(); 5976 } 5977 5978 // Check for array bounds violations for each argument to the call. This 5979 // check only triggers warnings when the argument isn't a more complex Expr 5980 // with its own checking, such as a BinaryOperator. 5981 CheckArrayAccess(Arg); 5982 5983 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5984 CheckStaticArrayArgument(CallLoc, Param, Arg); 5985 5986 AllArgs.push_back(Arg); 5987 } 5988 5989 // If this is a variadic call, handle args passed through "...". 5990 if (CallType != VariadicDoesNotApply) { 5991 // Assume that extern "C" functions with variadic arguments that 5992 // return __unknown_anytype aren't *really* variadic. 5993 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5994 FDecl->isExternC()) { 5995 for (Expr *A : Args.slice(ArgIx)) { 5996 QualType paramType; // ignored 5997 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5998 Invalid |= arg.isInvalid(); 5999 AllArgs.push_back(arg.get()); 6000 } 6001 6002 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6003 } else { 6004 for (Expr *A : Args.slice(ArgIx)) { 6005 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6006 Invalid |= Arg.isInvalid(); 6007 AllArgs.push_back(Arg.get()); 6008 } 6009 } 6010 6011 // Check for array bounds violations. 6012 for (Expr *A : Args.slice(ArgIx)) 6013 CheckArrayAccess(A); 6014 } 6015 return Invalid; 6016 } 6017 6018 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6019 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6020 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6021 TL = DTL.getOriginalLoc(); 6022 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6023 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6024 << ATL.getLocalSourceRange(); 6025 } 6026 6027 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6028 /// array parameter, check that it is non-null, and that if it is formed by 6029 /// array-to-pointer decay, the underlying array is sufficiently large. 6030 /// 6031 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6032 /// array type derivation, then for each call to the function, the value of the 6033 /// corresponding actual argument shall provide access to the first element of 6034 /// an array with at least as many elements as specified by the size expression. 6035 void 6036 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6037 ParmVarDecl *Param, 6038 const Expr *ArgExpr) { 6039 // Static array parameters are not supported in C++. 6040 if (!Param || getLangOpts().CPlusPlus) 6041 return; 6042 6043 QualType OrigTy = Param->getOriginalType(); 6044 6045 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6046 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6047 return; 6048 6049 if (ArgExpr->isNullPointerConstant(Context, 6050 Expr::NPC_NeverValueDependent)) { 6051 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6052 DiagnoseCalleeStaticArrayParam(*this, Param); 6053 return; 6054 } 6055 6056 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6057 if (!CAT) 6058 return; 6059 6060 const ConstantArrayType *ArgCAT = 6061 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6062 if (!ArgCAT) 6063 return; 6064 6065 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6066 ArgCAT->getElementType())) { 6067 if (ArgCAT->getSize().ult(CAT->getSize())) { 6068 Diag(CallLoc, diag::warn_static_array_too_small) 6069 << ArgExpr->getSourceRange() 6070 << (unsigned)ArgCAT->getSize().getZExtValue() 6071 << (unsigned)CAT->getSize().getZExtValue() << 0; 6072 DiagnoseCalleeStaticArrayParam(*this, Param); 6073 } 6074 return; 6075 } 6076 6077 Optional<CharUnits> ArgSize = 6078 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6079 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6080 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6081 Diag(CallLoc, diag::warn_static_array_too_small) 6082 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6083 << (unsigned)ParmSize->getQuantity() << 1; 6084 DiagnoseCalleeStaticArrayParam(*this, Param); 6085 } 6086 } 6087 6088 /// Given a function expression of unknown-any type, try to rebuild it 6089 /// to have a function type. 6090 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6091 6092 /// Is the given type a placeholder that we need to lower out 6093 /// immediately during argument processing? 6094 static bool isPlaceholderToRemoveAsArg(QualType type) { 6095 // Placeholders are never sugared. 6096 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6097 if (!placeholder) return false; 6098 6099 switch (placeholder->getKind()) { 6100 // Ignore all the non-placeholder types. 6101 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6102 case BuiltinType::Id: 6103 #include "clang/Basic/OpenCLImageTypes.def" 6104 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6105 case BuiltinType::Id: 6106 #include "clang/Basic/OpenCLExtensionTypes.def" 6107 // In practice we'll never use this, since all SVE types are sugared 6108 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6109 #define SVE_TYPE(Name, Id, SingletonId) \ 6110 case BuiltinType::Id: 6111 #include "clang/Basic/AArch64SVEACLETypes.def" 6112 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6113 case BuiltinType::Id: 6114 #include "clang/Basic/PPCTypes.def" 6115 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6116 #include "clang/Basic/RISCVVTypes.def" 6117 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6118 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6119 #include "clang/AST/BuiltinTypes.def" 6120 return false; 6121 6122 // We cannot lower out overload sets; they might validly be resolved 6123 // by the call machinery. 6124 case BuiltinType::Overload: 6125 return false; 6126 6127 // Unbridged casts in ARC can be handled in some call positions and 6128 // should be left in place. 6129 case BuiltinType::ARCUnbridgedCast: 6130 return false; 6131 6132 // Pseudo-objects should be converted as soon as possible. 6133 case BuiltinType::PseudoObject: 6134 return true; 6135 6136 // The debugger mode could theoretically but currently does not try 6137 // to resolve unknown-typed arguments based on known parameter types. 6138 case BuiltinType::UnknownAny: 6139 return true; 6140 6141 // These are always invalid as call arguments and should be reported. 6142 case BuiltinType::BoundMember: 6143 case BuiltinType::BuiltinFn: 6144 case BuiltinType::IncompleteMatrixIdx: 6145 case BuiltinType::OMPArraySection: 6146 case BuiltinType::OMPArrayShaping: 6147 case BuiltinType::OMPIterator: 6148 return true; 6149 6150 } 6151 llvm_unreachable("bad builtin type kind"); 6152 } 6153 6154 /// Check an argument list for placeholders that we won't try to 6155 /// handle later. 6156 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6157 // Apply this processing to all the arguments at once instead of 6158 // dying at the first failure. 6159 bool hasInvalid = false; 6160 for (size_t i = 0, e = args.size(); i != e; i++) { 6161 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6162 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6163 if (result.isInvalid()) hasInvalid = true; 6164 else args[i] = result.get(); 6165 } 6166 } 6167 return hasInvalid; 6168 } 6169 6170 /// If a builtin function has a pointer argument with no explicit address 6171 /// space, then it should be able to accept a pointer to any address 6172 /// space as input. In order to do this, we need to replace the 6173 /// standard builtin declaration with one that uses the same address space 6174 /// as the call. 6175 /// 6176 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6177 /// it does not contain any pointer arguments without 6178 /// an address space qualifer. Otherwise the rewritten 6179 /// FunctionDecl is returned. 6180 /// TODO: Handle pointer return types. 6181 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6182 FunctionDecl *FDecl, 6183 MultiExprArg ArgExprs) { 6184 6185 QualType DeclType = FDecl->getType(); 6186 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6187 6188 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6189 ArgExprs.size() < FT->getNumParams()) 6190 return nullptr; 6191 6192 bool NeedsNewDecl = false; 6193 unsigned i = 0; 6194 SmallVector<QualType, 8> OverloadParams; 6195 6196 for (QualType ParamType : FT->param_types()) { 6197 6198 // Convert array arguments to pointer to simplify type lookup. 6199 ExprResult ArgRes = 6200 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6201 if (ArgRes.isInvalid()) 6202 return nullptr; 6203 Expr *Arg = ArgRes.get(); 6204 QualType ArgType = Arg->getType(); 6205 if (!ParamType->isPointerType() || 6206 ParamType.hasAddressSpace() || 6207 !ArgType->isPointerType() || 6208 !ArgType->getPointeeType().hasAddressSpace()) { 6209 OverloadParams.push_back(ParamType); 6210 continue; 6211 } 6212 6213 QualType PointeeType = ParamType->getPointeeType(); 6214 if (PointeeType.hasAddressSpace()) 6215 continue; 6216 6217 NeedsNewDecl = true; 6218 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6219 6220 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6221 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6222 } 6223 6224 if (!NeedsNewDecl) 6225 return nullptr; 6226 6227 FunctionProtoType::ExtProtoInfo EPI; 6228 EPI.Variadic = FT->isVariadic(); 6229 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6230 OverloadParams, EPI); 6231 DeclContext *Parent = FDecl->getParent(); 6232 FunctionDecl *OverloadDecl = FunctionDecl::Create( 6233 Context, Parent, FDecl->getLocation(), FDecl->getLocation(), 6234 FDecl->getIdentifier(), OverloadTy, 6235 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), 6236 false, 6237 /*hasPrototype=*/true); 6238 SmallVector<ParmVarDecl*, 16> Params; 6239 FT = cast<FunctionProtoType>(OverloadTy); 6240 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6241 QualType ParamType = FT->getParamType(i); 6242 ParmVarDecl *Parm = 6243 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6244 SourceLocation(), nullptr, ParamType, 6245 /*TInfo=*/nullptr, SC_None, nullptr); 6246 Parm->setScopeInfo(0, i); 6247 Params.push_back(Parm); 6248 } 6249 OverloadDecl->setParams(Params); 6250 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6251 return OverloadDecl; 6252 } 6253 6254 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6255 FunctionDecl *Callee, 6256 MultiExprArg ArgExprs) { 6257 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6258 // similar attributes) really don't like it when functions are called with an 6259 // invalid number of args. 6260 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6261 /*PartialOverloading=*/false) && 6262 !Callee->isVariadic()) 6263 return; 6264 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6265 return; 6266 6267 if (const EnableIfAttr *Attr = 6268 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6269 S.Diag(Fn->getBeginLoc(), 6270 isa<CXXMethodDecl>(Callee) 6271 ? diag::err_ovl_no_viable_member_function_in_call 6272 : diag::err_ovl_no_viable_function_in_call) 6273 << Callee << Callee->getSourceRange(); 6274 S.Diag(Callee->getLocation(), 6275 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6276 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6277 return; 6278 } 6279 } 6280 6281 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6282 const UnresolvedMemberExpr *const UME, Sema &S) { 6283 6284 const auto GetFunctionLevelDCIfCXXClass = 6285 [](Sema &S) -> const CXXRecordDecl * { 6286 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6287 if (!DC || !DC->getParent()) 6288 return nullptr; 6289 6290 // If the call to some member function was made from within a member 6291 // function body 'M' return return 'M's parent. 6292 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6293 return MD->getParent()->getCanonicalDecl(); 6294 // else the call was made from within a default member initializer of a 6295 // class, so return the class. 6296 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6297 return RD->getCanonicalDecl(); 6298 return nullptr; 6299 }; 6300 // If our DeclContext is neither a member function nor a class (in the 6301 // case of a lambda in a default member initializer), we can't have an 6302 // enclosing 'this'. 6303 6304 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6305 if (!CurParentClass) 6306 return false; 6307 6308 // The naming class for implicit member functions call is the class in which 6309 // name lookup starts. 6310 const CXXRecordDecl *const NamingClass = 6311 UME->getNamingClass()->getCanonicalDecl(); 6312 assert(NamingClass && "Must have naming class even for implicit access"); 6313 6314 // If the unresolved member functions were found in a 'naming class' that is 6315 // related (either the same or derived from) to the class that contains the 6316 // member function that itself contained the implicit member access. 6317 6318 return CurParentClass == NamingClass || 6319 CurParentClass->isDerivedFrom(NamingClass); 6320 } 6321 6322 static void 6323 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6324 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6325 6326 if (!UME) 6327 return; 6328 6329 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6330 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6331 // already been captured, or if this is an implicit member function call (if 6332 // it isn't, an attempt to capture 'this' should already have been made). 6333 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6334 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6335 return; 6336 6337 // Check if the naming class in which the unresolved members were found is 6338 // related (same as or is a base of) to the enclosing class. 6339 6340 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6341 return; 6342 6343 6344 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6345 // If the enclosing function is not dependent, then this lambda is 6346 // capture ready, so if we can capture this, do so. 6347 if (!EnclosingFunctionCtx->isDependentContext()) { 6348 // If the current lambda and all enclosing lambdas can capture 'this' - 6349 // then go ahead and capture 'this' (since our unresolved overload set 6350 // contains at least one non-static member function). 6351 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6352 S.CheckCXXThisCapture(CallLoc); 6353 } else if (S.CurContext->isDependentContext()) { 6354 // ... since this is an implicit member reference, that might potentially 6355 // involve a 'this' capture, mark 'this' for potential capture in 6356 // enclosing lambdas. 6357 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6358 CurLSI->addPotentialThisCapture(CallLoc); 6359 } 6360 } 6361 6362 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6363 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6364 Expr *ExecConfig) { 6365 ExprResult Call = 6366 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6367 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6368 if (Call.isInvalid()) 6369 return Call; 6370 6371 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6372 // language modes. 6373 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6374 if (ULE->hasExplicitTemplateArgs() && 6375 ULE->decls_begin() == ULE->decls_end()) { 6376 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6377 ? diag::warn_cxx17_compat_adl_only_template_id 6378 : diag::ext_adl_only_template_id) 6379 << ULE->getName(); 6380 } 6381 } 6382 6383 if (LangOpts.OpenMP) 6384 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6385 ExecConfig); 6386 6387 return Call; 6388 } 6389 6390 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6391 /// This provides the location of the left/right parens and a list of comma 6392 /// locations. 6393 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6394 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6395 Expr *ExecConfig, bool IsExecConfig, 6396 bool AllowRecovery) { 6397 // Since this might be a postfix expression, get rid of ParenListExprs. 6398 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6399 if (Result.isInvalid()) return ExprError(); 6400 Fn = Result.get(); 6401 6402 if (checkArgsForPlaceholders(*this, ArgExprs)) 6403 return ExprError(); 6404 6405 if (getLangOpts().CPlusPlus) { 6406 // If this is a pseudo-destructor expression, build the call immediately. 6407 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6408 if (!ArgExprs.empty()) { 6409 // Pseudo-destructor calls should not have any arguments. 6410 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6411 << FixItHint::CreateRemoval( 6412 SourceRange(ArgExprs.front()->getBeginLoc(), 6413 ArgExprs.back()->getEndLoc())); 6414 } 6415 6416 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6417 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6418 } 6419 if (Fn->getType() == Context.PseudoObjectTy) { 6420 ExprResult result = CheckPlaceholderExpr(Fn); 6421 if (result.isInvalid()) return ExprError(); 6422 Fn = result.get(); 6423 } 6424 6425 // Determine whether this is a dependent call inside a C++ template, 6426 // in which case we won't do any semantic analysis now. 6427 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6428 if (ExecConfig) { 6429 return CUDAKernelCallExpr::Create(Context, Fn, 6430 cast<CallExpr>(ExecConfig), ArgExprs, 6431 Context.DependentTy, VK_PRValue, 6432 RParenLoc, CurFPFeatureOverrides()); 6433 } else { 6434 6435 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6436 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6437 Fn->getBeginLoc()); 6438 6439 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6440 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6441 } 6442 } 6443 6444 // Determine whether this is a call to an object (C++ [over.call.object]). 6445 if (Fn->getType()->isRecordType()) 6446 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6447 RParenLoc); 6448 6449 if (Fn->getType() == Context.UnknownAnyTy) { 6450 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6451 if (result.isInvalid()) return ExprError(); 6452 Fn = result.get(); 6453 } 6454 6455 if (Fn->getType() == Context.BoundMemberTy) { 6456 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6457 RParenLoc, AllowRecovery); 6458 } 6459 } 6460 6461 // Check for overloaded calls. This can happen even in C due to extensions. 6462 if (Fn->getType() == Context.OverloadTy) { 6463 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6464 6465 // We aren't supposed to apply this logic if there's an '&' involved. 6466 if (!find.HasFormOfMemberPointer) { 6467 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6468 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6469 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6470 OverloadExpr *ovl = find.Expression; 6471 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6472 return BuildOverloadedCallExpr( 6473 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6474 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6475 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6476 RParenLoc, AllowRecovery); 6477 } 6478 } 6479 6480 // If we're directly calling a function, get the appropriate declaration. 6481 if (Fn->getType() == Context.UnknownAnyTy) { 6482 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6483 if (result.isInvalid()) return ExprError(); 6484 Fn = result.get(); 6485 } 6486 6487 Expr *NakedFn = Fn->IgnoreParens(); 6488 6489 bool CallingNDeclIndirectly = false; 6490 NamedDecl *NDecl = nullptr; 6491 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6492 if (UnOp->getOpcode() == UO_AddrOf) { 6493 CallingNDeclIndirectly = true; 6494 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6495 } 6496 } 6497 6498 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6499 NDecl = DRE->getDecl(); 6500 6501 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6502 if (FDecl && FDecl->getBuiltinID()) { 6503 // Rewrite the function decl for this builtin by replacing parameters 6504 // with no explicit address space with the address space of the arguments 6505 // in ArgExprs. 6506 if ((FDecl = 6507 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6508 NDecl = FDecl; 6509 Fn = DeclRefExpr::Create( 6510 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6511 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6512 nullptr, DRE->isNonOdrUse()); 6513 } 6514 } 6515 } else if (isa<MemberExpr>(NakedFn)) 6516 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6517 6518 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6519 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6520 FD, /*Complain=*/true, Fn->getBeginLoc())) 6521 return ExprError(); 6522 6523 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6524 6525 // If this expression is a call to a builtin function in HIP device 6526 // compilation, allow a pointer-type argument to default address space to be 6527 // passed as a pointer-type parameter to a non-default address space. 6528 // If Arg is declared in the default address space and Param is declared 6529 // in a non-default address space, perform an implicit address space cast to 6530 // the parameter type. 6531 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && 6532 FD->getBuiltinID()) { 6533 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) { 6534 ParmVarDecl *Param = FD->getParamDecl(Idx); 6535 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || 6536 !ArgExprs[Idx]->getType()->isPointerType()) 6537 continue; 6538 6539 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); 6540 auto ArgTy = ArgExprs[Idx]->getType(); 6541 auto ArgPtTy = ArgTy->getPointeeType(); 6542 auto ArgAS = ArgPtTy.getAddressSpace(); 6543 6544 // Only allow implicit casting from a non-default address space pointee 6545 // type to a default address space pointee type 6546 if (ArgAS != LangAS::Default || ParamAS == LangAS::Default) 6547 continue; 6548 6549 // First, ensure that the Arg is an RValue. 6550 if (ArgExprs[Idx]->isGLValue()) { 6551 ArgExprs[Idx] = ImplicitCastExpr::Create( 6552 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx], 6553 nullptr, VK_PRValue, FPOptionsOverride()); 6554 } 6555 6556 // Construct a new arg type with address space of Param 6557 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); 6558 ArgPtQuals.setAddressSpace(ParamAS); 6559 auto NewArgPtTy = 6560 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); 6561 auto NewArgTy = 6562 Context.getQualifiedType(Context.getPointerType(NewArgPtTy), 6563 ArgTy.getQualifiers()); 6564 6565 // Finally perform an implicit address space cast 6566 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, 6567 CK_AddressSpaceConversion) 6568 .get(); 6569 } 6570 } 6571 } 6572 6573 if (Context.isDependenceAllowed() && 6574 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6575 assert(!getLangOpts().CPlusPlus); 6576 assert((Fn->containsErrors() || 6577 llvm::any_of(ArgExprs, 6578 [](clang::Expr *E) { return E->containsErrors(); })) && 6579 "should only occur in error-recovery path."); 6580 QualType ReturnType = 6581 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6582 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6583 : Context.DependentTy; 6584 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6585 Expr::getValueKindForType(ReturnType), RParenLoc, 6586 CurFPFeatureOverrides()); 6587 } 6588 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6589 ExecConfig, IsExecConfig); 6590 } 6591 6592 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id 6593 // with the specified CallArgs 6594 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 6595 MultiExprArg CallArgs) { 6596 StringRef Name = Context.BuiltinInfo.getName(Id); 6597 LookupResult R(*this, &Context.Idents.get(Name), Loc, 6598 Sema::LookupOrdinaryName); 6599 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); 6600 6601 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); 6602 assert(BuiltInDecl && "failed to find builtin declaration"); 6603 6604 ExprResult DeclRef = 6605 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); 6606 assert(DeclRef.isUsable() && "Builtin reference cannot fail"); 6607 6608 ExprResult Call = 6609 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); 6610 6611 assert(!Call.isInvalid() && "Call to builtin cannot fail!"); 6612 return Call.get(); 6613 } 6614 6615 /// Parse a __builtin_astype expression. 6616 /// 6617 /// __builtin_astype( value, dst type ) 6618 /// 6619 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6620 SourceLocation BuiltinLoc, 6621 SourceLocation RParenLoc) { 6622 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6623 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6624 } 6625 6626 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6627 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6628 SourceLocation BuiltinLoc, 6629 SourceLocation RParenLoc) { 6630 ExprValueKind VK = VK_PRValue; 6631 ExprObjectKind OK = OK_Ordinary; 6632 QualType SrcTy = E->getType(); 6633 if (!SrcTy->isDependentType() && 6634 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6635 return ExprError( 6636 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6637 << DestTy << SrcTy << E->getSourceRange()); 6638 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6639 } 6640 6641 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6642 /// provided arguments. 6643 /// 6644 /// __builtin_convertvector( value, dst type ) 6645 /// 6646 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6647 SourceLocation BuiltinLoc, 6648 SourceLocation RParenLoc) { 6649 TypeSourceInfo *TInfo; 6650 GetTypeFromParser(ParsedDestTy, &TInfo); 6651 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6652 } 6653 6654 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6655 /// i.e. an expression not of \p OverloadTy. The expression should 6656 /// unary-convert to an expression of function-pointer or 6657 /// block-pointer type. 6658 /// 6659 /// \param NDecl the declaration being called, if available 6660 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6661 SourceLocation LParenLoc, 6662 ArrayRef<Expr *> Args, 6663 SourceLocation RParenLoc, Expr *Config, 6664 bool IsExecConfig, ADLCallKind UsesADL) { 6665 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6666 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6667 6668 // Functions with 'interrupt' attribute cannot be called directly. 6669 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6670 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6671 return ExprError(); 6672 } 6673 6674 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6675 // so there's some risk when calling out to non-interrupt handler functions 6676 // that the callee might not preserve them. This is easy to diagnose here, 6677 // but can be very challenging to debug. 6678 // Likewise, X86 interrupt handlers may only call routines with attribute 6679 // no_caller_saved_registers since there is no efficient way to 6680 // save and restore the non-GPR state. 6681 if (auto *Caller = getCurFunctionDecl()) { 6682 if (Caller->hasAttr<ARMInterruptAttr>()) { 6683 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6684 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6685 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6686 if (FDecl) 6687 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6688 } 6689 } 6690 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6691 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6692 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6693 if (FDecl) 6694 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6695 } 6696 } 6697 6698 // Promote the function operand. 6699 // We special-case function promotion here because we only allow promoting 6700 // builtin functions to function pointers in the callee of a call. 6701 ExprResult Result; 6702 QualType ResultTy; 6703 if (BuiltinID && 6704 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6705 // Extract the return type from the (builtin) function pointer type. 6706 // FIXME Several builtins still have setType in 6707 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6708 // Builtins.def to ensure they are correct before removing setType calls. 6709 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6710 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6711 ResultTy = FDecl->getCallResultType(); 6712 } else { 6713 Result = CallExprUnaryConversions(Fn); 6714 ResultTy = Context.BoolTy; 6715 } 6716 if (Result.isInvalid()) 6717 return ExprError(); 6718 Fn = Result.get(); 6719 6720 // Check for a valid function type, but only if it is not a builtin which 6721 // requires custom type checking. These will be handled by 6722 // CheckBuiltinFunctionCall below just after creation of the call expression. 6723 const FunctionType *FuncT = nullptr; 6724 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6725 retry: 6726 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6727 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6728 // have type pointer to function". 6729 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6730 if (!FuncT) 6731 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6732 << Fn->getType() << Fn->getSourceRange()); 6733 } else if (const BlockPointerType *BPT = 6734 Fn->getType()->getAs<BlockPointerType>()) { 6735 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6736 } else { 6737 // Handle calls to expressions of unknown-any type. 6738 if (Fn->getType() == Context.UnknownAnyTy) { 6739 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6740 if (rewrite.isInvalid()) 6741 return ExprError(); 6742 Fn = rewrite.get(); 6743 goto retry; 6744 } 6745 6746 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6747 << Fn->getType() << Fn->getSourceRange()); 6748 } 6749 } 6750 6751 // Get the number of parameters in the function prototype, if any. 6752 // We will allocate space for max(Args.size(), NumParams) arguments 6753 // in the call expression. 6754 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6755 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6756 6757 CallExpr *TheCall; 6758 if (Config) { 6759 assert(UsesADL == ADLCallKind::NotADL && 6760 "CUDAKernelCallExpr should not use ADL"); 6761 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6762 Args, ResultTy, VK_PRValue, RParenLoc, 6763 CurFPFeatureOverrides(), NumParams); 6764 } else { 6765 TheCall = 6766 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6767 CurFPFeatureOverrides(), NumParams, UsesADL); 6768 } 6769 6770 if (!Context.isDependenceAllowed()) { 6771 // Forget about the nulled arguments since typo correction 6772 // do not handle them well. 6773 TheCall->shrinkNumArgs(Args.size()); 6774 // C cannot always handle TypoExpr nodes in builtin calls and direct 6775 // function calls as their argument checking don't necessarily handle 6776 // dependent types properly, so make sure any TypoExprs have been 6777 // dealt with. 6778 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6779 if (!Result.isUsable()) return ExprError(); 6780 CallExpr *TheOldCall = TheCall; 6781 TheCall = dyn_cast<CallExpr>(Result.get()); 6782 bool CorrectedTypos = TheCall != TheOldCall; 6783 if (!TheCall) return Result; 6784 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6785 6786 // A new call expression node was created if some typos were corrected. 6787 // However it may not have been constructed with enough storage. In this 6788 // case, rebuild the node with enough storage. The waste of space is 6789 // immaterial since this only happens when some typos were corrected. 6790 if (CorrectedTypos && Args.size() < NumParams) { 6791 if (Config) 6792 TheCall = CUDAKernelCallExpr::Create( 6793 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 6794 RParenLoc, CurFPFeatureOverrides(), NumParams); 6795 else 6796 TheCall = 6797 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6798 CurFPFeatureOverrides(), NumParams, UsesADL); 6799 } 6800 // We can now handle the nulled arguments for the default arguments. 6801 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6802 } 6803 6804 // Bail out early if calling a builtin with custom type checking. 6805 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6806 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6807 6808 if (getLangOpts().CUDA) { 6809 if (Config) { 6810 // CUDA: Kernel calls must be to global functions 6811 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6812 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6813 << FDecl << Fn->getSourceRange()); 6814 6815 // CUDA: Kernel function must have 'void' return type 6816 if (!FuncT->getReturnType()->isVoidType() && 6817 !FuncT->getReturnType()->getAs<AutoType>() && 6818 !FuncT->getReturnType()->isInstantiationDependentType()) 6819 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6820 << Fn->getType() << Fn->getSourceRange()); 6821 } else { 6822 // CUDA: Calls to global functions must be configured 6823 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6824 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6825 << FDecl << Fn->getSourceRange()); 6826 } 6827 } 6828 6829 // Check for a valid return type 6830 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6831 FDecl)) 6832 return ExprError(); 6833 6834 // We know the result type of the call, set it. 6835 TheCall->setType(FuncT->getCallResultType(Context)); 6836 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6837 6838 if (Proto) { 6839 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6840 IsExecConfig)) 6841 return ExprError(); 6842 } else { 6843 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6844 6845 if (FDecl) { 6846 // Check if we have too few/too many template arguments, based 6847 // on our knowledge of the function definition. 6848 const FunctionDecl *Def = nullptr; 6849 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6850 Proto = Def->getType()->getAs<FunctionProtoType>(); 6851 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6852 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6853 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6854 } 6855 6856 // If the function we're calling isn't a function prototype, but we have 6857 // a function prototype from a prior declaratiom, use that prototype. 6858 if (!FDecl->hasPrototype()) 6859 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6860 } 6861 6862 // Promote the arguments (C99 6.5.2.2p6). 6863 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6864 Expr *Arg = Args[i]; 6865 6866 if (Proto && i < Proto->getNumParams()) { 6867 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6868 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6869 ExprResult ArgE = 6870 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6871 if (ArgE.isInvalid()) 6872 return true; 6873 6874 Arg = ArgE.getAs<Expr>(); 6875 6876 } else { 6877 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6878 6879 if (ArgE.isInvalid()) 6880 return true; 6881 6882 Arg = ArgE.getAs<Expr>(); 6883 } 6884 6885 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6886 diag::err_call_incomplete_argument, Arg)) 6887 return ExprError(); 6888 6889 TheCall->setArg(i, Arg); 6890 } 6891 TheCall->computeDependence(); 6892 } 6893 6894 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6895 if (!Method->isStatic()) 6896 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6897 << Fn->getSourceRange()); 6898 6899 // Check for sentinels 6900 if (NDecl) 6901 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6902 6903 // Warn for unions passing across security boundary (CMSE). 6904 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6905 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6906 if (const auto *RT = 6907 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6908 if (RT->getDecl()->isOrContainsUnion()) 6909 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6910 << 0 << i; 6911 } 6912 } 6913 } 6914 6915 // Do special checking on direct calls to functions. 6916 if (FDecl) { 6917 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6918 return ExprError(); 6919 6920 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6921 6922 if (BuiltinID) 6923 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6924 } else if (NDecl) { 6925 if (CheckPointerCall(NDecl, TheCall, Proto)) 6926 return ExprError(); 6927 } else { 6928 if (CheckOtherCall(TheCall, Proto)) 6929 return ExprError(); 6930 } 6931 6932 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6933 } 6934 6935 ExprResult 6936 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6937 SourceLocation RParenLoc, Expr *InitExpr) { 6938 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6939 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6940 6941 TypeSourceInfo *TInfo; 6942 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6943 if (!TInfo) 6944 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6945 6946 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6947 } 6948 6949 ExprResult 6950 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6951 SourceLocation RParenLoc, Expr *LiteralExpr) { 6952 QualType literalType = TInfo->getType(); 6953 6954 if (literalType->isArrayType()) { 6955 if (RequireCompleteSizedType( 6956 LParenLoc, Context.getBaseElementType(literalType), 6957 diag::err_array_incomplete_or_sizeless_type, 6958 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6959 return ExprError(); 6960 if (literalType->isVariableArrayType()) { 6961 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 6962 diag::err_variable_object_no_init)) { 6963 return ExprError(); 6964 } 6965 } 6966 } else if (!literalType->isDependentType() && 6967 RequireCompleteType(LParenLoc, literalType, 6968 diag::err_typecheck_decl_incomplete_type, 6969 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6970 return ExprError(); 6971 6972 InitializedEntity Entity 6973 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6974 InitializationKind Kind 6975 = InitializationKind::CreateCStyleCast(LParenLoc, 6976 SourceRange(LParenLoc, RParenLoc), 6977 /*InitList=*/true); 6978 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6979 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6980 &literalType); 6981 if (Result.isInvalid()) 6982 return ExprError(); 6983 LiteralExpr = Result.get(); 6984 6985 bool isFileScope = !CurContext->isFunctionOrMethod(); 6986 6987 // In C, compound literals are l-values for some reason. 6988 // For GCC compatibility, in C++, file-scope array compound literals with 6989 // constant initializers are also l-values, and compound literals are 6990 // otherwise prvalues. 6991 // 6992 // (GCC also treats C++ list-initialized file-scope array prvalues with 6993 // constant initializers as l-values, but that's non-conforming, so we don't 6994 // follow it there.) 6995 // 6996 // FIXME: It would be better to handle the lvalue cases as materializing and 6997 // lifetime-extending a temporary object, but our materialized temporaries 6998 // representation only supports lifetime extension from a variable, not "out 6999 // of thin air". 7000 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 7001 // is bound to the result of applying array-to-pointer decay to the compound 7002 // literal. 7003 // FIXME: GCC supports compound literals of reference type, which should 7004 // obviously have a value kind derived from the kind of reference involved. 7005 ExprValueKind VK = 7006 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 7007 ? VK_PRValue 7008 : VK_LValue; 7009 7010 if (isFileScope) 7011 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 7012 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 7013 Expr *Init = ILE->getInit(i); 7014 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 7015 } 7016 7017 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 7018 VK, LiteralExpr, isFileScope); 7019 if (isFileScope) { 7020 if (!LiteralExpr->isTypeDependent() && 7021 !LiteralExpr->isValueDependent() && 7022 !literalType->isDependentType()) // C99 6.5.2.5p3 7023 if (CheckForConstantInitializer(LiteralExpr, literalType)) 7024 return ExprError(); 7025 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 7026 literalType.getAddressSpace() != LangAS::Default) { 7027 // Embedded-C extensions to C99 6.5.2.5: 7028 // "If the compound literal occurs inside the body of a function, the 7029 // type name shall not be qualified by an address-space qualifier." 7030 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 7031 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 7032 return ExprError(); 7033 } 7034 7035 if (!isFileScope && !getLangOpts().CPlusPlus) { 7036 // Compound literals that have automatic storage duration are destroyed at 7037 // the end of the scope in C; in C++, they're just temporaries. 7038 7039 // Emit diagnostics if it is or contains a C union type that is non-trivial 7040 // to destruct. 7041 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 7042 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 7043 NTCUC_CompoundLiteral, NTCUK_Destruct); 7044 7045 // Diagnose jumps that enter or exit the lifetime of the compound literal. 7046 if (literalType.isDestructedType()) { 7047 Cleanup.setExprNeedsCleanups(true); 7048 ExprCleanupObjects.push_back(E); 7049 getCurFunction()->setHasBranchProtectedScope(); 7050 } 7051 } 7052 7053 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7054 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7055 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7056 E->getInitializer()->getExprLoc()); 7057 7058 return MaybeBindToTemporary(E); 7059 } 7060 7061 ExprResult 7062 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7063 SourceLocation RBraceLoc) { 7064 // Only produce each kind of designated initialization diagnostic once. 7065 SourceLocation FirstDesignator; 7066 bool DiagnosedArrayDesignator = false; 7067 bool DiagnosedNestedDesignator = false; 7068 bool DiagnosedMixedDesignator = false; 7069 7070 // Check that any designated initializers are syntactically valid in the 7071 // current language mode. 7072 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7073 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7074 if (FirstDesignator.isInvalid()) 7075 FirstDesignator = DIE->getBeginLoc(); 7076 7077 if (!getLangOpts().CPlusPlus) 7078 break; 7079 7080 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7081 DiagnosedNestedDesignator = true; 7082 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7083 << DIE->getDesignatorsSourceRange(); 7084 } 7085 7086 for (auto &Desig : DIE->designators()) { 7087 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7088 DiagnosedArrayDesignator = true; 7089 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7090 << Desig.getSourceRange(); 7091 } 7092 } 7093 7094 if (!DiagnosedMixedDesignator && 7095 !isa<DesignatedInitExpr>(InitArgList[0])) { 7096 DiagnosedMixedDesignator = true; 7097 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7098 << DIE->getSourceRange(); 7099 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7100 << InitArgList[0]->getSourceRange(); 7101 } 7102 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7103 isa<DesignatedInitExpr>(InitArgList[0])) { 7104 DiagnosedMixedDesignator = true; 7105 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7106 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7107 << DIE->getSourceRange(); 7108 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7109 << InitArgList[I]->getSourceRange(); 7110 } 7111 } 7112 7113 if (FirstDesignator.isValid()) { 7114 // Only diagnose designated initiaization as a C++20 extension if we didn't 7115 // already diagnose use of (non-C++20) C99 designator syntax. 7116 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7117 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7118 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7119 ? diag::warn_cxx17_compat_designated_init 7120 : diag::ext_cxx_designated_init); 7121 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7122 Diag(FirstDesignator, diag::ext_designated_init); 7123 } 7124 } 7125 7126 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7127 } 7128 7129 ExprResult 7130 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7131 SourceLocation RBraceLoc) { 7132 // Semantic analysis for initializers is done by ActOnDeclarator() and 7133 // CheckInitializer() - it requires knowledge of the object being initialized. 7134 7135 // Immediately handle non-overload placeholders. Overloads can be 7136 // resolved contextually, but everything else here can't. 7137 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7138 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7139 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7140 7141 // Ignore failures; dropping the entire initializer list because 7142 // of one failure would be terrible for indexing/etc. 7143 if (result.isInvalid()) continue; 7144 7145 InitArgList[I] = result.get(); 7146 } 7147 } 7148 7149 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7150 RBraceLoc); 7151 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7152 return E; 7153 } 7154 7155 /// Do an explicit extend of the given block pointer if we're in ARC. 7156 void Sema::maybeExtendBlockObject(ExprResult &E) { 7157 assert(E.get()->getType()->isBlockPointerType()); 7158 assert(E.get()->isPRValue()); 7159 7160 // Only do this in an r-value context. 7161 if (!getLangOpts().ObjCAutoRefCount) return; 7162 7163 E = ImplicitCastExpr::Create( 7164 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7165 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 7166 Cleanup.setExprNeedsCleanups(true); 7167 } 7168 7169 /// Prepare a conversion of the given expression to an ObjC object 7170 /// pointer type. 7171 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7172 QualType type = E.get()->getType(); 7173 if (type->isObjCObjectPointerType()) { 7174 return CK_BitCast; 7175 } else if (type->isBlockPointerType()) { 7176 maybeExtendBlockObject(E); 7177 return CK_BlockPointerToObjCPointerCast; 7178 } else { 7179 assert(type->isPointerType()); 7180 return CK_CPointerToObjCPointerCast; 7181 } 7182 } 7183 7184 /// Prepares for a scalar cast, performing all the necessary stages 7185 /// except the final cast and returning the kind required. 7186 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7187 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7188 // Also, callers should have filtered out the invalid cases with 7189 // pointers. Everything else should be possible. 7190 7191 QualType SrcTy = Src.get()->getType(); 7192 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7193 return CK_NoOp; 7194 7195 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7196 case Type::STK_MemberPointer: 7197 llvm_unreachable("member pointer type in C"); 7198 7199 case Type::STK_CPointer: 7200 case Type::STK_BlockPointer: 7201 case Type::STK_ObjCObjectPointer: 7202 switch (DestTy->getScalarTypeKind()) { 7203 case Type::STK_CPointer: { 7204 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7205 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7206 if (SrcAS != DestAS) 7207 return CK_AddressSpaceConversion; 7208 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7209 return CK_NoOp; 7210 return CK_BitCast; 7211 } 7212 case Type::STK_BlockPointer: 7213 return (SrcKind == Type::STK_BlockPointer 7214 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7215 case Type::STK_ObjCObjectPointer: 7216 if (SrcKind == Type::STK_ObjCObjectPointer) 7217 return CK_BitCast; 7218 if (SrcKind == Type::STK_CPointer) 7219 return CK_CPointerToObjCPointerCast; 7220 maybeExtendBlockObject(Src); 7221 return CK_BlockPointerToObjCPointerCast; 7222 case Type::STK_Bool: 7223 return CK_PointerToBoolean; 7224 case Type::STK_Integral: 7225 return CK_PointerToIntegral; 7226 case Type::STK_Floating: 7227 case Type::STK_FloatingComplex: 7228 case Type::STK_IntegralComplex: 7229 case Type::STK_MemberPointer: 7230 case Type::STK_FixedPoint: 7231 llvm_unreachable("illegal cast from pointer"); 7232 } 7233 llvm_unreachable("Should have returned before this"); 7234 7235 case Type::STK_FixedPoint: 7236 switch (DestTy->getScalarTypeKind()) { 7237 case Type::STK_FixedPoint: 7238 return CK_FixedPointCast; 7239 case Type::STK_Bool: 7240 return CK_FixedPointToBoolean; 7241 case Type::STK_Integral: 7242 return CK_FixedPointToIntegral; 7243 case Type::STK_Floating: 7244 return CK_FixedPointToFloating; 7245 case Type::STK_IntegralComplex: 7246 case Type::STK_FloatingComplex: 7247 Diag(Src.get()->getExprLoc(), 7248 diag::err_unimplemented_conversion_with_fixed_point_type) 7249 << DestTy; 7250 return CK_IntegralCast; 7251 case Type::STK_CPointer: 7252 case Type::STK_ObjCObjectPointer: 7253 case Type::STK_BlockPointer: 7254 case Type::STK_MemberPointer: 7255 llvm_unreachable("illegal cast to pointer type"); 7256 } 7257 llvm_unreachable("Should have returned before this"); 7258 7259 case Type::STK_Bool: // casting from bool is like casting from an integer 7260 case Type::STK_Integral: 7261 switch (DestTy->getScalarTypeKind()) { 7262 case Type::STK_CPointer: 7263 case Type::STK_ObjCObjectPointer: 7264 case Type::STK_BlockPointer: 7265 if (Src.get()->isNullPointerConstant(Context, 7266 Expr::NPC_ValueDependentIsNull)) 7267 return CK_NullToPointer; 7268 return CK_IntegralToPointer; 7269 case Type::STK_Bool: 7270 return CK_IntegralToBoolean; 7271 case Type::STK_Integral: 7272 return CK_IntegralCast; 7273 case Type::STK_Floating: 7274 return CK_IntegralToFloating; 7275 case Type::STK_IntegralComplex: 7276 Src = ImpCastExprToType(Src.get(), 7277 DestTy->castAs<ComplexType>()->getElementType(), 7278 CK_IntegralCast); 7279 return CK_IntegralRealToComplex; 7280 case Type::STK_FloatingComplex: 7281 Src = ImpCastExprToType(Src.get(), 7282 DestTy->castAs<ComplexType>()->getElementType(), 7283 CK_IntegralToFloating); 7284 return CK_FloatingRealToComplex; 7285 case Type::STK_MemberPointer: 7286 llvm_unreachable("member pointer type in C"); 7287 case Type::STK_FixedPoint: 7288 return CK_IntegralToFixedPoint; 7289 } 7290 llvm_unreachable("Should have returned before this"); 7291 7292 case Type::STK_Floating: 7293 switch (DestTy->getScalarTypeKind()) { 7294 case Type::STK_Floating: 7295 return CK_FloatingCast; 7296 case Type::STK_Bool: 7297 return CK_FloatingToBoolean; 7298 case Type::STK_Integral: 7299 return CK_FloatingToIntegral; 7300 case Type::STK_FloatingComplex: 7301 Src = ImpCastExprToType(Src.get(), 7302 DestTy->castAs<ComplexType>()->getElementType(), 7303 CK_FloatingCast); 7304 return CK_FloatingRealToComplex; 7305 case Type::STK_IntegralComplex: 7306 Src = ImpCastExprToType(Src.get(), 7307 DestTy->castAs<ComplexType>()->getElementType(), 7308 CK_FloatingToIntegral); 7309 return CK_IntegralRealToComplex; 7310 case Type::STK_CPointer: 7311 case Type::STK_ObjCObjectPointer: 7312 case Type::STK_BlockPointer: 7313 llvm_unreachable("valid float->pointer cast?"); 7314 case Type::STK_MemberPointer: 7315 llvm_unreachable("member pointer type in C"); 7316 case Type::STK_FixedPoint: 7317 return CK_FloatingToFixedPoint; 7318 } 7319 llvm_unreachable("Should have returned before this"); 7320 7321 case Type::STK_FloatingComplex: 7322 switch (DestTy->getScalarTypeKind()) { 7323 case Type::STK_FloatingComplex: 7324 return CK_FloatingComplexCast; 7325 case Type::STK_IntegralComplex: 7326 return CK_FloatingComplexToIntegralComplex; 7327 case Type::STK_Floating: { 7328 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7329 if (Context.hasSameType(ET, DestTy)) 7330 return CK_FloatingComplexToReal; 7331 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7332 return CK_FloatingCast; 7333 } 7334 case Type::STK_Bool: 7335 return CK_FloatingComplexToBoolean; 7336 case Type::STK_Integral: 7337 Src = ImpCastExprToType(Src.get(), 7338 SrcTy->castAs<ComplexType>()->getElementType(), 7339 CK_FloatingComplexToReal); 7340 return CK_FloatingToIntegral; 7341 case Type::STK_CPointer: 7342 case Type::STK_ObjCObjectPointer: 7343 case Type::STK_BlockPointer: 7344 llvm_unreachable("valid complex float->pointer cast?"); 7345 case Type::STK_MemberPointer: 7346 llvm_unreachable("member pointer type in C"); 7347 case Type::STK_FixedPoint: 7348 Diag(Src.get()->getExprLoc(), 7349 diag::err_unimplemented_conversion_with_fixed_point_type) 7350 << SrcTy; 7351 return CK_IntegralCast; 7352 } 7353 llvm_unreachable("Should have returned before this"); 7354 7355 case Type::STK_IntegralComplex: 7356 switch (DestTy->getScalarTypeKind()) { 7357 case Type::STK_FloatingComplex: 7358 return CK_IntegralComplexToFloatingComplex; 7359 case Type::STK_IntegralComplex: 7360 return CK_IntegralComplexCast; 7361 case Type::STK_Integral: { 7362 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7363 if (Context.hasSameType(ET, DestTy)) 7364 return CK_IntegralComplexToReal; 7365 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7366 return CK_IntegralCast; 7367 } 7368 case Type::STK_Bool: 7369 return CK_IntegralComplexToBoolean; 7370 case Type::STK_Floating: 7371 Src = ImpCastExprToType(Src.get(), 7372 SrcTy->castAs<ComplexType>()->getElementType(), 7373 CK_IntegralComplexToReal); 7374 return CK_IntegralToFloating; 7375 case Type::STK_CPointer: 7376 case Type::STK_ObjCObjectPointer: 7377 case Type::STK_BlockPointer: 7378 llvm_unreachable("valid complex int->pointer cast?"); 7379 case Type::STK_MemberPointer: 7380 llvm_unreachable("member pointer type in C"); 7381 case Type::STK_FixedPoint: 7382 Diag(Src.get()->getExprLoc(), 7383 diag::err_unimplemented_conversion_with_fixed_point_type) 7384 << SrcTy; 7385 return CK_IntegralCast; 7386 } 7387 llvm_unreachable("Should have returned before this"); 7388 } 7389 7390 llvm_unreachable("Unhandled scalar cast"); 7391 } 7392 7393 static bool breakDownVectorType(QualType type, uint64_t &len, 7394 QualType &eltType) { 7395 // Vectors are simple. 7396 if (const VectorType *vecType = type->getAs<VectorType>()) { 7397 len = vecType->getNumElements(); 7398 eltType = vecType->getElementType(); 7399 assert(eltType->isScalarType()); 7400 return true; 7401 } 7402 7403 // We allow lax conversion to and from non-vector types, but only if 7404 // they're real types (i.e. non-complex, non-pointer scalar types). 7405 if (!type->isRealType()) return false; 7406 7407 len = 1; 7408 eltType = type; 7409 return true; 7410 } 7411 7412 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7413 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7414 /// allowed? 7415 /// 7416 /// This will also return false if the two given types do not make sense from 7417 /// the perspective of SVE bitcasts. 7418 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7419 assert(srcTy->isVectorType() || destTy->isVectorType()); 7420 7421 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7422 if (!FirstType->isSizelessBuiltinType()) 7423 return false; 7424 7425 const auto *VecTy = SecondType->getAs<VectorType>(); 7426 return VecTy && 7427 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7428 }; 7429 7430 return ValidScalableConversion(srcTy, destTy) || 7431 ValidScalableConversion(destTy, srcTy); 7432 } 7433 7434 /// Are the two types matrix types and do they have the same dimensions i.e. 7435 /// do they have the same number of rows and the same number of columns? 7436 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7437 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7438 return false; 7439 7440 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7441 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7442 7443 return matSrcType->getNumRows() == matDestType->getNumRows() && 7444 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7445 } 7446 7447 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7448 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7449 7450 uint64_t SrcLen, DestLen; 7451 QualType SrcEltTy, DestEltTy; 7452 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7453 return false; 7454 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7455 return false; 7456 7457 // ASTContext::getTypeSize will return the size rounded up to a 7458 // power of 2, so instead of using that, we need to use the raw 7459 // element size multiplied by the element count. 7460 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7461 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7462 7463 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7464 } 7465 7466 /// Are the two types lax-compatible vector types? That is, given 7467 /// that one of them is a vector, do they have equal storage sizes, 7468 /// where the storage size is the number of elements times the element 7469 /// size? 7470 /// 7471 /// This will also return false if either of the types is neither a 7472 /// vector nor a real type. 7473 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7474 assert(destTy->isVectorType() || srcTy->isVectorType()); 7475 7476 // Disallow lax conversions between scalars and ExtVectors (these 7477 // conversions are allowed for other vector types because common headers 7478 // depend on them). Most scalar OP ExtVector cases are handled by the 7479 // splat path anyway, which does what we want (convert, not bitcast). 7480 // What this rules out for ExtVectors is crazy things like char4*float. 7481 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7482 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7483 7484 return areVectorTypesSameSize(srcTy, destTy); 7485 } 7486 7487 /// Is this a legal conversion between two types, one of which is 7488 /// known to be a vector type? 7489 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7490 assert(destTy->isVectorType() || srcTy->isVectorType()); 7491 7492 switch (Context.getLangOpts().getLaxVectorConversions()) { 7493 case LangOptions::LaxVectorConversionKind::None: 7494 return false; 7495 7496 case LangOptions::LaxVectorConversionKind::Integer: 7497 if (!srcTy->isIntegralOrEnumerationType()) { 7498 auto *Vec = srcTy->getAs<VectorType>(); 7499 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7500 return false; 7501 } 7502 if (!destTy->isIntegralOrEnumerationType()) { 7503 auto *Vec = destTy->getAs<VectorType>(); 7504 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7505 return false; 7506 } 7507 // OK, integer (vector) -> integer (vector) bitcast. 7508 break; 7509 7510 case LangOptions::LaxVectorConversionKind::All: 7511 break; 7512 } 7513 7514 return areLaxCompatibleVectorTypes(srcTy, destTy); 7515 } 7516 7517 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7518 CastKind &Kind) { 7519 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7520 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7521 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7522 << DestTy << SrcTy << R; 7523 } 7524 } else if (SrcTy->isMatrixType()) { 7525 return Diag(R.getBegin(), 7526 diag::err_invalid_conversion_between_matrix_and_type) 7527 << SrcTy << DestTy << R; 7528 } else if (DestTy->isMatrixType()) { 7529 return Diag(R.getBegin(), 7530 diag::err_invalid_conversion_between_matrix_and_type) 7531 << DestTy << SrcTy << R; 7532 } 7533 7534 Kind = CK_MatrixCast; 7535 return false; 7536 } 7537 7538 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7539 CastKind &Kind) { 7540 assert(VectorTy->isVectorType() && "Not a vector type!"); 7541 7542 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7543 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7544 return Diag(R.getBegin(), 7545 Ty->isVectorType() ? 7546 diag::err_invalid_conversion_between_vectors : 7547 diag::err_invalid_conversion_between_vector_and_integer) 7548 << VectorTy << Ty << R; 7549 } else 7550 return Diag(R.getBegin(), 7551 diag::err_invalid_conversion_between_vector_and_scalar) 7552 << VectorTy << Ty << R; 7553 7554 Kind = CK_BitCast; 7555 return false; 7556 } 7557 7558 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7559 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7560 7561 if (DestElemTy == SplattedExpr->getType()) 7562 return SplattedExpr; 7563 7564 assert(DestElemTy->isFloatingType() || 7565 DestElemTy->isIntegralOrEnumerationType()); 7566 7567 CastKind CK; 7568 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7569 // OpenCL requires that we convert `true` boolean expressions to -1, but 7570 // only when splatting vectors. 7571 if (DestElemTy->isFloatingType()) { 7572 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7573 // in two steps: boolean to signed integral, then to floating. 7574 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7575 CK_BooleanToSignedIntegral); 7576 SplattedExpr = CastExprRes.get(); 7577 CK = CK_IntegralToFloating; 7578 } else { 7579 CK = CK_BooleanToSignedIntegral; 7580 } 7581 } else { 7582 ExprResult CastExprRes = SplattedExpr; 7583 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7584 if (CastExprRes.isInvalid()) 7585 return ExprError(); 7586 SplattedExpr = CastExprRes.get(); 7587 } 7588 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7589 } 7590 7591 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7592 Expr *CastExpr, CastKind &Kind) { 7593 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7594 7595 QualType SrcTy = CastExpr->getType(); 7596 7597 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7598 // an ExtVectorType. 7599 // In OpenCL, casts between vectors of different types are not allowed. 7600 // (See OpenCL 6.2). 7601 if (SrcTy->isVectorType()) { 7602 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7603 (getLangOpts().OpenCL && 7604 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7605 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7606 << DestTy << SrcTy << R; 7607 return ExprError(); 7608 } 7609 Kind = CK_BitCast; 7610 return CastExpr; 7611 } 7612 7613 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7614 // conversion will take place first from scalar to elt type, and then 7615 // splat from elt type to vector. 7616 if (SrcTy->isPointerType()) 7617 return Diag(R.getBegin(), 7618 diag::err_invalid_conversion_between_vector_and_scalar) 7619 << DestTy << SrcTy << R; 7620 7621 Kind = CK_VectorSplat; 7622 return prepareVectorSplat(DestTy, CastExpr); 7623 } 7624 7625 ExprResult 7626 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7627 Declarator &D, ParsedType &Ty, 7628 SourceLocation RParenLoc, Expr *CastExpr) { 7629 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7630 "ActOnCastExpr(): missing type or expr"); 7631 7632 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7633 if (D.isInvalidType()) 7634 return ExprError(); 7635 7636 if (getLangOpts().CPlusPlus) { 7637 // Check that there are no default arguments (C++ only). 7638 CheckExtraCXXDefaultArguments(D); 7639 } else { 7640 // Make sure any TypoExprs have been dealt with. 7641 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7642 if (!Res.isUsable()) 7643 return ExprError(); 7644 CastExpr = Res.get(); 7645 } 7646 7647 checkUnusedDeclAttributes(D); 7648 7649 QualType castType = castTInfo->getType(); 7650 Ty = CreateParsedType(castType, castTInfo); 7651 7652 bool isVectorLiteral = false; 7653 7654 // Check for an altivec or OpenCL literal, 7655 // i.e. all the elements are integer constants. 7656 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7657 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7658 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7659 && castType->isVectorType() && (PE || PLE)) { 7660 if (PLE && PLE->getNumExprs() == 0) { 7661 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7662 return ExprError(); 7663 } 7664 if (PE || PLE->getNumExprs() == 1) { 7665 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7666 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7667 isVectorLiteral = true; 7668 } 7669 else 7670 isVectorLiteral = true; 7671 } 7672 7673 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7674 // then handle it as such. 7675 if (isVectorLiteral) 7676 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7677 7678 // If the Expr being casted is a ParenListExpr, handle it specially. 7679 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7680 // sequence of BinOp comma operators. 7681 if (isa<ParenListExpr>(CastExpr)) { 7682 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7683 if (Result.isInvalid()) return ExprError(); 7684 CastExpr = Result.get(); 7685 } 7686 7687 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7688 !getSourceManager().isInSystemMacro(LParenLoc)) 7689 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7690 7691 CheckTollFreeBridgeCast(castType, CastExpr); 7692 7693 CheckObjCBridgeRelatedCast(castType, CastExpr); 7694 7695 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7696 7697 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7698 } 7699 7700 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7701 SourceLocation RParenLoc, Expr *E, 7702 TypeSourceInfo *TInfo) { 7703 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7704 "Expected paren or paren list expression"); 7705 7706 Expr **exprs; 7707 unsigned numExprs; 7708 Expr *subExpr; 7709 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7710 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7711 LiteralLParenLoc = PE->getLParenLoc(); 7712 LiteralRParenLoc = PE->getRParenLoc(); 7713 exprs = PE->getExprs(); 7714 numExprs = PE->getNumExprs(); 7715 } else { // isa<ParenExpr> by assertion at function entrance 7716 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7717 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7718 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7719 exprs = &subExpr; 7720 numExprs = 1; 7721 } 7722 7723 QualType Ty = TInfo->getType(); 7724 assert(Ty->isVectorType() && "Expected vector type"); 7725 7726 SmallVector<Expr *, 8> initExprs; 7727 const VectorType *VTy = Ty->castAs<VectorType>(); 7728 unsigned numElems = VTy->getNumElements(); 7729 7730 // '(...)' form of vector initialization in AltiVec: the number of 7731 // initializers must be one or must match the size of the vector. 7732 // If a single value is specified in the initializer then it will be 7733 // replicated to all the components of the vector 7734 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, 7735 VTy->getElementType())) 7736 return ExprError(); 7737 if (ShouldSplatAltivecScalarInCast(VTy)) { 7738 // The number of initializers must be one or must match the size of the 7739 // vector. If a single value is specified in the initializer then it will 7740 // be replicated to all the components of the vector 7741 if (numExprs == 1) { 7742 QualType ElemTy = VTy->getElementType(); 7743 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7744 if (Literal.isInvalid()) 7745 return ExprError(); 7746 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7747 PrepareScalarCast(Literal, ElemTy)); 7748 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7749 } 7750 else if (numExprs < numElems) { 7751 Diag(E->getExprLoc(), 7752 diag::err_incorrect_number_of_vector_initializers); 7753 return ExprError(); 7754 } 7755 else 7756 initExprs.append(exprs, exprs + numExprs); 7757 } 7758 else { 7759 // For OpenCL, when the number of initializers is a single value, 7760 // it will be replicated to all components of the vector. 7761 if (getLangOpts().OpenCL && 7762 VTy->getVectorKind() == VectorType::GenericVector && 7763 numExprs == 1) { 7764 QualType ElemTy = VTy->getElementType(); 7765 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7766 if (Literal.isInvalid()) 7767 return ExprError(); 7768 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7769 PrepareScalarCast(Literal, ElemTy)); 7770 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7771 } 7772 7773 initExprs.append(exprs, exprs + numExprs); 7774 } 7775 // FIXME: This means that pretty-printing the final AST will produce curly 7776 // braces instead of the original commas. 7777 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7778 initExprs, LiteralRParenLoc); 7779 initE->setType(Ty); 7780 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7781 } 7782 7783 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7784 /// the ParenListExpr into a sequence of comma binary operators. 7785 ExprResult 7786 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7787 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7788 if (!E) 7789 return OrigExpr; 7790 7791 ExprResult Result(E->getExpr(0)); 7792 7793 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7794 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7795 E->getExpr(i)); 7796 7797 if (Result.isInvalid()) return ExprError(); 7798 7799 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7800 } 7801 7802 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7803 SourceLocation R, 7804 MultiExprArg Val) { 7805 return ParenListExpr::Create(Context, L, Val, R); 7806 } 7807 7808 /// Emit a specialized diagnostic when one expression is a null pointer 7809 /// constant and the other is not a pointer. Returns true if a diagnostic is 7810 /// emitted. 7811 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7812 SourceLocation QuestionLoc) { 7813 Expr *NullExpr = LHSExpr; 7814 Expr *NonPointerExpr = RHSExpr; 7815 Expr::NullPointerConstantKind NullKind = 7816 NullExpr->isNullPointerConstant(Context, 7817 Expr::NPC_ValueDependentIsNotNull); 7818 7819 if (NullKind == Expr::NPCK_NotNull) { 7820 NullExpr = RHSExpr; 7821 NonPointerExpr = LHSExpr; 7822 NullKind = 7823 NullExpr->isNullPointerConstant(Context, 7824 Expr::NPC_ValueDependentIsNotNull); 7825 } 7826 7827 if (NullKind == Expr::NPCK_NotNull) 7828 return false; 7829 7830 if (NullKind == Expr::NPCK_ZeroExpression) 7831 return false; 7832 7833 if (NullKind == Expr::NPCK_ZeroLiteral) { 7834 // In this case, check to make sure that we got here from a "NULL" 7835 // string in the source code. 7836 NullExpr = NullExpr->IgnoreParenImpCasts(); 7837 SourceLocation loc = NullExpr->getExprLoc(); 7838 if (!findMacroSpelling(loc, "NULL")) 7839 return false; 7840 } 7841 7842 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7843 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7844 << NonPointerExpr->getType() << DiagType 7845 << NonPointerExpr->getSourceRange(); 7846 return true; 7847 } 7848 7849 /// Return false if the condition expression is valid, true otherwise. 7850 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7851 QualType CondTy = Cond->getType(); 7852 7853 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7854 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7855 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7856 << CondTy << Cond->getSourceRange(); 7857 return true; 7858 } 7859 7860 // C99 6.5.15p2 7861 if (CondTy->isScalarType()) return false; 7862 7863 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7864 << CondTy << Cond->getSourceRange(); 7865 return true; 7866 } 7867 7868 /// Handle when one or both operands are void type. 7869 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7870 ExprResult &RHS) { 7871 Expr *LHSExpr = LHS.get(); 7872 Expr *RHSExpr = RHS.get(); 7873 7874 if (!LHSExpr->getType()->isVoidType()) 7875 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7876 << RHSExpr->getSourceRange(); 7877 if (!RHSExpr->getType()->isVoidType()) 7878 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7879 << LHSExpr->getSourceRange(); 7880 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7881 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7882 return S.Context.VoidTy; 7883 } 7884 7885 /// Return false if the NullExpr can be promoted to PointerTy, 7886 /// true otherwise. 7887 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7888 QualType PointerTy) { 7889 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7890 !NullExpr.get()->isNullPointerConstant(S.Context, 7891 Expr::NPC_ValueDependentIsNull)) 7892 return true; 7893 7894 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7895 return false; 7896 } 7897 7898 /// Checks compatibility between two pointers and return the resulting 7899 /// type. 7900 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7901 ExprResult &RHS, 7902 SourceLocation Loc) { 7903 QualType LHSTy = LHS.get()->getType(); 7904 QualType RHSTy = RHS.get()->getType(); 7905 7906 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7907 // Two identical pointers types are always compatible. 7908 return LHSTy; 7909 } 7910 7911 QualType lhptee, rhptee; 7912 7913 // Get the pointee types. 7914 bool IsBlockPointer = false; 7915 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7916 lhptee = LHSBTy->getPointeeType(); 7917 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7918 IsBlockPointer = true; 7919 } else { 7920 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7921 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7922 } 7923 7924 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7925 // differently qualified versions of compatible types, the result type is 7926 // a pointer to an appropriately qualified version of the composite 7927 // type. 7928 7929 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7930 // clause doesn't make sense for our extensions. E.g. address space 2 should 7931 // be incompatible with address space 3: they may live on different devices or 7932 // anything. 7933 Qualifiers lhQual = lhptee.getQualifiers(); 7934 Qualifiers rhQual = rhptee.getQualifiers(); 7935 7936 LangAS ResultAddrSpace = LangAS::Default; 7937 LangAS LAddrSpace = lhQual.getAddressSpace(); 7938 LangAS RAddrSpace = rhQual.getAddressSpace(); 7939 7940 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7941 // spaces is disallowed. 7942 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7943 ResultAddrSpace = LAddrSpace; 7944 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7945 ResultAddrSpace = RAddrSpace; 7946 else { 7947 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7948 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7949 << RHS.get()->getSourceRange(); 7950 return QualType(); 7951 } 7952 7953 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7954 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7955 lhQual.removeCVRQualifiers(); 7956 rhQual.removeCVRQualifiers(); 7957 7958 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7959 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7960 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7961 // qual types are compatible iff 7962 // * corresponded types are compatible 7963 // * CVR qualifiers are equal 7964 // * address spaces are equal 7965 // Thus for conditional operator we merge CVR and address space unqualified 7966 // pointees and if there is a composite type we return a pointer to it with 7967 // merged qualifiers. 7968 LHSCastKind = 7969 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7970 RHSCastKind = 7971 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7972 lhQual.removeAddressSpace(); 7973 rhQual.removeAddressSpace(); 7974 7975 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7976 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7977 7978 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7979 7980 if (CompositeTy.isNull()) { 7981 // In this situation, we assume void* type. No especially good 7982 // reason, but this is what gcc does, and we do have to pick 7983 // to get a consistent AST. 7984 QualType incompatTy; 7985 incompatTy = S.Context.getPointerType( 7986 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7987 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7988 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7989 7990 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7991 // for casts between types with incompatible address space qualifiers. 7992 // For the following code the compiler produces casts between global and 7993 // local address spaces of the corresponded innermost pointees: 7994 // local int *global *a; 7995 // global int *global *b; 7996 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7997 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7998 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7999 << RHS.get()->getSourceRange(); 8000 8001 return incompatTy; 8002 } 8003 8004 // The pointer types are compatible. 8005 // In case of OpenCL ResultTy should have the address space qualifier 8006 // which is a superset of address spaces of both the 2nd and the 3rd 8007 // operands of the conditional operator. 8008 QualType ResultTy = [&, ResultAddrSpace]() { 8009 if (S.getLangOpts().OpenCL) { 8010 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 8011 CompositeQuals.setAddressSpace(ResultAddrSpace); 8012 return S.Context 8013 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 8014 .withCVRQualifiers(MergedCVRQual); 8015 } 8016 return CompositeTy.withCVRQualifiers(MergedCVRQual); 8017 }(); 8018 if (IsBlockPointer) 8019 ResultTy = S.Context.getBlockPointerType(ResultTy); 8020 else 8021 ResultTy = S.Context.getPointerType(ResultTy); 8022 8023 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 8024 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 8025 return ResultTy; 8026 } 8027 8028 /// Return the resulting type when the operands are both block pointers. 8029 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 8030 ExprResult &LHS, 8031 ExprResult &RHS, 8032 SourceLocation Loc) { 8033 QualType LHSTy = LHS.get()->getType(); 8034 QualType RHSTy = RHS.get()->getType(); 8035 8036 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 8037 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 8038 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 8039 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8040 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8041 return destType; 8042 } 8043 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 8044 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8045 << RHS.get()->getSourceRange(); 8046 return QualType(); 8047 } 8048 8049 // We have 2 block pointer types. 8050 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8051 } 8052 8053 /// Return the resulting type when the operands are both pointers. 8054 static QualType 8055 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8056 ExprResult &RHS, 8057 SourceLocation Loc) { 8058 // get the pointer types 8059 QualType LHSTy = LHS.get()->getType(); 8060 QualType RHSTy = RHS.get()->getType(); 8061 8062 // get the "pointed to" types 8063 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8064 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8065 8066 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8067 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8068 // Figure out necessary qualifiers (C99 6.5.15p6) 8069 QualType destPointee 8070 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8071 QualType destType = S.Context.getPointerType(destPointee); 8072 // Add qualifiers if necessary. 8073 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8074 // Promote to void*. 8075 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8076 return destType; 8077 } 8078 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8079 QualType destPointee 8080 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8081 QualType destType = S.Context.getPointerType(destPointee); 8082 // Add qualifiers if necessary. 8083 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8084 // Promote to void*. 8085 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8086 return destType; 8087 } 8088 8089 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8090 } 8091 8092 /// Return false if the first expression is not an integer and the second 8093 /// expression is not a pointer, true otherwise. 8094 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8095 Expr* PointerExpr, SourceLocation Loc, 8096 bool IsIntFirstExpr) { 8097 if (!PointerExpr->getType()->isPointerType() || 8098 !Int.get()->getType()->isIntegerType()) 8099 return false; 8100 8101 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8102 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8103 8104 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8105 << Expr1->getType() << Expr2->getType() 8106 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8107 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8108 CK_IntegralToPointer); 8109 return true; 8110 } 8111 8112 /// Simple conversion between integer and floating point types. 8113 /// 8114 /// Used when handling the OpenCL conditional operator where the 8115 /// condition is a vector while the other operands are scalar. 8116 /// 8117 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8118 /// types are either integer or floating type. Between the two 8119 /// operands, the type with the higher rank is defined as the "result 8120 /// type". The other operand needs to be promoted to the same type. No 8121 /// other type promotion is allowed. We cannot use 8122 /// UsualArithmeticConversions() for this purpose, since it always 8123 /// promotes promotable types. 8124 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8125 ExprResult &RHS, 8126 SourceLocation QuestionLoc) { 8127 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8128 if (LHS.isInvalid()) 8129 return QualType(); 8130 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8131 if (RHS.isInvalid()) 8132 return QualType(); 8133 8134 // For conversion purposes, we ignore any qualifiers. 8135 // For example, "const float" and "float" are equivalent. 8136 QualType LHSType = 8137 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8138 QualType RHSType = 8139 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8140 8141 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8142 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8143 << LHSType << LHS.get()->getSourceRange(); 8144 return QualType(); 8145 } 8146 8147 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8148 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8149 << RHSType << RHS.get()->getSourceRange(); 8150 return QualType(); 8151 } 8152 8153 // If both types are identical, no conversion is needed. 8154 if (LHSType == RHSType) 8155 return LHSType; 8156 8157 // Now handle "real" floating types (i.e. float, double, long double). 8158 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8159 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8160 /*IsCompAssign = */ false); 8161 8162 // Finally, we have two differing integer types. 8163 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8164 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8165 } 8166 8167 /// Convert scalar operands to a vector that matches the 8168 /// condition in length. 8169 /// 8170 /// Used when handling the OpenCL conditional operator where the 8171 /// condition is a vector while the other operands are scalar. 8172 /// 8173 /// We first compute the "result type" for the scalar operands 8174 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8175 /// into a vector of that type where the length matches the condition 8176 /// vector type. s6.11.6 requires that the element types of the result 8177 /// and the condition must have the same number of bits. 8178 static QualType 8179 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8180 QualType CondTy, SourceLocation QuestionLoc) { 8181 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8182 if (ResTy.isNull()) return QualType(); 8183 8184 const VectorType *CV = CondTy->getAs<VectorType>(); 8185 assert(CV); 8186 8187 // Determine the vector result type 8188 unsigned NumElements = CV->getNumElements(); 8189 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8190 8191 // Ensure that all types have the same number of bits 8192 if (S.Context.getTypeSize(CV->getElementType()) 8193 != S.Context.getTypeSize(ResTy)) { 8194 // Since VectorTy is created internally, it does not pretty print 8195 // with an OpenCL name. Instead, we just print a description. 8196 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8197 SmallString<64> Str; 8198 llvm::raw_svector_ostream OS(Str); 8199 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8200 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8201 << CondTy << OS.str(); 8202 return QualType(); 8203 } 8204 8205 // Convert operands to the vector result type 8206 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8207 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8208 8209 return VectorTy; 8210 } 8211 8212 /// Return false if this is a valid OpenCL condition vector 8213 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8214 SourceLocation QuestionLoc) { 8215 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8216 // integral type. 8217 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8218 assert(CondTy); 8219 QualType EleTy = CondTy->getElementType(); 8220 if (EleTy->isIntegerType()) return false; 8221 8222 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8223 << Cond->getType() << Cond->getSourceRange(); 8224 return true; 8225 } 8226 8227 /// Return false if the vector condition type and the vector 8228 /// result type are compatible. 8229 /// 8230 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8231 /// number of elements, and their element types have the same number 8232 /// of bits. 8233 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8234 SourceLocation QuestionLoc) { 8235 const VectorType *CV = CondTy->getAs<VectorType>(); 8236 const VectorType *RV = VecResTy->getAs<VectorType>(); 8237 assert(CV && RV); 8238 8239 if (CV->getNumElements() != RV->getNumElements()) { 8240 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8241 << CondTy << VecResTy; 8242 return true; 8243 } 8244 8245 QualType CVE = CV->getElementType(); 8246 QualType RVE = RV->getElementType(); 8247 8248 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8249 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8250 << CondTy << VecResTy; 8251 return true; 8252 } 8253 8254 return false; 8255 } 8256 8257 /// Return the resulting type for the conditional operator in 8258 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8259 /// s6.3.i) when the condition is a vector type. 8260 static QualType 8261 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8262 ExprResult &LHS, ExprResult &RHS, 8263 SourceLocation QuestionLoc) { 8264 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8265 if (Cond.isInvalid()) 8266 return QualType(); 8267 QualType CondTy = Cond.get()->getType(); 8268 8269 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8270 return QualType(); 8271 8272 // If either operand is a vector then find the vector type of the 8273 // result as specified in OpenCL v1.1 s6.3.i. 8274 if (LHS.get()->getType()->isVectorType() || 8275 RHS.get()->getType()->isVectorType()) { 8276 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8277 /*isCompAssign*/false, 8278 /*AllowBothBool*/true, 8279 /*AllowBoolConversions*/false); 8280 if (VecResTy.isNull()) return QualType(); 8281 // The result type must match the condition type as specified in 8282 // OpenCL v1.1 s6.11.6. 8283 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8284 return QualType(); 8285 return VecResTy; 8286 } 8287 8288 // Both operands are scalar. 8289 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8290 } 8291 8292 /// Return true if the Expr is block type 8293 static bool checkBlockType(Sema &S, const Expr *E) { 8294 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8295 QualType Ty = CE->getCallee()->getType(); 8296 if (Ty->isBlockPointerType()) { 8297 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8298 return true; 8299 } 8300 } 8301 return false; 8302 } 8303 8304 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8305 /// In that case, LHS = cond. 8306 /// C99 6.5.15 8307 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8308 ExprResult &RHS, ExprValueKind &VK, 8309 ExprObjectKind &OK, 8310 SourceLocation QuestionLoc) { 8311 8312 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8313 if (!LHSResult.isUsable()) return QualType(); 8314 LHS = LHSResult; 8315 8316 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8317 if (!RHSResult.isUsable()) return QualType(); 8318 RHS = RHSResult; 8319 8320 // C++ is sufficiently different to merit its own checker. 8321 if (getLangOpts().CPlusPlus) 8322 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8323 8324 VK = VK_PRValue; 8325 OK = OK_Ordinary; 8326 8327 if (Context.isDependenceAllowed() && 8328 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8329 RHS.get()->isTypeDependent())) { 8330 assert(!getLangOpts().CPlusPlus); 8331 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8332 RHS.get()->containsErrors()) && 8333 "should only occur in error-recovery path."); 8334 return Context.DependentTy; 8335 } 8336 8337 // The OpenCL operator with a vector condition is sufficiently 8338 // different to merit its own checker. 8339 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8340 Cond.get()->getType()->isExtVectorType()) 8341 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8342 8343 // First, check the condition. 8344 Cond = UsualUnaryConversions(Cond.get()); 8345 if (Cond.isInvalid()) 8346 return QualType(); 8347 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8348 return QualType(); 8349 8350 // Now check the two expressions. 8351 if (LHS.get()->getType()->isVectorType() || 8352 RHS.get()->getType()->isVectorType()) 8353 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8354 /*AllowBothBool*/true, 8355 /*AllowBoolConversions*/false); 8356 8357 QualType ResTy = 8358 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8359 if (LHS.isInvalid() || RHS.isInvalid()) 8360 return QualType(); 8361 8362 QualType LHSTy = LHS.get()->getType(); 8363 QualType RHSTy = RHS.get()->getType(); 8364 8365 // Diagnose attempts to convert between __ibm128, __float128 and long double 8366 // where such conversions currently can't be handled. 8367 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8368 Diag(QuestionLoc, 8369 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8370 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8371 return QualType(); 8372 } 8373 8374 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8375 // selection operator (?:). 8376 if (getLangOpts().OpenCL && 8377 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8378 return QualType(); 8379 } 8380 8381 // If both operands have arithmetic type, do the usual arithmetic conversions 8382 // to find a common type: C99 6.5.15p3,5. 8383 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8384 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8385 // different sizes, or between ExtInts and other types. 8386 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8387 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8388 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8389 << RHS.get()->getSourceRange(); 8390 return QualType(); 8391 } 8392 8393 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8394 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8395 8396 return ResTy; 8397 } 8398 8399 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8400 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8401 return LHSTy; 8402 } 8403 8404 // If both operands are the same structure or union type, the result is that 8405 // type. 8406 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8407 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8408 if (LHSRT->getDecl() == RHSRT->getDecl()) 8409 // "If both the operands have structure or union type, the result has 8410 // that type." This implies that CV qualifiers are dropped. 8411 return LHSTy.getUnqualifiedType(); 8412 // FIXME: Type of conditional expression must be complete in C mode. 8413 } 8414 8415 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8416 // The following || allows only one side to be void (a GCC-ism). 8417 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8418 return checkConditionalVoidType(*this, LHS, RHS); 8419 } 8420 8421 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8422 // the type of the other operand." 8423 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8424 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8425 8426 // All objective-c pointer type analysis is done here. 8427 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8428 QuestionLoc); 8429 if (LHS.isInvalid() || RHS.isInvalid()) 8430 return QualType(); 8431 if (!compositeType.isNull()) 8432 return compositeType; 8433 8434 8435 // Handle block pointer types. 8436 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8437 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8438 QuestionLoc); 8439 8440 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8441 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8442 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8443 QuestionLoc); 8444 8445 // GCC compatibility: soften pointer/integer mismatch. Note that 8446 // null pointers have been filtered out by this point. 8447 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8448 /*IsIntFirstExpr=*/true)) 8449 return RHSTy; 8450 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8451 /*IsIntFirstExpr=*/false)) 8452 return LHSTy; 8453 8454 // Allow ?: operations in which both operands have the same 8455 // built-in sizeless type. 8456 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) 8457 return LHSTy; 8458 8459 // Emit a better diagnostic if one of the expressions is a null pointer 8460 // constant and the other is not a pointer type. In this case, the user most 8461 // likely forgot to take the address of the other expression. 8462 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8463 return QualType(); 8464 8465 // Otherwise, the operands are not compatible. 8466 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8467 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8468 << RHS.get()->getSourceRange(); 8469 return QualType(); 8470 } 8471 8472 /// FindCompositeObjCPointerType - Helper method to find composite type of 8473 /// two objective-c pointer types of the two input expressions. 8474 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8475 SourceLocation QuestionLoc) { 8476 QualType LHSTy = LHS.get()->getType(); 8477 QualType RHSTy = RHS.get()->getType(); 8478 8479 // Handle things like Class and struct objc_class*. Here we case the result 8480 // to the pseudo-builtin, because that will be implicitly cast back to the 8481 // redefinition type if an attempt is made to access its fields. 8482 if (LHSTy->isObjCClassType() && 8483 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8484 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8485 return LHSTy; 8486 } 8487 if (RHSTy->isObjCClassType() && 8488 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8489 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8490 return RHSTy; 8491 } 8492 // And the same for struct objc_object* / id 8493 if (LHSTy->isObjCIdType() && 8494 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8495 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8496 return LHSTy; 8497 } 8498 if (RHSTy->isObjCIdType() && 8499 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8500 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8501 return RHSTy; 8502 } 8503 // And the same for struct objc_selector* / SEL 8504 if (Context.isObjCSelType(LHSTy) && 8505 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8506 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8507 return LHSTy; 8508 } 8509 if (Context.isObjCSelType(RHSTy) && 8510 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8511 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8512 return RHSTy; 8513 } 8514 // Check constraints for Objective-C object pointers types. 8515 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8516 8517 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8518 // Two identical object pointer types are always compatible. 8519 return LHSTy; 8520 } 8521 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8522 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8523 QualType compositeType = LHSTy; 8524 8525 // If both operands are interfaces and either operand can be 8526 // assigned to the other, use that type as the composite 8527 // type. This allows 8528 // xxx ? (A*) a : (B*) b 8529 // where B is a subclass of A. 8530 // 8531 // Additionally, as for assignment, if either type is 'id' 8532 // allow silent coercion. Finally, if the types are 8533 // incompatible then make sure to use 'id' as the composite 8534 // type so the result is acceptable for sending messages to. 8535 8536 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8537 // It could return the composite type. 8538 if (!(compositeType = 8539 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8540 // Nothing more to do. 8541 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8542 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8543 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8544 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8545 } else if ((LHSOPT->isObjCQualifiedIdType() || 8546 RHSOPT->isObjCQualifiedIdType()) && 8547 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8548 true)) { 8549 // Need to handle "id<xx>" explicitly. 8550 // GCC allows qualified id and any Objective-C type to devolve to 8551 // id. Currently localizing to here until clear this should be 8552 // part of ObjCQualifiedIdTypesAreCompatible. 8553 compositeType = Context.getObjCIdType(); 8554 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8555 compositeType = Context.getObjCIdType(); 8556 } else { 8557 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8558 << LHSTy << RHSTy 8559 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8560 QualType incompatTy = Context.getObjCIdType(); 8561 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8562 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8563 return incompatTy; 8564 } 8565 // The object pointer types are compatible. 8566 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8567 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8568 return compositeType; 8569 } 8570 // Check Objective-C object pointer types and 'void *' 8571 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8572 if (getLangOpts().ObjCAutoRefCount) { 8573 // ARC forbids the implicit conversion of object pointers to 'void *', 8574 // so these types are not compatible. 8575 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8576 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8577 LHS = RHS = true; 8578 return QualType(); 8579 } 8580 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8581 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8582 QualType destPointee 8583 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8584 QualType destType = Context.getPointerType(destPointee); 8585 // Add qualifiers if necessary. 8586 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8587 // Promote to void*. 8588 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8589 return destType; 8590 } 8591 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8592 if (getLangOpts().ObjCAutoRefCount) { 8593 // ARC forbids the implicit conversion of object pointers to 'void *', 8594 // so these types are not compatible. 8595 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8596 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8597 LHS = RHS = true; 8598 return QualType(); 8599 } 8600 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8601 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8602 QualType destPointee 8603 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8604 QualType destType = Context.getPointerType(destPointee); 8605 // Add qualifiers if necessary. 8606 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8607 // Promote to void*. 8608 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8609 return destType; 8610 } 8611 return QualType(); 8612 } 8613 8614 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8615 /// ParenRange in parentheses. 8616 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8617 const PartialDiagnostic &Note, 8618 SourceRange ParenRange) { 8619 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8620 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8621 EndLoc.isValid()) { 8622 Self.Diag(Loc, Note) 8623 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8624 << FixItHint::CreateInsertion(EndLoc, ")"); 8625 } else { 8626 // We can't display the parentheses, so just show the bare note. 8627 Self.Diag(Loc, Note) << ParenRange; 8628 } 8629 } 8630 8631 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8632 return BinaryOperator::isAdditiveOp(Opc) || 8633 BinaryOperator::isMultiplicativeOp(Opc) || 8634 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8635 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8636 // not any of the logical operators. Bitwise-xor is commonly used as a 8637 // logical-xor because there is no logical-xor operator. The logical 8638 // operators, including uses of xor, have a high false positive rate for 8639 // precedence warnings. 8640 } 8641 8642 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8643 /// expression, either using a built-in or overloaded operator, 8644 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8645 /// expression. 8646 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8647 Expr **RHSExprs) { 8648 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8649 E = E->IgnoreImpCasts(); 8650 E = E->IgnoreConversionOperatorSingleStep(); 8651 E = E->IgnoreImpCasts(); 8652 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8653 E = MTE->getSubExpr(); 8654 E = E->IgnoreImpCasts(); 8655 } 8656 8657 // Built-in binary operator. 8658 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8659 if (IsArithmeticOp(OP->getOpcode())) { 8660 *Opcode = OP->getOpcode(); 8661 *RHSExprs = OP->getRHS(); 8662 return true; 8663 } 8664 } 8665 8666 // Overloaded operator. 8667 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8668 if (Call->getNumArgs() != 2) 8669 return false; 8670 8671 // Make sure this is really a binary operator that is safe to pass into 8672 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8673 OverloadedOperatorKind OO = Call->getOperator(); 8674 if (OO < OO_Plus || OO > OO_Arrow || 8675 OO == OO_PlusPlus || OO == OO_MinusMinus) 8676 return false; 8677 8678 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8679 if (IsArithmeticOp(OpKind)) { 8680 *Opcode = OpKind; 8681 *RHSExprs = Call->getArg(1); 8682 return true; 8683 } 8684 } 8685 8686 return false; 8687 } 8688 8689 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8690 /// or is a logical expression such as (x==y) which has int type, but is 8691 /// commonly interpreted as boolean. 8692 static bool ExprLooksBoolean(Expr *E) { 8693 E = E->IgnoreParenImpCasts(); 8694 8695 if (E->getType()->isBooleanType()) 8696 return true; 8697 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8698 return OP->isComparisonOp() || OP->isLogicalOp(); 8699 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8700 return OP->getOpcode() == UO_LNot; 8701 if (E->getType()->isPointerType()) 8702 return true; 8703 // FIXME: What about overloaded operator calls returning "unspecified boolean 8704 // type"s (commonly pointer-to-members)? 8705 8706 return false; 8707 } 8708 8709 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8710 /// and binary operator are mixed in a way that suggests the programmer assumed 8711 /// the conditional operator has higher precedence, for example: 8712 /// "int x = a + someBinaryCondition ? 1 : 2". 8713 static void DiagnoseConditionalPrecedence(Sema &Self, 8714 SourceLocation OpLoc, 8715 Expr *Condition, 8716 Expr *LHSExpr, 8717 Expr *RHSExpr) { 8718 BinaryOperatorKind CondOpcode; 8719 Expr *CondRHS; 8720 8721 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8722 return; 8723 if (!ExprLooksBoolean(CondRHS)) 8724 return; 8725 8726 // The condition is an arithmetic binary expression, with a right- 8727 // hand side that looks boolean, so warn. 8728 8729 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8730 ? diag::warn_precedence_bitwise_conditional 8731 : diag::warn_precedence_conditional; 8732 8733 Self.Diag(OpLoc, DiagID) 8734 << Condition->getSourceRange() 8735 << BinaryOperator::getOpcodeStr(CondOpcode); 8736 8737 SuggestParentheses( 8738 Self, OpLoc, 8739 Self.PDiag(diag::note_precedence_silence) 8740 << BinaryOperator::getOpcodeStr(CondOpcode), 8741 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8742 8743 SuggestParentheses(Self, OpLoc, 8744 Self.PDiag(diag::note_precedence_conditional_first), 8745 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8746 } 8747 8748 /// Compute the nullability of a conditional expression. 8749 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8750 QualType LHSTy, QualType RHSTy, 8751 ASTContext &Ctx) { 8752 if (!ResTy->isAnyPointerType()) 8753 return ResTy; 8754 8755 auto GetNullability = [&Ctx](QualType Ty) { 8756 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8757 if (Kind) { 8758 // For our purposes, treat _Nullable_result as _Nullable. 8759 if (*Kind == NullabilityKind::NullableResult) 8760 return NullabilityKind::Nullable; 8761 return *Kind; 8762 } 8763 return NullabilityKind::Unspecified; 8764 }; 8765 8766 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8767 NullabilityKind MergedKind; 8768 8769 // Compute nullability of a binary conditional expression. 8770 if (IsBin) { 8771 if (LHSKind == NullabilityKind::NonNull) 8772 MergedKind = NullabilityKind::NonNull; 8773 else 8774 MergedKind = RHSKind; 8775 // Compute nullability of a normal conditional expression. 8776 } else { 8777 if (LHSKind == NullabilityKind::Nullable || 8778 RHSKind == NullabilityKind::Nullable) 8779 MergedKind = NullabilityKind::Nullable; 8780 else if (LHSKind == NullabilityKind::NonNull) 8781 MergedKind = RHSKind; 8782 else if (RHSKind == NullabilityKind::NonNull) 8783 MergedKind = LHSKind; 8784 else 8785 MergedKind = NullabilityKind::Unspecified; 8786 } 8787 8788 // Return if ResTy already has the correct nullability. 8789 if (GetNullability(ResTy) == MergedKind) 8790 return ResTy; 8791 8792 // Strip all nullability from ResTy. 8793 while (ResTy->getNullability(Ctx)) 8794 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8795 8796 // Create a new AttributedType with the new nullability kind. 8797 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8798 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8799 } 8800 8801 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8802 /// in the case of a the GNU conditional expr extension. 8803 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8804 SourceLocation ColonLoc, 8805 Expr *CondExpr, Expr *LHSExpr, 8806 Expr *RHSExpr) { 8807 if (!Context.isDependenceAllowed()) { 8808 // C cannot handle TypoExpr nodes in the condition because it 8809 // doesn't handle dependent types properly, so make sure any TypoExprs have 8810 // been dealt with before checking the operands. 8811 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8812 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8813 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8814 8815 if (!CondResult.isUsable()) 8816 return ExprError(); 8817 8818 if (LHSExpr) { 8819 if (!LHSResult.isUsable()) 8820 return ExprError(); 8821 } 8822 8823 if (!RHSResult.isUsable()) 8824 return ExprError(); 8825 8826 CondExpr = CondResult.get(); 8827 LHSExpr = LHSResult.get(); 8828 RHSExpr = RHSResult.get(); 8829 } 8830 8831 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8832 // was the condition. 8833 OpaqueValueExpr *opaqueValue = nullptr; 8834 Expr *commonExpr = nullptr; 8835 if (!LHSExpr) { 8836 commonExpr = CondExpr; 8837 // Lower out placeholder types first. This is important so that we don't 8838 // try to capture a placeholder. This happens in few cases in C++; such 8839 // as Objective-C++'s dictionary subscripting syntax. 8840 if (commonExpr->hasPlaceholderType()) { 8841 ExprResult result = CheckPlaceholderExpr(commonExpr); 8842 if (!result.isUsable()) return ExprError(); 8843 commonExpr = result.get(); 8844 } 8845 // We usually want to apply unary conversions *before* saving, except 8846 // in the special case of a C++ l-value conditional. 8847 if (!(getLangOpts().CPlusPlus 8848 && !commonExpr->isTypeDependent() 8849 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8850 && commonExpr->isGLValue() 8851 && commonExpr->isOrdinaryOrBitFieldObject() 8852 && RHSExpr->isOrdinaryOrBitFieldObject() 8853 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8854 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8855 if (commonRes.isInvalid()) 8856 return ExprError(); 8857 commonExpr = commonRes.get(); 8858 } 8859 8860 // If the common expression is a class or array prvalue, materialize it 8861 // so that we can safely refer to it multiple times. 8862 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 8863 commonExpr->getType()->isArrayType())) { 8864 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8865 if (MatExpr.isInvalid()) 8866 return ExprError(); 8867 commonExpr = MatExpr.get(); 8868 } 8869 8870 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8871 commonExpr->getType(), 8872 commonExpr->getValueKind(), 8873 commonExpr->getObjectKind(), 8874 commonExpr); 8875 LHSExpr = CondExpr = opaqueValue; 8876 } 8877 8878 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8879 ExprValueKind VK = VK_PRValue; 8880 ExprObjectKind OK = OK_Ordinary; 8881 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8882 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8883 VK, OK, QuestionLoc); 8884 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8885 RHS.isInvalid()) 8886 return ExprError(); 8887 8888 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8889 RHS.get()); 8890 8891 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8892 8893 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8894 Context); 8895 8896 if (!commonExpr) 8897 return new (Context) 8898 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8899 RHS.get(), result, VK, OK); 8900 8901 return new (Context) BinaryConditionalOperator( 8902 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8903 ColonLoc, result, VK, OK); 8904 } 8905 8906 // Check if we have a conversion between incompatible cmse function pointer 8907 // types, that is, a conversion between a function pointer with the 8908 // cmse_nonsecure_call attribute and one without. 8909 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8910 QualType ToType) { 8911 if (const auto *ToFn = 8912 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8913 if (const auto *FromFn = 8914 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8915 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8916 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8917 8918 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8919 } 8920 } 8921 return false; 8922 } 8923 8924 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8925 // being closely modeled after the C99 spec:-). The odd characteristic of this 8926 // routine is it effectively iqnores the qualifiers on the top level pointee. 8927 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8928 // FIXME: add a couple examples in this comment. 8929 static Sema::AssignConvertType 8930 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8931 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8932 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8933 8934 // get the "pointed to" type (ignoring qualifiers at the top level) 8935 const Type *lhptee, *rhptee; 8936 Qualifiers lhq, rhq; 8937 std::tie(lhptee, lhq) = 8938 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8939 std::tie(rhptee, rhq) = 8940 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8941 8942 Sema::AssignConvertType ConvTy = Sema::Compatible; 8943 8944 // C99 6.5.16.1p1: This following citation is common to constraints 8945 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8946 // qualifiers of the type *pointed to* by the right; 8947 8948 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8949 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8950 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8951 // Ignore lifetime for further calculation. 8952 lhq.removeObjCLifetime(); 8953 rhq.removeObjCLifetime(); 8954 } 8955 8956 if (!lhq.compatiblyIncludes(rhq)) { 8957 // Treat address-space mismatches as fatal. 8958 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8959 return Sema::IncompatiblePointerDiscardsQualifiers; 8960 8961 // It's okay to add or remove GC or lifetime qualifiers when converting to 8962 // and from void*. 8963 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8964 .compatiblyIncludes( 8965 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8966 && (lhptee->isVoidType() || rhptee->isVoidType())) 8967 ; // keep old 8968 8969 // Treat lifetime mismatches as fatal. 8970 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8971 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8972 8973 // For GCC/MS compatibility, other qualifier mismatches are treated 8974 // as still compatible in C. 8975 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8976 } 8977 8978 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8979 // incomplete type and the other is a pointer to a qualified or unqualified 8980 // version of void... 8981 if (lhptee->isVoidType()) { 8982 if (rhptee->isIncompleteOrObjectType()) 8983 return ConvTy; 8984 8985 // As an extension, we allow cast to/from void* to function pointer. 8986 assert(rhptee->isFunctionType()); 8987 return Sema::FunctionVoidPointer; 8988 } 8989 8990 if (rhptee->isVoidType()) { 8991 if (lhptee->isIncompleteOrObjectType()) 8992 return ConvTy; 8993 8994 // As an extension, we allow cast to/from void* to function pointer. 8995 assert(lhptee->isFunctionType()); 8996 return Sema::FunctionVoidPointer; 8997 } 8998 8999 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 9000 // unqualified versions of compatible types, ... 9001 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 9002 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 9003 // Check if the pointee types are compatible ignoring the sign. 9004 // We explicitly check for char so that we catch "char" vs 9005 // "unsigned char" on systems where "char" is unsigned. 9006 if (lhptee->isCharType()) 9007 ltrans = S.Context.UnsignedCharTy; 9008 else if (lhptee->hasSignedIntegerRepresentation()) 9009 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 9010 9011 if (rhptee->isCharType()) 9012 rtrans = S.Context.UnsignedCharTy; 9013 else if (rhptee->hasSignedIntegerRepresentation()) 9014 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 9015 9016 if (ltrans == rtrans) { 9017 // Types are compatible ignoring the sign. Qualifier incompatibility 9018 // takes priority over sign incompatibility because the sign 9019 // warning can be disabled. 9020 if (ConvTy != Sema::Compatible) 9021 return ConvTy; 9022 9023 return Sema::IncompatiblePointerSign; 9024 } 9025 9026 // If we are a multi-level pointer, it's possible that our issue is simply 9027 // one of qualification - e.g. char ** -> const char ** is not allowed. If 9028 // the eventual target type is the same and the pointers have the same 9029 // level of indirection, this must be the issue. 9030 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 9031 do { 9032 std::tie(lhptee, lhq) = 9033 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 9034 std::tie(rhptee, rhq) = 9035 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 9036 9037 // Inconsistent address spaces at this point is invalid, even if the 9038 // address spaces would be compatible. 9039 // FIXME: This doesn't catch address space mismatches for pointers of 9040 // different nesting levels, like: 9041 // __local int *** a; 9042 // int ** b = a; 9043 // It's not clear how to actually determine when such pointers are 9044 // invalidly incompatible. 9045 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 9046 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 9047 9048 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 9049 9050 if (lhptee == rhptee) 9051 return Sema::IncompatibleNestedPointerQualifiers; 9052 } 9053 9054 // General pointer incompatibility takes priority over qualifiers. 9055 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9056 return Sema::IncompatibleFunctionPointer; 9057 return Sema::IncompatiblePointer; 9058 } 9059 if (!S.getLangOpts().CPlusPlus && 9060 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9061 return Sema::IncompatibleFunctionPointer; 9062 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9063 return Sema::IncompatibleFunctionPointer; 9064 return ConvTy; 9065 } 9066 9067 /// checkBlockPointerTypesForAssignment - This routine determines whether two 9068 /// block pointer types are compatible or whether a block and normal pointer 9069 /// are compatible. It is more restrict than comparing two function pointer 9070 // types. 9071 static Sema::AssignConvertType 9072 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9073 QualType RHSType) { 9074 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9075 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9076 9077 QualType lhptee, rhptee; 9078 9079 // get the "pointed to" type (ignoring qualifiers at the top level) 9080 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9081 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9082 9083 // In C++, the types have to match exactly. 9084 if (S.getLangOpts().CPlusPlus) 9085 return Sema::IncompatibleBlockPointer; 9086 9087 Sema::AssignConvertType ConvTy = Sema::Compatible; 9088 9089 // For blocks we enforce that qualifiers are identical. 9090 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9091 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9092 if (S.getLangOpts().OpenCL) { 9093 LQuals.removeAddressSpace(); 9094 RQuals.removeAddressSpace(); 9095 } 9096 if (LQuals != RQuals) 9097 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9098 9099 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9100 // assignment. 9101 // The current behavior is similar to C++ lambdas. A block might be 9102 // assigned to a variable iff its return type and parameters are compatible 9103 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9104 // an assignment. Presumably it should behave in way that a function pointer 9105 // assignment does in C, so for each parameter and return type: 9106 // * CVR and address space of LHS should be a superset of CVR and address 9107 // space of RHS. 9108 // * unqualified types should be compatible. 9109 if (S.getLangOpts().OpenCL) { 9110 if (!S.Context.typesAreBlockPointerCompatible( 9111 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9112 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9113 return Sema::IncompatibleBlockPointer; 9114 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9115 return Sema::IncompatibleBlockPointer; 9116 9117 return ConvTy; 9118 } 9119 9120 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9121 /// for assignment compatibility. 9122 static Sema::AssignConvertType 9123 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9124 QualType RHSType) { 9125 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9126 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9127 9128 if (LHSType->isObjCBuiltinType()) { 9129 // Class is not compatible with ObjC object pointers. 9130 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9131 !RHSType->isObjCQualifiedClassType()) 9132 return Sema::IncompatiblePointer; 9133 return Sema::Compatible; 9134 } 9135 if (RHSType->isObjCBuiltinType()) { 9136 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9137 !LHSType->isObjCQualifiedClassType()) 9138 return Sema::IncompatiblePointer; 9139 return Sema::Compatible; 9140 } 9141 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9142 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9143 9144 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9145 // make an exception for id<P> 9146 !LHSType->isObjCQualifiedIdType()) 9147 return Sema::CompatiblePointerDiscardsQualifiers; 9148 9149 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9150 return Sema::Compatible; 9151 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9152 return Sema::IncompatibleObjCQualifiedId; 9153 return Sema::IncompatiblePointer; 9154 } 9155 9156 Sema::AssignConvertType 9157 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9158 QualType LHSType, QualType RHSType) { 9159 // Fake up an opaque expression. We don't actually care about what 9160 // cast operations are required, so if CheckAssignmentConstraints 9161 // adds casts to this they'll be wasted, but fortunately that doesn't 9162 // usually happen on valid code. 9163 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 9164 ExprResult RHSPtr = &RHSExpr; 9165 CastKind K; 9166 9167 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9168 } 9169 9170 /// This helper function returns true if QT is a vector type that has element 9171 /// type ElementType. 9172 static bool isVector(QualType QT, QualType ElementType) { 9173 if (const VectorType *VT = QT->getAs<VectorType>()) 9174 return VT->getElementType().getCanonicalType() == ElementType; 9175 return false; 9176 } 9177 9178 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9179 /// has code to accommodate several GCC extensions when type checking 9180 /// pointers. Here are some objectionable examples that GCC considers warnings: 9181 /// 9182 /// int a, *pint; 9183 /// short *pshort; 9184 /// struct foo *pfoo; 9185 /// 9186 /// pint = pshort; // warning: assignment from incompatible pointer type 9187 /// a = pint; // warning: assignment makes integer from pointer without a cast 9188 /// pint = a; // warning: assignment makes pointer from integer without a cast 9189 /// pint = pfoo; // warning: assignment from incompatible pointer type 9190 /// 9191 /// As a result, the code for dealing with pointers is more complex than the 9192 /// C99 spec dictates. 9193 /// 9194 /// Sets 'Kind' for any result kind except Incompatible. 9195 Sema::AssignConvertType 9196 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9197 CastKind &Kind, bool ConvertRHS) { 9198 QualType RHSType = RHS.get()->getType(); 9199 QualType OrigLHSType = LHSType; 9200 9201 // Get canonical types. We're not formatting these types, just comparing 9202 // them. 9203 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9204 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9205 9206 // Common case: no conversion required. 9207 if (LHSType == RHSType) { 9208 Kind = CK_NoOp; 9209 return Compatible; 9210 } 9211 9212 // If we have an atomic type, try a non-atomic assignment, then just add an 9213 // atomic qualification step. 9214 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9215 Sema::AssignConvertType result = 9216 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9217 if (result != Compatible) 9218 return result; 9219 if (Kind != CK_NoOp && ConvertRHS) 9220 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9221 Kind = CK_NonAtomicToAtomic; 9222 return Compatible; 9223 } 9224 9225 // If the left-hand side is a reference type, then we are in a 9226 // (rare!) case where we've allowed the use of references in C, 9227 // e.g., as a parameter type in a built-in function. In this case, 9228 // just make sure that the type referenced is compatible with the 9229 // right-hand side type. The caller is responsible for adjusting 9230 // LHSType so that the resulting expression does not have reference 9231 // type. 9232 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9233 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9234 Kind = CK_LValueBitCast; 9235 return Compatible; 9236 } 9237 return Incompatible; 9238 } 9239 9240 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9241 // to the same ExtVector type. 9242 if (LHSType->isExtVectorType()) { 9243 if (RHSType->isExtVectorType()) 9244 return Incompatible; 9245 if (RHSType->isArithmeticType()) { 9246 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9247 if (ConvertRHS) 9248 RHS = prepareVectorSplat(LHSType, RHS.get()); 9249 Kind = CK_VectorSplat; 9250 return Compatible; 9251 } 9252 } 9253 9254 // Conversions to or from vector type. 9255 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9256 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9257 // Allow assignments of an AltiVec vector type to an equivalent GCC 9258 // vector type and vice versa 9259 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9260 Kind = CK_BitCast; 9261 return Compatible; 9262 } 9263 9264 // If we are allowing lax vector conversions, and LHS and RHS are both 9265 // vectors, the total size only needs to be the same. This is a bitcast; 9266 // no bits are changed but the result type is different. 9267 if (isLaxVectorConversion(RHSType, LHSType)) { 9268 Kind = CK_BitCast; 9269 return IncompatibleVectors; 9270 } 9271 } 9272 9273 // When the RHS comes from another lax conversion (e.g. binops between 9274 // scalars and vectors) the result is canonicalized as a vector. When the 9275 // LHS is also a vector, the lax is allowed by the condition above. Handle 9276 // the case where LHS is a scalar. 9277 if (LHSType->isScalarType()) { 9278 const VectorType *VecType = RHSType->getAs<VectorType>(); 9279 if (VecType && VecType->getNumElements() == 1 && 9280 isLaxVectorConversion(RHSType, LHSType)) { 9281 ExprResult *VecExpr = &RHS; 9282 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9283 Kind = CK_BitCast; 9284 return Compatible; 9285 } 9286 } 9287 9288 // Allow assignments between fixed-length and sizeless SVE vectors. 9289 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9290 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9291 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9292 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9293 Kind = CK_BitCast; 9294 return Compatible; 9295 } 9296 9297 return Incompatible; 9298 } 9299 9300 // Diagnose attempts to convert between __ibm128, __float128 and long double 9301 // where such conversions currently can't be handled. 9302 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9303 return Incompatible; 9304 9305 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9306 // discards the imaginary part. 9307 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9308 !LHSType->getAs<ComplexType>()) 9309 return Incompatible; 9310 9311 // Arithmetic conversions. 9312 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9313 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9314 if (ConvertRHS) 9315 Kind = PrepareScalarCast(RHS, LHSType); 9316 return Compatible; 9317 } 9318 9319 // Conversions to normal pointers. 9320 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9321 // U* -> T* 9322 if (isa<PointerType>(RHSType)) { 9323 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9324 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9325 if (AddrSpaceL != AddrSpaceR) 9326 Kind = CK_AddressSpaceConversion; 9327 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9328 Kind = CK_NoOp; 9329 else 9330 Kind = CK_BitCast; 9331 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9332 } 9333 9334 // int -> T* 9335 if (RHSType->isIntegerType()) { 9336 Kind = CK_IntegralToPointer; // FIXME: null? 9337 return IntToPointer; 9338 } 9339 9340 // C pointers are not compatible with ObjC object pointers, 9341 // with two exceptions: 9342 if (isa<ObjCObjectPointerType>(RHSType)) { 9343 // - conversions to void* 9344 if (LHSPointer->getPointeeType()->isVoidType()) { 9345 Kind = CK_BitCast; 9346 return Compatible; 9347 } 9348 9349 // - conversions from 'Class' to the redefinition type 9350 if (RHSType->isObjCClassType() && 9351 Context.hasSameType(LHSType, 9352 Context.getObjCClassRedefinitionType())) { 9353 Kind = CK_BitCast; 9354 return Compatible; 9355 } 9356 9357 Kind = CK_BitCast; 9358 return IncompatiblePointer; 9359 } 9360 9361 // U^ -> void* 9362 if (RHSType->getAs<BlockPointerType>()) { 9363 if (LHSPointer->getPointeeType()->isVoidType()) { 9364 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9365 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9366 ->getPointeeType() 9367 .getAddressSpace(); 9368 Kind = 9369 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9370 return Compatible; 9371 } 9372 } 9373 9374 return Incompatible; 9375 } 9376 9377 // Conversions to block pointers. 9378 if (isa<BlockPointerType>(LHSType)) { 9379 // U^ -> T^ 9380 if (RHSType->isBlockPointerType()) { 9381 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9382 ->getPointeeType() 9383 .getAddressSpace(); 9384 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9385 ->getPointeeType() 9386 .getAddressSpace(); 9387 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9388 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9389 } 9390 9391 // int or null -> T^ 9392 if (RHSType->isIntegerType()) { 9393 Kind = CK_IntegralToPointer; // FIXME: null 9394 return IntToBlockPointer; 9395 } 9396 9397 // id -> T^ 9398 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9399 Kind = CK_AnyPointerToBlockPointerCast; 9400 return Compatible; 9401 } 9402 9403 // void* -> T^ 9404 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9405 if (RHSPT->getPointeeType()->isVoidType()) { 9406 Kind = CK_AnyPointerToBlockPointerCast; 9407 return Compatible; 9408 } 9409 9410 return Incompatible; 9411 } 9412 9413 // Conversions to Objective-C pointers. 9414 if (isa<ObjCObjectPointerType>(LHSType)) { 9415 // A* -> B* 9416 if (RHSType->isObjCObjectPointerType()) { 9417 Kind = CK_BitCast; 9418 Sema::AssignConvertType result = 9419 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9420 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9421 result == Compatible && 9422 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9423 result = IncompatibleObjCWeakRef; 9424 return result; 9425 } 9426 9427 // int or null -> A* 9428 if (RHSType->isIntegerType()) { 9429 Kind = CK_IntegralToPointer; // FIXME: null 9430 return IntToPointer; 9431 } 9432 9433 // In general, C pointers are not compatible with ObjC object pointers, 9434 // with two exceptions: 9435 if (isa<PointerType>(RHSType)) { 9436 Kind = CK_CPointerToObjCPointerCast; 9437 9438 // - conversions from 'void*' 9439 if (RHSType->isVoidPointerType()) { 9440 return Compatible; 9441 } 9442 9443 // - conversions to 'Class' from its redefinition type 9444 if (LHSType->isObjCClassType() && 9445 Context.hasSameType(RHSType, 9446 Context.getObjCClassRedefinitionType())) { 9447 return Compatible; 9448 } 9449 9450 return IncompatiblePointer; 9451 } 9452 9453 // Only under strict condition T^ is compatible with an Objective-C pointer. 9454 if (RHSType->isBlockPointerType() && 9455 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9456 if (ConvertRHS) 9457 maybeExtendBlockObject(RHS); 9458 Kind = CK_BlockPointerToObjCPointerCast; 9459 return Compatible; 9460 } 9461 9462 return Incompatible; 9463 } 9464 9465 // Conversions from pointers that are not covered by the above. 9466 if (isa<PointerType>(RHSType)) { 9467 // T* -> _Bool 9468 if (LHSType == Context.BoolTy) { 9469 Kind = CK_PointerToBoolean; 9470 return Compatible; 9471 } 9472 9473 // T* -> int 9474 if (LHSType->isIntegerType()) { 9475 Kind = CK_PointerToIntegral; 9476 return PointerToInt; 9477 } 9478 9479 return Incompatible; 9480 } 9481 9482 // Conversions from Objective-C pointers that are not covered by the above. 9483 if (isa<ObjCObjectPointerType>(RHSType)) { 9484 // T* -> _Bool 9485 if (LHSType == Context.BoolTy) { 9486 Kind = CK_PointerToBoolean; 9487 return Compatible; 9488 } 9489 9490 // T* -> int 9491 if (LHSType->isIntegerType()) { 9492 Kind = CK_PointerToIntegral; 9493 return PointerToInt; 9494 } 9495 9496 return Incompatible; 9497 } 9498 9499 // struct A -> struct B 9500 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9501 if (Context.typesAreCompatible(LHSType, RHSType)) { 9502 Kind = CK_NoOp; 9503 return Compatible; 9504 } 9505 } 9506 9507 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9508 Kind = CK_IntToOCLSampler; 9509 return Compatible; 9510 } 9511 9512 return Incompatible; 9513 } 9514 9515 /// Constructs a transparent union from an expression that is 9516 /// used to initialize the transparent union. 9517 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9518 ExprResult &EResult, QualType UnionType, 9519 FieldDecl *Field) { 9520 // Build an initializer list that designates the appropriate member 9521 // of the transparent union. 9522 Expr *E = EResult.get(); 9523 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9524 E, SourceLocation()); 9525 Initializer->setType(UnionType); 9526 Initializer->setInitializedFieldInUnion(Field); 9527 9528 // Build a compound literal constructing a value of the transparent 9529 // union type from this initializer list. 9530 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9531 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9532 VK_PRValue, Initializer, false); 9533 } 9534 9535 Sema::AssignConvertType 9536 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9537 ExprResult &RHS) { 9538 QualType RHSType = RHS.get()->getType(); 9539 9540 // If the ArgType is a Union type, we want to handle a potential 9541 // transparent_union GCC extension. 9542 const RecordType *UT = ArgType->getAsUnionType(); 9543 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9544 return Incompatible; 9545 9546 // The field to initialize within the transparent union. 9547 RecordDecl *UD = UT->getDecl(); 9548 FieldDecl *InitField = nullptr; 9549 // It's compatible if the expression matches any of the fields. 9550 for (auto *it : UD->fields()) { 9551 if (it->getType()->isPointerType()) { 9552 // If the transparent union contains a pointer type, we allow: 9553 // 1) void pointer 9554 // 2) null pointer constant 9555 if (RHSType->isPointerType()) 9556 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9557 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9558 InitField = it; 9559 break; 9560 } 9561 9562 if (RHS.get()->isNullPointerConstant(Context, 9563 Expr::NPC_ValueDependentIsNull)) { 9564 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9565 CK_NullToPointer); 9566 InitField = it; 9567 break; 9568 } 9569 } 9570 9571 CastKind Kind; 9572 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9573 == Compatible) { 9574 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9575 InitField = it; 9576 break; 9577 } 9578 } 9579 9580 if (!InitField) 9581 return Incompatible; 9582 9583 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9584 return Compatible; 9585 } 9586 9587 Sema::AssignConvertType 9588 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9589 bool Diagnose, 9590 bool DiagnoseCFAudited, 9591 bool ConvertRHS) { 9592 // We need to be able to tell the caller whether we diagnosed a problem, if 9593 // they ask us to issue diagnostics. 9594 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9595 9596 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9597 // we can't avoid *all* modifications at the moment, so we need some somewhere 9598 // to put the updated value. 9599 ExprResult LocalRHS = CallerRHS; 9600 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9601 9602 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9603 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9604 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9605 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9606 Diag(RHS.get()->getExprLoc(), 9607 diag::warn_noderef_to_dereferenceable_pointer) 9608 << RHS.get()->getSourceRange(); 9609 } 9610 } 9611 } 9612 9613 if (getLangOpts().CPlusPlus) { 9614 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9615 // C++ 5.17p3: If the left operand is not of class type, the 9616 // expression is implicitly converted (C++ 4) to the 9617 // cv-unqualified type of the left operand. 9618 QualType RHSType = RHS.get()->getType(); 9619 if (Diagnose) { 9620 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9621 AA_Assigning); 9622 } else { 9623 ImplicitConversionSequence ICS = 9624 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9625 /*SuppressUserConversions=*/false, 9626 AllowedExplicit::None, 9627 /*InOverloadResolution=*/false, 9628 /*CStyle=*/false, 9629 /*AllowObjCWritebackConversion=*/false); 9630 if (ICS.isFailure()) 9631 return Incompatible; 9632 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9633 ICS, AA_Assigning); 9634 } 9635 if (RHS.isInvalid()) 9636 return Incompatible; 9637 Sema::AssignConvertType result = Compatible; 9638 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9639 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9640 result = IncompatibleObjCWeakRef; 9641 return result; 9642 } 9643 9644 // FIXME: Currently, we fall through and treat C++ classes like C 9645 // structures. 9646 // FIXME: We also fall through for atomics; not sure what should 9647 // happen there, though. 9648 } else if (RHS.get()->getType() == Context.OverloadTy) { 9649 // As a set of extensions to C, we support overloading on functions. These 9650 // functions need to be resolved here. 9651 DeclAccessPair DAP; 9652 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9653 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9654 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9655 else 9656 return Incompatible; 9657 } 9658 9659 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9660 // a null pointer constant. 9661 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9662 LHSType->isBlockPointerType()) && 9663 RHS.get()->isNullPointerConstant(Context, 9664 Expr::NPC_ValueDependentIsNull)) { 9665 if (Diagnose || ConvertRHS) { 9666 CastKind Kind; 9667 CXXCastPath Path; 9668 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9669 /*IgnoreBaseAccess=*/false, Diagnose); 9670 if (ConvertRHS) 9671 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 9672 } 9673 return Compatible; 9674 } 9675 9676 // OpenCL queue_t type assignment. 9677 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9678 Context, Expr::NPC_ValueDependentIsNull)) { 9679 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9680 return Compatible; 9681 } 9682 9683 // This check seems unnatural, however it is necessary to ensure the proper 9684 // conversion of functions/arrays. If the conversion were done for all 9685 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9686 // expressions that suppress this implicit conversion (&, sizeof). 9687 // 9688 // Suppress this for references: C++ 8.5.3p5. 9689 if (!LHSType->isReferenceType()) { 9690 // FIXME: We potentially allocate here even if ConvertRHS is false. 9691 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9692 if (RHS.isInvalid()) 9693 return Incompatible; 9694 } 9695 CastKind Kind; 9696 Sema::AssignConvertType result = 9697 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9698 9699 // C99 6.5.16.1p2: The value of the right operand is converted to the 9700 // type of the assignment expression. 9701 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9702 // so that we can use references in built-in functions even in C. 9703 // The getNonReferenceType() call makes sure that the resulting expression 9704 // does not have reference type. 9705 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9706 QualType Ty = LHSType.getNonLValueExprType(Context); 9707 Expr *E = RHS.get(); 9708 9709 // Check for various Objective-C errors. If we are not reporting 9710 // diagnostics and just checking for errors, e.g., during overload 9711 // resolution, return Incompatible to indicate the failure. 9712 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9713 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9714 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9715 if (!Diagnose) 9716 return Incompatible; 9717 } 9718 if (getLangOpts().ObjC && 9719 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9720 E->getType(), E, Diagnose) || 9721 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9722 if (!Diagnose) 9723 return Incompatible; 9724 // Replace the expression with a corrected version and continue so we 9725 // can find further errors. 9726 RHS = E; 9727 return Compatible; 9728 } 9729 9730 if (ConvertRHS) 9731 RHS = ImpCastExprToType(E, Ty, Kind); 9732 } 9733 9734 return result; 9735 } 9736 9737 namespace { 9738 /// The original operand to an operator, prior to the application of the usual 9739 /// arithmetic conversions and converting the arguments of a builtin operator 9740 /// candidate. 9741 struct OriginalOperand { 9742 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9743 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9744 Op = MTE->getSubExpr(); 9745 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9746 Op = BTE->getSubExpr(); 9747 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9748 Orig = ICE->getSubExprAsWritten(); 9749 Conversion = ICE->getConversionFunction(); 9750 } 9751 } 9752 9753 QualType getType() const { return Orig->getType(); } 9754 9755 Expr *Orig; 9756 NamedDecl *Conversion; 9757 }; 9758 } 9759 9760 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9761 ExprResult &RHS) { 9762 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9763 9764 Diag(Loc, diag::err_typecheck_invalid_operands) 9765 << OrigLHS.getType() << OrigRHS.getType() 9766 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9767 9768 // If a user-defined conversion was applied to either of the operands prior 9769 // to applying the built-in operator rules, tell the user about it. 9770 if (OrigLHS.Conversion) { 9771 Diag(OrigLHS.Conversion->getLocation(), 9772 diag::note_typecheck_invalid_operands_converted) 9773 << 0 << LHS.get()->getType(); 9774 } 9775 if (OrigRHS.Conversion) { 9776 Diag(OrigRHS.Conversion->getLocation(), 9777 diag::note_typecheck_invalid_operands_converted) 9778 << 1 << RHS.get()->getType(); 9779 } 9780 9781 return QualType(); 9782 } 9783 9784 // Diagnose cases where a scalar was implicitly converted to a vector and 9785 // diagnose the underlying types. Otherwise, diagnose the error 9786 // as invalid vector logical operands for non-C++ cases. 9787 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9788 ExprResult &RHS) { 9789 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9790 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9791 9792 bool LHSNatVec = LHSType->isVectorType(); 9793 bool RHSNatVec = RHSType->isVectorType(); 9794 9795 if (!(LHSNatVec && RHSNatVec)) { 9796 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9797 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9798 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9799 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9800 << Vector->getSourceRange(); 9801 return QualType(); 9802 } 9803 9804 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9805 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9806 << RHS.get()->getSourceRange(); 9807 9808 return QualType(); 9809 } 9810 9811 /// Try to convert a value of non-vector type to a vector type by converting 9812 /// the type to the element type of the vector and then performing a splat. 9813 /// If the language is OpenCL, we only use conversions that promote scalar 9814 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9815 /// for float->int. 9816 /// 9817 /// OpenCL V2.0 6.2.6.p2: 9818 /// An error shall occur if any scalar operand type has greater rank 9819 /// than the type of the vector element. 9820 /// 9821 /// \param scalar - if non-null, actually perform the conversions 9822 /// \return true if the operation fails (but without diagnosing the failure) 9823 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9824 QualType scalarTy, 9825 QualType vectorEltTy, 9826 QualType vectorTy, 9827 unsigned &DiagID) { 9828 // The conversion to apply to the scalar before splatting it, 9829 // if necessary. 9830 CastKind scalarCast = CK_NoOp; 9831 9832 if (vectorEltTy->isIntegralType(S.Context)) { 9833 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9834 (scalarTy->isIntegerType() && 9835 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9836 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9837 return true; 9838 } 9839 if (!scalarTy->isIntegralType(S.Context)) 9840 return true; 9841 scalarCast = CK_IntegralCast; 9842 } else if (vectorEltTy->isRealFloatingType()) { 9843 if (scalarTy->isRealFloatingType()) { 9844 if (S.getLangOpts().OpenCL && 9845 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9846 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9847 return true; 9848 } 9849 scalarCast = CK_FloatingCast; 9850 } 9851 else if (scalarTy->isIntegralType(S.Context)) 9852 scalarCast = CK_IntegralToFloating; 9853 else 9854 return true; 9855 } else { 9856 return true; 9857 } 9858 9859 // Adjust scalar if desired. 9860 if (scalar) { 9861 if (scalarCast != CK_NoOp) 9862 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9863 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9864 } 9865 return false; 9866 } 9867 9868 /// Convert vector E to a vector with the same number of elements but different 9869 /// element type. 9870 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9871 const auto *VecTy = E->getType()->getAs<VectorType>(); 9872 assert(VecTy && "Expression E must be a vector"); 9873 QualType NewVecTy = S.Context.getVectorType(ElementType, 9874 VecTy->getNumElements(), 9875 VecTy->getVectorKind()); 9876 9877 // Look through the implicit cast. Return the subexpression if its type is 9878 // NewVecTy. 9879 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9880 if (ICE->getSubExpr()->getType() == NewVecTy) 9881 return ICE->getSubExpr(); 9882 9883 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9884 return S.ImpCastExprToType(E, NewVecTy, Cast); 9885 } 9886 9887 /// Test if a (constant) integer Int can be casted to another integer type 9888 /// IntTy without losing precision. 9889 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9890 QualType OtherIntTy) { 9891 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9892 9893 // Reject cases where the value of the Int is unknown as that would 9894 // possibly cause truncation, but accept cases where the scalar can be 9895 // demoted without loss of precision. 9896 Expr::EvalResult EVResult; 9897 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9898 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9899 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9900 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9901 9902 if (CstInt) { 9903 // If the scalar is constant and is of a higher order and has more active 9904 // bits that the vector element type, reject it. 9905 llvm::APSInt Result = EVResult.Val.getInt(); 9906 unsigned NumBits = IntSigned 9907 ? (Result.isNegative() ? Result.getMinSignedBits() 9908 : Result.getActiveBits()) 9909 : Result.getActiveBits(); 9910 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9911 return true; 9912 9913 // If the signedness of the scalar type and the vector element type 9914 // differs and the number of bits is greater than that of the vector 9915 // element reject it. 9916 return (IntSigned != OtherIntSigned && 9917 NumBits > S.Context.getIntWidth(OtherIntTy)); 9918 } 9919 9920 // Reject cases where the value of the scalar is not constant and it's 9921 // order is greater than that of the vector element type. 9922 return (Order < 0); 9923 } 9924 9925 /// Test if a (constant) integer Int can be casted to floating point type 9926 /// FloatTy without losing precision. 9927 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9928 QualType FloatTy) { 9929 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9930 9931 // Determine if the integer constant can be expressed as a floating point 9932 // number of the appropriate type. 9933 Expr::EvalResult EVResult; 9934 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9935 9936 uint64_t Bits = 0; 9937 if (CstInt) { 9938 // Reject constants that would be truncated if they were converted to 9939 // the floating point type. Test by simple to/from conversion. 9940 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9941 // could be avoided if there was a convertFromAPInt method 9942 // which could signal back if implicit truncation occurred. 9943 llvm::APSInt Result = EVResult.Val.getInt(); 9944 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9945 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9946 llvm::APFloat::rmTowardZero); 9947 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9948 !IntTy->hasSignedIntegerRepresentation()); 9949 bool Ignored = false; 9950 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9951 &Ignored); 9952 if (Result != ConvertBack) 9953 return true; 9954 } else { 9955 // Reject types that cannot be fully encoded into the mantissa of 9956 // the float. 9957 Bits = S.Context.getTypeSize(IntTy); 9958 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9959 S.Context.getFloatTypeSemantics(FloatTy)); 9960 if (Bits > FloatPrec) 9961 return true; 9962 } 9963 9964 return false; 9965 } 9966 9967 /// Attempt to convert and splat Scalar into a vector whose types matches 9968 /// Vector following GCC conversion rules. The rule is that implicit 9969 /// conversion can occur when Scalar can be casted to match Vector's element 9970 /// type without causing truncation of Scalar. 9971 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9972 ExprResult *Vector) { 9973 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9974 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9975 const VectorType *VT = VectorTy->getAs<VectorType>(); 9976 9977 assert(!isa<ExtVectorType>(VT) && 9978 "ExtVectorTypes should not be handled here!"); 9979 9980 QualType VectorEltTy = VT->getElementType(); 9981 9982 // Reject cases where the vector element type or the scalar element type are 9983 // not integral or floating point types. 9984 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9985 return true; 9986 9987 // The conversion to apply to the scalar before splatting it, 9988 // if necessary. 9989 CastKind ScalarCast = CK_NoOp; 9990 9991 // Accept cases where the vector elements are integers and the scalar is 9992 // an integer. 9993 // FIXME: Notionally if the scalar was a floating point value with a precise 9994 // integral representation, we could cast it to an appropriate integer 9995 // type and then perform the rest of the checks here. GCC will perform 9996 // this conversion in some cases as determined by the input language. 9997 // We should accept it on a language independent basis. 9998 if (VectorEltTy->isIntegralType(S.Context) && 9999 ScalarTy->isIntegralType(S.Context) && 10000 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 10001 10002 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 10003 return true; 10004 10005 ScalarCast = CK_IntegralCast; 10006 } else if (VectorEltTy->isIntegralType(S.Context) && 10007 ScalarTy->isRealFloatingType()) { 10008 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 10009 ScalarCast = CK_FloatingToIntegral; 10010 else 10011 return true; 10012 } else if (VectorEltTy->isRealFloatingType()) { 10013 if (ScalarTy->isRealFloatingType()) { 10014 10015 // Reject cases where the scalar type is not a constant and has a higher 10016 // Order than the vector element type. 10017 llvm::APFloat Result(0.0); 10018 10019 // Determine whether this is a constant scalar. In the event that the 10020 // value is dependent (and thus cannot be evaluated by the constant 10021 // evaluator), skip the evaluation. This will then diagnose once the 10022 // expression is instantiated. 10023 bool CstScalar = Scalar->get()->isValueDependent() || 10024 Scalar->get()->EvaluateAsFloat(Result, S.Context); 10025 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 10026 if (!CstScalar && Order < 0) 10027 return true; 10028 10029 // If the scalar cannot be safely casted to the vector element type, 10030 // reject it. 10031 if (CstScalar) { 10032 bool Truncated = false; 10033 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 10034 llvm::APFloat::rmNearestTiesToEven, &Truncated); 10035 if (Truncated) 10036 return true; 10037 } 10038 10039 ScalarCast = CK_FloatingCast; 10040 } else if (ScalarTy->isIntegralType(S.Context)) { 10041 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 10042 return true; 10043 10044 ScalarCast = CK_IntegralToFloating; 10045 } else 10046 return true; 10047 } else if (ScalarTy->isEnumeralType()) 10048 return true; 10049 10050 // Adjust scalar if desired. 10051 if (Scalar) { 10052 if (ScalarCast != CK_NoOp) 10053 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 10054 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 10055 } 10056 return false; 10057 } 10058 10059 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 10060 SourceLocation Loc, bool IsCompAssign, 10061 bool AllowBothBool, 10062 bool AllowBoolConversions) { 10063 if (!IsCompAssign) { 10064 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10065 if (LHS.isInvalid()) 10066 return QualType(); 10067 } 10068 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10069 if (RHS.isInvalid()) 10070 return QualType(); 10071 10072 // For conversion purposes, we ignore any qualifiers. 10073 // For example, "const float" and "float" are equivalent. 10074 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10075 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10076 10077 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10078 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10079 assert(LHSVecType || RHSVecType); 10080 10081 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10082 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10083 return InvalidOperands(Loc, LHS, RHS); 10084 10085 // AltiVec-style "vector bool op vector bool" combinations are allowed 10086 // for some operators but not others. 10087 if (!AllowBothBool && 10088 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10089 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10090 return InvalidOperands(Loc, LHS, RHS); 10091 10092 // If the vector types are identical, return. 10093 if (Context.hasSameType(LHSType, RHSType)) 10094 return LHSType; 10095 10096 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10097 if (LHSVecType && RHSVecType && 10098 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10099 if (isa<ExtVectorType>(LHSVecType)) { 10100 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10101 return LHSType; 10102 } 10103 10104 if (!IsCompAssign) 10105 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10106 return RHSType; 10107 } 10108 10109 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10110 // can be mixed, with the result being the non-bool type. The non-bool 10111 // operand must have integer element type. 10112 if (AllowBoolConversions && LHSVecType && RHSVecType && 10113 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10114 (Context.getTypeSize(LHSVecType->getElementType()) == 10115 Context.getTypeSize(RHSVecType->getElementType()))) { 10116 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10117 LHSVecType->getElementType()->isIntegerType() && 10118 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10119 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10120 return LHSType; 10121 } 10122 if (!IsCompAssign && 10123 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10124 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10125 RHSVecType->getElementType()->isIntegerType()) { 10126 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10127 return RHSType; 10128 } 10129 } 10130 10131 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10132 // since the ambiguity can affect the ABI. 10133 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10134 const VectorType *VecType = SecondType->getAs<VectorType>(); 10135 return FirstType->isSizelessBuiltinType() && VecType && 10136 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10137 VecType->getVectorKind() == 10138 VectorType::SveFixedLengthPredicateVector); 10139 }; 10140 10141 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10142 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10143 return QualType(); 10144 } 10145 10146 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10147 // since the ambiguity can affect the ABI. 10148 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10149 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10150 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10151 10152 if (FirstVecType && SecondVecType) 10153 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10154 (SecondVecType->getVectorKind() == 10155 VectorType::SveFixedLengthDataVector || 10156 SecondVecType->getVectorKind() == 10157 VectorType::SveFixedLengthPredicateVector); 10158 10159 return FirstType->isSizelessBuiltinType() && SecondVecType && 10160 SecondVecType->getVectorKind() == VectorType::GenericVector; 10161 }; 10162 10163 if (IsSveGnuConversion(LHSType, RHSType) || 10164 IsSveGnuConversion(RHSType, LHSType)) { 10165 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10166 return QualType(); 10167 } 10168 10169 // If there's a vector type and a scalar, try to convert the scalar to 10170 // the vector element type and splat. 10171 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10172 if (!RHSVecType) { 10173 if (isa<ExtVectorType>(LHSVecType)) { 10174 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10175 LHSVecType->getElementType(), LHSType, 10176 DiagID)) 10177 return LHSType; 10178 } else { 10179 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10180 return LHSType; 10181 } 10182 } 10183 if (!LHSVecType) { 10184 if (isa<ExtVectorType>(RHSVecType)) { 10185 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10186 LHSType, RHSVecType->getElementType(), 10187 RHSType, DiagID)) 10188 return RHSType; 10189 } else { 10190 if (LHS.get()->isLValue() || 10191 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10192 return RHSType; 10193 } 10194 } 10195 10196 // FIXME: The code below also handles conversion between vectors and 10197 // non-scalars, we should break this down into fine grained specific checks 10198 // and emit proper diagnostics. 10199 QualType VecType = LHSVecType ? LHSType : RHSType; 10200 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10201 QualType OtherType = LHSVecType ? RHSType : LHSType; 10202 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10203 if (isLaxVectorConversion(OtherType, VecType)) { 10204 // If we're allowing lax vector conversions, only the total (data) size 10205 // needs to be the same. For non compound assignment, if one of the types is 10206 // scalar, the result is always the vector type. 10207 if (!IsCompAssign) { 10208 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10209 return VecType; 10210 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10211 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10212 // type. Note that this is already done by non-compound assignments in 10213 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10214 // <1 x T> -> T. The result is also a vector type. 10215 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10216 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10217 ExprResult *RHSExpr = &RHS; 10218 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10219 return VecType; 10220 } 10221 } 10222 10223 // Okay, the expression is invalid. 10224 10225 // If there's a non-vector, non-real operand, diagnose that. 10226 if ((!RHSVecType && !RHSType->isRealType()) || 10227 (!LHSVecType && !LHSType->isRealType())) { 10228 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10229 << LHSType << RHSType 10230 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10231 return QualType(); 10232 } 10233 10234 // OpenCL V1.1 6.2.6.p1: 10235 // If the operands are of more than one vector type, then an error shall 10236 // occur. Implicit conversions between vector types are not permitted, per 10237 // section 6.2.1. 10238 if (getLangOpts().OpenCL && 10239 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10240 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10241 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10242 << RHSType; 10243 return QualType(); 10244 } 10245 10246 10247 // If there is a vector type that is not a ExtVector and a scalar, we reach 10248 // this point if scalar could not be converted to the vector's element type 10249 // without truncation. 10250 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10251 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10252 QualType Scalar = LHSVecType ? RHSType : LHSType; 10253 QualType Vector = LHSVecType ? LHSType : RHSType; 10254 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10255 Diag(Loc, 10256 diag::err_typecheck_vector_not_convertable_implict_truncation) 10257 << ScalarOrVector << Scalar << Vector; 10258 10259 return QualType(); 10260 } 10261 10262 // Otherwise, use the generic diagnostic. 10263 Diag(Loc, DiagID) 10264 << LHSType << RHSType 10265 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10266 return QualType(); 10267 } 10268 10269 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10270 // expression. These are mainly cases where the null pointer is used as an 10271 // integer instead of a pointer. 10272 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10273 SourceLocation Loc, bool IsCompare) { 10274 // The canonical way to check for a GNU null is with isNullPointerConstant, 10275 // but we use a bit of a hack here for speed; this is a relatively 10276 // hot path, and isNullPointerConstant is slow. 10277 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10278 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10279 10280 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10281 10282 // Avoid analyzing cases where the result will either be invalid (and 10283 // diagnosed as such) or entirely valid and not something to warn about. 10284 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10285 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10286 return; 10287 10288 // Comparison operations would not make sense with a null pointer no matter 10289 // what the other expression is. 10290 if (!IsCompare) { 10291 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10292 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10293 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10294 return; 10295 } 10296 10297 // The rest of the operations only make sense with a null pointer 10298 // if the other expression is a pointer. 10299 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10300 NonNullType->canDecayToPointerType()) 10301 return; 10302 10303 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10304 << LHSNull /* LHS is NULL */ << NonNullType 10305 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10306 } 10307 10308 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10309 SourceLocation Loc) { 10310 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10311 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10312 if (!LUE || !RUE) 10313 return; 10314 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10315 RUE->getKind() != UETT_SizeOf) 10316 return; 10317 10318 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10319 QualType LHSTy = LHSArg->getType(); 10320 QualType RHSTy; 10321 10322 if (RUE->isArgumentType()) 10323 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10324 else 10325 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10326 10327 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10328 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10329 return; 10330 10331 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10332 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10333 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10334 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10335 << LHSArgDecl; 10336 } 10337 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10338 QualType ArrayElemTy = ArrayTy->getElementType(); 10339 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10340 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10341 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10342 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10343 return; 10344 S.Diag(Loc, diag::warn_division_sizeof_array) 10345 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10346 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10347 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10348 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10349 << LHSArgDecl; 10350 } 10351 10352 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10353 } 10354 } 10355 10356 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10357 ExprResult &RHS, 10358 SourceLocation Loc, bool IsDiv) { 10359 // Check for division/remainder by zero. 10360 Expr::EvalResult RHSValue; 10361 if (!RHS.get()->isValueDependent() && 10362 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10363 RHSValue.Val.getInt() == 0) 10364 S.DiagRuntimeBehavior(Loc, RHS.get(), 10365 S.PDiag(diag::warn_remainder_division_by_zero) 10366 << IsDiv << RHS.get()->getSourceRange()); 10367 } 10368 10369 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10370 SourceLocation Loc, 10371 bool IsCompAssign, bool IsDiv) { 10372 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10373 10374 QualType LHSTy = LHS.get()->getType(); 10375 QualType RHSTy = RHS.get()->getType(); 10376 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10377 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10378 /*AllowBothBool*/getLangOpts().AltiVec, 10379 /*AllowBoolConversions*/false); 10380 if (!IsDiv && 10381 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10382 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10383 // For division, only matrix-by-scalar is supported. Other combinations with 10384 // matrix types are invalid. 10385 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10386 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10387 10388 QualType compType = UsualArithmeticConversions( 10389 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10390 if (LHS.isInvalid() || RHS.isInvalid()) 10391 return QualType(); 10392 10393 10394 if (compType.isNull() || !compType->isArithmeticType()) 10395 return InvalidOperands(Loc, LHS, RHS); 10396 if (IsDiv) { 10397 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10398 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10399 } 10400 return compType; 10401 } 10402 10403 QualType Sema::CheckRemainderOperands( 10404 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10405 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10406 10407 if (LHS.get()->getType()->isVectorType() || 10408 RHS.get()->getType()->isVectorType()) { 10409 if (LHS.get()->getType()->hasIntegerRepresentation() && 10410 RHS.get()->getType()->hasIntegerRepresentation()) 10411 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10412 /*AllowBothBool*/getLangOpts().AltiVec, 10413 /*AllowBoolConversions*/false); 10414 return InvalidOperands(Loc, LHS, RHS); 10415 } 10416 10417 QualType compType = UsualArithmeticConversions( 10418 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10419 if (LHS.isInvalid() || RHS.isInvalid()) 10420 return QualType(); 10421 10422 if (compType.isNull() || !compType->isIntegerType()) 10423 return InvalidOperands(Loc, LHS, RHS); 10424 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10425 return compType; 10426 } 10427 10428 /// Diagnose invalid arithmetic on two void pointers. 10429 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10430 Expr *LHSExpr, Expr *RHSExpr) { 10431 S.Diag(Loc, S.getLangOpts().CPlusPlus 10432 ? diag::err_typecheck_pointer_arith_void_type 10433 : diag::ext_gnu_void_ptr) 10434 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10435 << RHSExpr->getSourceRange(); 10436 } 10437 10438 /// Diagnose invalid arithmetic on a void pointer. 10439 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10440 Expr *Pointer) { 10441 S.Diag(Loc, S.getLangOpts().CPlusPlus 10442 ? diag::err_typecheck_pointer_arith_void_type 10443 : diag::ext_gnu_void_ptr) 10444 << 0 /* one pointer */ << Pointer->getSourceRange(); 10445 } 10446 10447 /// Diagnose invalid arithmetic on a null pointer. 10448 /// 10449 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10450 /// idiom, which we recognize as a GNU extension. 10451 /// 10452 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10453 Expr *Pointer, bool IsGNUIdiom) { 10454 if (IsGNUIdiom) 10455 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10456 << Pointer->getSourceRange(); 10457 else 10458 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10459 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10460 } 10461 10462 /// Diagnose invalid subraction on a null pointer. 10463 /// 10464 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, 10465 Expr *Pointer, bool BothNull) { 10466 // Null - null is valid in C++ [expr.add]p7 10467 if (BothNull && S.getLangOpts().CPlusPlus) 10468 return; 10469 10470 // Is this s a macro from a system header? 10471 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) 10472 return; 10473 10474 S.Diag(Loc, diag::warn_pointer_sub_null_ptr) 10475 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10476 } 10477 10478 /// Diagnose invalid arithmetic on two function pointers. 10479 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10480 Expr *LHS, Expr *RHS) { 10481 assert(LHS->getType()->isAnyPointerType()); 10482 assert(RHS->getType()->isAnyPointerType()); 10483 S.Diag(Loc, S.getLangOpts().CPlusPlus 10484 ? diag::err_typecheck_pointer_arith_function_type 10485 : diag::ext_gnu_ptr_func_arith) 10486 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10487 // We only show the second type if it differs from the first. 10488 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10489 RHS->getType()) 10490 << RHS->getType()->getPointeeType() 10491 << LHS->getSourceRange() << RHS->getSourceRange(); 10492 } 10493 10494 /// Diagnose invalid arithmetic on a function pointer. 10495 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10496 Expr *Pointer) { 10497 assert(Pointer->getType()->isAnyPointerType()); 10498 S.Diag(Loc, S.getLangOpts().CPlusPlus 10499 ? diag::err_typecheck_pointer_arith_function_type 10500 : diag::ext_gnu_ptr_func_arith) 10501 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10502 << 0 /* one pointer, so only one type */ 10503 << Pointer->getSourceRange(); 10504 } 10505 10506 /// Emit error if Operand is incomplete pointer type 10507 /// 10508 /// \returns True if pointer has incomplete type 10509 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10510 Expr *Operand) { 10511 QualType ResType = Operand->getType(); 10512 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10513 ResType = ResAtomicType->getValueType(); 10514 10515 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10516 QualType PointeeTy = ResType->getPointeeType(); 10517 return S.RequireCompleteSizedType( 10518 Loc, PointeeTy, 10519 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10520 Operand->getSourceRange()); 10521 } 10522 10523 /// Check the validity of an arithmetic pointer operand. 10524 /// 10525 /// If the operand has pointer type, this code will check for pointer types 10526 /// which are invalid in arithmetic operations. These will be diagnosed 10527 /// appropriately, including whether or not the use is supported as an 10528 /// extension. 10529 /// 10530 /// \returns True when the operand is valid to use (even if as an extension). 10531 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10532 Expr *Operand) { 10533 QualType ResType = Operand->getType(); 10534 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10535 ResType = ResAtomicType->getValueType(); 10536 10537 if (!ResType->isAnyPointerType()) return true; 10538 10539 QualType PointeeTy = ResType->getPointeeType(); 10540 if (PointeeTy->isVoidType()) { 10541 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10542 return !S.getLangOpts().CPlusPlus; 10543 } 10544 if (PointeeTy->isFunctionType()) { 10545 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10546 return !S.getLangOpts().CPlusPlus; 10547 } 10548 10549 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10550 10551 return true; 10552 } 10553 10554 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10555 /// operands. 10556 /// 10557 /// This routine will diagnose any invalid arithmetic on pointer operands much 10558 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10559 /// for emitting a single diagnostic even for operations where both LHS and RHS 10560 /// are (potentially problematic) pointers. 10561 /// 10562 /// \returns True when the operand is valid to use (even if as an extension). 10563 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10564 Expr *LHSExpr, Expr *RHSExpr) { 10565 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10566 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10567 if (!isLHSPointer && !isRHSPointer) return true; 10568 10569 QualType LHSPointeeTy, RHSPointeeTy; 10570 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10571 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10572 10573 // if both are pointers check if operation is valid wrt address spaces 10574 if (isLHSPointer && isRHSPointer) { 10575 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10576 S.Diag(Loc, 10577 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10578 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10579 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10580 return false; 10581 } 10582 } 10583 10584 // Check for arithmetic on pointers to incomplete types. 10585 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10586 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10587 if (isLHSVoidPtr || isRHSVoidPtr) { 10588 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10589 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10590 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10591 10592 return !S.getLangOpts().CPlusPlus; 10593 } 10594 10595 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10596 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10597 if (isLHSFuncPtr || isRHSFuncPtr) { 10598 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10599 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10600 RHSExpr); 10601 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10602 10603 return !S.getLangOpts().CPlusPlus; 10604 } 10605 10606 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10607 return false; 10608 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10609 return false; 10610 10611 return true; 10612 } 10613 10614 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10615 /// literal. 10616 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10617 Expr *LHSExpr, Expr *RHSExpr) { 10618 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10619 Expr* IndexExpr = RHSExpr; 10620 if (!StrExpr) { 10621 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10622 IndexExpr = LHSExpr; 10623 } 10624 10625 bool IsStringPlusInt = StrExpr && 10626 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10627 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10628 return; 10629 10630 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10631 Self.Diag(OpLoc, diag::warn_string_plus_int) 10632 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10633 10634 // Only print a fixit for "str" + int, not for int + "str". 10635 if (IndexExpr == RHSExpr) { 10636 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10637 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10638 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10639 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10640 << FixItHint::CreateInsertion(EndLoc, "]"); 10641 } else 10642 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10643 } 10644 10645 /// Emit a warning when adding a char literal to a string. 10646 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10647 Expr *LHSExpr, Expr *RHSExpr) { 10648 const Expr *StringRefExpr = LHSExpr; 10649 const CharacterLiteral *CharExpr = 10650 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10651 10652 if (!CharExpr) { 10653 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10654 StringRefExpr = RHSExpr; 10655 } 10656 10657 if (!CharExpr || !StringRefExpr) 10658 return; 10659 10660 const QualType StringType = StringRefExpr->getType(); 10661 10662 // Return if not a PointerType. 10663 if (!StringType->isAnyPointerType()) 10664 return; 10665 10666 // Return if not a CharacterType. 10667 if (!StringType->getPointeeType()->isAnyCharacterType()) 10668 return; 10669 10670 ASTContext &Ctx = Self.getASTContext(); 10671 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10672 10673 const QualType CharType = CharExpr->getType(); 10674 if (!CharType->isAnyCharacterType() && 10675 CharType->isIntegerType() && 10676 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10677 Self.Diag(OpLoc, diag::warn_string_plus_char) 10678 << DiagRange << Ctx.CharTy; 10679 } else { 10680 Self.Diag(OpLoc, diag::warn_string_plus_char) 10681 << DiagRange << CharExpr->getType(); 10682 } 10683 10684 // Only print a fixit for str + char, not for char + str. 10685 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10686 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10687 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10688 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10689 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10690 << FixItHint::CreateInsertion(EndLoc, "]"); 10691 } else { 10692 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10693 } 10694 } 10695 10696 /// Emit error when two pointers are incompatible. 10697 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10698 Expr *LHSExpr, Expr *RHSExpr) { 10699 assert(LHSExpr->getType()->isAnyPointerType()); 10700 assert(RHSExpr->getType()->isAnyPointerType()); 10701 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10702 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10703 << RHSExpr->getSourceRange(); 10704 } 10705 10706 // C99 6.5.6 10707 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10708 SourceLocation Loc, BinaryOperatorKind Opc, 10709 QualType* CompLHSTy) { 10710 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10711 10712 if (LHS.get()->getType()->isVectorType() || 10713 RHS.get()->getType()->isVectorType()) { 10714 QualType compType = CheckVectorOperands( 10715 LHS, RHS, Loc, CompLHSTy, 10716 /*AllowBothBool*/getLangOpts().AltiVec, 10717 /*AllowBoolConversions*/getLangOpts().ZVector); 10718 if (CompLHSTy) *CompLHSTy = compType; 10719 return compType; 10720 } 10721 10722 if (LHS.get()->getType()->isConstantMatrixType() || 10723 RHS.get()->getType()->isConstantMatrixType()) { 10724 QualType compType = 10725 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10726 if (CompLHSTy) 10727 *CompLHSTy = compType; 10728 return compType; 10729 } 10730 10731 QualType compType = UsualArithmeticConversions( 10732 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10733 if (LHS.isInvalid() || RHS.isInvalid()) 10734 return QualType(); 10735 10736 // Diagnose "string literal" '+' int and string '+' "char literal". 10737 if (Opc == BO_Add) { 10738 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10739 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10740 } 10741 10742 // handle the common case first (both operands are arithmetic). 10743 if (!compType.isNull() && compType->isArithmeticType()) { 10744 if (CompLHSTy) *CompLHSTy = compType; 10745 return compType; 10746 } 10747 10748 // Type-checking. Ultimately the pointer's going to be in PExp; 10749 // note that we bias towards the LHS being the pointer. 10750 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10751 10752 bool isObjCPointer; 10753 if (PExp->getType()->isPointerType()) { 10754 isObjCPointer = false; 10755 } else if (PExp->getType()->isObjCObjectPointerType()) { 10756 isObjCPointer = true; 10757 } else { 10758 std::swap(PExp, IExp); 10759 if (PExp->getType()->isPointerType()) { 10760 isObjCPointer = false; 10761 } else if (PExp->getType()->isObjCObjectPointerType()) { 10762 isObjCPointer = true; 10763 } else { 10764 return InvalidOperands(Loc, LHS, RHS); 10765 } 10766 } 10767 assert(PExp->getType()->isAnyPointerType()); 10768 10769 if (!IExp->getType()->isIntegerType()) 10770 return InvalidOperands(Loc, LHS, RHS); 10771 10772 // Adding to a null pointer results in undefined behavior. 10773 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10774 Context, Expr::NPC_ValueDependentIsNotNull)) { 10775 // In C++ adding zero to a null pointer is defined. 10776 Expr::EvalResult KnownVal; 10777 if (!getLangOpts().CPlusPlus || 10778 (!IExp->isValueDependent() && 10779 (!IExp->EvaluateAsInt(KnownVal, Context) || 10780 KnownVal.Val.getInt() != 0))) { 10781 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10782 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10783 Context, BO_Add, PExp, IExp); 10784 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10785 } 10786 } 10787 10788 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10789 return QualType(); 10790 10791 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10792 return QualType(); 10793 10794 // Check array bounds for pointer arithemtic 10795 CheckArrayAccess(PExp, IExp); 10796 10797 if (CompLHSTy) { 10798 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10799 if (LHSTy.isNull()) { 10800 LHSTy = LHS.get()->getType(); 10801 if (LHSTy->isPromotableIntegerType()) 10802 LHSTy = Context.getPromotedIntegerType(LHSTy); 10803 } 10804 *CompLHSTy = LHSTy; 10805 } 10806 10807 return PExp->getType(); 10808 } 10809 10810 // C99 6.5.6 10811 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10812 SourceLocation Loc, 10813 QualType* CompLHSTy) { 10814 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10815 10816 if (LHS.get()->getType()->isVectorType() || 10817 RHS.get()->getType()->isVectorType()) { 10818 QualType compType = CheckVectorOperands( 10819 LHS, RHS, Loc, CompLHSTy, 10820 /*AllowBothBool*/getLangOpts().AltiVec, 10821 /*AllowBoolConversions*/getLangOpts().ZVector); 10822 if (CompLHSTy) *CompLHSTy = compType; 10823 return compType; 10824 } 10825 10826 if (LHS.get()->getType()->isConstantMatrixType() || 10827 RHS.get()->getType()->isConstantMatrixType()) { 10828 QualType compType = 10829 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10830 if (CompLHSTy) 10831 *CompLHSTy = compType; 10832 return compType; 10833 } 10834 10835 QualType compType = UsualArithmeticConversions( 10836 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10837 if (LHS.isInvalid() || RHS.isInvalid()) 10838 return QualType(); 10839 10840 // Enforce type constraints: C99 6.5.6p3. 10841 10842 // Handle the common case first (both operands are arithmetic). 10843 if (!compType.isNull() && compType->isArithmeticType()) { 10844 if (CompLHSTy) *CompLHSTy = compType; 10845 return compType; 10846 } 10847 10848 // Either ptr - int or ptr - ptr. 10849 if (LHS.get()->getType()->isAnyPointerType()) { 10850 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10851 10852 // Diagnose bad cases where we step over interface counts. 10853 if (LHS.get()->getType()->isObjCObjectPointerType() && 10854 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10855 return QualType(); 10856 10857 // The result type of a pointer-int computation is the pointer type. 10858 if (RHS.get()->getType()->isIntegerType()) { 10859 // Subtracting from a null pointer should produce a warning. 10860 // The last argument to the diagnose call says this doesn't match the 10861 // GNU int-to-pointer idiom. 10862 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10863 Expr::NPC_ValueDependentIsNotNull)) { 10864 // In C++ adding zero to a null pointer is defined. 10865 Expr::EvalResult KnownVal; 10866 if (!getLangOpts().CPlusPlus || 10867 (!RHS.get()->isValueDependent() && 10868 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10869 KnownVal.Val.getInt() != 0))) { 10870 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10871 } 10872 } 10873 10874 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10875 return QualType(); 10876 10877 // Check array bounds for pointer arithemtic 10878 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10879 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10880 10881 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10882 return LHS.get()->getType(); 10883 } 10884 10885 // Handle pointer-pointer subtractions. 10886 if (const PointerType *RHSPTy 10887 = RHS.get()->getType()->getAs<PointerType>()) { 10888 QualType rpointee = RHSPTy->getPointeeType(); 10889 10890 if (getLangOpts().CPlusPlus) { 10891 // Pointee types must be the same: C++ [expr.add] 10892 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10893 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10894 } 10895 } else { 10896 // Pointee types must be compatible C99 6.5.6p3 10897 if (!Context.typesAreCompatible( 10898 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10899 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10900 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10901 return QualType(); 10902 } 10903 } 10904 10905 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10906 LHS.get(), RHS.get())) 10907 return QualType(); 10908 10909 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10910 Context, Expr::NPC_ValueDependentIsNotNull); 10911 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10912 Context, Expr::NPC_ValueDependentIsNotNull); 10913 10914 // Subtracting nullptr or from nullptr is suspect 10915 if (LHSIsNullPtr) 10916 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); 10917 if (RHSIsNullPtr) 10918 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); 10919 10920 // The pointee type may have zero size. As an extension, a structure or 10921 // union may have zero size or an array may have zero length. In this 10922 // case subtraction does not make sense. 10923 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10924 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10925 if (ElementSize.isZero()) { 10926 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10927 << rpointee.getUnqualifiedType() 10928 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10929 } 10930 } 10931 10932 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10933 return Context.getPointerDiffType(); 10934 } 10935 } 10936 10937 return InvalidOperands(Loc, LHS, RHS); 10938 } 10939 10940 static bool isScopedEnumerationType(QualType T) { 10941 if (const EnumType *ET = T->getAs<EnumType>()) 10942 return ET->getDecl()->isScoped(); 10943 return false; 10944 } 10945 10946 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10947 SourceLocation Loc, BinaryOperatorKind Opc, 10948 QualType LHSType) { 10949 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10950 // so skip remaining warnings as we don't want to modify values within Sema. 10951 if (S.getLangOpts().OpenCL) 10952 return; 10953 10954 // Check right/shifter operand 10955 Expr::EvalResult RHSResult; 10956 if (RHS.get()->isValueDependent() || 10957 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10958 return; 10959 llvm::APSInt Right = RHSResult.Val.getInt(); 10960 10961 if (Right.isNegative()) { 10962 S.DiagRuntimeBehavior(Loc, RHS.get(), 10963 S.PDiag(diag::warn_shift_negative) 10964 << RHS.get()->getSourceRange()); 10965 return; 10966 } 10967 10968 QualType LHSExprType = LHS.get()->getType(); 10969 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10970 if (LHSExprType->isExtIntType()) 10971 LeftSize = S.Context.getIntWidth(LHSExprType); 10972 else if (LHSExprType->isFixedPointType()) { 10973 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10974 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10975 } 10976 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10977 if (Right.uge(LeftBits)) { 10978 S.DiagRuntimeBehavior(Loc, RHS.get(), 10979 S.PDiag(diag::warn_shift_gt_typewidth) 10980 << RHS.get()->getSourceRange()); 10981 return; 10982 } 10983 10984 // FIXME: We probably need to handle fixed point types specially here. 10985 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10986 return; 10987 10988 // When left shifting an ICE which is signed, we can check for overflow which 10989 // according to C++ standards prior to C++2a has undefined behavior 10990 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10991 // more than the maximum value representable in the result type, so never 10992 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10993 // expression is still probably a bug.) 10994 Expr::EvalResult LHSResult; 10995 if (LHS.get()->isValueDependent() || 10996 LHSType->hasUnsignedIntegerRepresentation() || 10997 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10998 return; 10999 llvm::APSInt Left = LHSResult.Val.getInt(); 11000 11001 // If LHS does not have a signed type and non-negative value 11002 // then, the behavior is undefined before C++2a. Warn about it. 11003 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 11004 !S.getLangOpts().CPlusPlus20) { 11005 S.DiagRuntimeBehavior(Loc, LHS.get(), 11006 S.PDiag(diag::warn_shift_lhs_negative) 11007 << LHS.get()->getSourceRange()); 11008 return; 11009 } 11010 11011 llvm::APInt ResultBits = 11012 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 11013 if (LeftBits.uge(ResultBits)) 11014 return; 11015 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 11016 Result = Result.shl(Right); 11017 11018 // Print the bit representation of the signed integer as an unsigned 11019 // hexadecimal number. 11020 SmallString<40> HexResult; 11021 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 11022 11023 // If we are only missing a sign bit, this is less likely to result in actual 11024 // bugs -- if the result is cast back to an unsigned type, it will have the 11025 // expected value. Thus we place this behind a different warning that can be 11026 // turned off separately if needed. 11027 if (LeftBits == ResultBits - 1) { 11028 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 11029 << HexResult << LHSType 11030 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11031 return; 11032 } 11033 11034 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 11035 << HexResult.str() << Result.getMinSignedBits() << LHSType 11036 << Left.getBitWidth() << LHS.get()->getSourceRange() 11037 << RHS.get()->getSourceRange(); 11038 } 11039 11040 /// Return the resulting type when a vector is shifted 11041 /// by a scalar or vector shift amount. 11042 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 11043 SourceLocation Loc, bool IsCompAssign) { 11044 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 11045 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 11046 !LHS.get()->getType()->isVectorType()) { 11047 S.Diag(Loc, diag::err_shift_rhs_only_vector) 11048 << RHS.get()->getType() << LHS.get()->getType() 11049 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11050 return QualType(); 11051 } 11052 11053 if (!IsCompAssign) { 11054 LHS = S.UsualUnaryConversions(LHS.get()); 11055 if (LHS.isInvalid()) return QualType(); 11056 } 11057 11058 RHS = S.UsualUnaryConversions(RHS.get()); 11059 if (RHS.isInvalid()) return QualType(); 11060 11061 QualType LHSType = LHS.get()->getType(); 11062 // Note that LHS might be a scalar because the routine calls not only in 11063 // OpenCL case. 11064 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 11065 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 11066 11067 // Note that RHS might not be a vector. 11068 QualType RHSType = RHS.get()->getType(); 11069 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 11070 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 11071 11072 // The operands need to be integers. 11073 if (!LHSEleType->isIntegerType()) { 11074 S.Diag(Loc, diag::err_typecheck_expect_int) 11075 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11076 return QualType(); 11077 } 11078 11079 if (!RHSEleType->isIntegerType()) { 11080 S.Diag(Loc, diag::err_typecheck_expect_int) 11081 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11082 return QualType(); 11083 } 11084 11085 if (!LHSVecTy) { 11086 assert(RHSVecTy); 11087 if (IsCompAssign) 11088 return RHSType; 11089 if (LHSEleType != RHSEleType) { 11090 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 11091 LHSEleType = RHSEleType; 11092 } 11093 QualType VecTy = 11094 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11095 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11096 LHSType = VecTy; 11097 } else if (RHSVecTy) { 11098 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11099 // are applied component-wise. So if RHS is a vector, then ensure 11100 // that the number of elements is the same as LHS... 11101 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11102 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11103 << LHS.get()->getType() << RHS.get()->getType() 11104 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11105 return QualType(); 11106 } 11107 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11108 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11109 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11110 if (LHSBT != RHSBT && 11111 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11112 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11113 << LHS.get()->getType() << RHS.get()->getType() 11114 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11115 } 11116 } 11117 } else { 11118 // ...else expand RHS to match the number of elements in LHS. 11119 QualType VecTy = 11120 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11121 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11122 } 11123 11124 return LHSType; 11125 } 11126 11127 // C99 6.5.7 11128 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11129 SourceLocation Loc, BinaryOperatorKind Opc, 11130 bool IsCompAssign) { 11131 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11132 11133 // Vector shifts promote their scalar inputs to vector type. 11134 if (LHS.get()->getType()->isVectorType() || 11135 RHS.get()->getType()->isVectorType()) { 11136 if (LangOpts.ZVector) { 11137 // The shift operators for the z vector extensions work basically 11138 // like general shifts, except that neither the LHS nor the RHS is 11139 // allowed to be a "vector bool". 11140 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11141 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11142 return InvalidOperands(Loc, LHS, RHS); 11143 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11144 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11145 return InvalidOperands(Loc, LHS, RHS); 11146 } 11147 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11148 } 11149 11150 // Shifts don't perform usual arithmetic conversions, they just do integer 11151 // promotions on each operand. C99 6.5.7p3 11152 11153 // For the LHS, do usual unary conversions, but then reset them away 11154 // if this is a compound assignment. 11155 ExprResult OldLHS = LHS; 11156 LHS = UsualUnaryConversions(LHS.get()); 11157 if (LHS.isInvalid()) 11158 return QualType(); 11159 QualType LHSType = LHS.get()->getType(); 11160 if (IsCompAssign) LHS = OldLHS; 11161 11162 // The RHS is simpler. 11163 RHS = UsualUnaryConversions(RHS.get()); 11164 if (RHS.isInvalid()) 11165 return QualType(); 11166 QualType RHSType = RHS.get()->getType(); 11167 11168 // C99 6.5.7p2: Each of the operands shall have integer type. 11169 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11170 if ((!LHSType->isFixedPointOrIntegerType() && 11171 !LHSType->hasIntegerRepresentation()) || 11172 !RHSType->hasIntegerRepresentation()) 11173 return InvalidOperands(Loc, LHS, RHS); 11174 11175 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11176 // hasIntegerRepresentation() above instead of this. 11177 if (isScopedEnumerationType(LHSType) || 11178 isScopedEnumerationType(RHSType)) { 11179 return InvalidOperands(Loc, LHS, RHS); 11180 } 11181 // Sanity-check shift operands 11182 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11183 11184 // "The type of the result is that of the promoted left operand." 11185 return LHSType; 11186 } 11187 11188 /// Diagnose bad pointer comparisons. 11189 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11190 ExprResult &LHS, ExprResult &RHS, 11191 bool IsError) { 11192 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11193 : diag::ext_typecheck_comparison_of_distinct_pointers) 11194 << LHS.get()->getType() << RHS.get()->getType() 11195 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11196 } 11197 11198 /// Returns false if the pointers are converted to a composite type, 11199 /// true otherwise. 11200 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11201 ExprResult &LHS, ExprResult &RHS) { 11202 // C++ [expr.rel]p2: 11203 // [...] Pointer conversions (4.10) and qualification 11204 // conversions (4.4) are performed on pointer operands (or on 11205 // a pointer operand and a null pointer constant) to bring 11206 // them to their composite pointer type. [...] 11207 // 11208 // C++ [expr.eq]p1 uses the same notion for (in)equality 11209 // comparisons of pointers. 11210 11211 QualType LHSType = LHS.get()->getType(); 11212 QualType RHSType = RHS.get()->getType(); 11213 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11214 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11215 11216 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11217 if (T.isNull()) { 11218 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11219 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11220 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11221 else 11222 S.InvalidOperands(Loc, LHS, RHS); 11223 return true; 11224 } 11225 11226 return false; 11227 } 11228 11229 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11230 ExprResult &LHS, 11231 ExprResult &RHS, 11232 bool IsError) { 11233 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11234 : diag::ext_typecheck_comparison_of_fptr_to_void) 11235 << LHS.get()->getType() << RHS.get()->getType() 11236 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11237 } 11238 11239 static bool isObjCObjectLiteral(ExprResult &E) { 11240 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11241 case Stmt::ObjCArrayLiteralClass: 11242 case Stmt::ObjCDictionaryLiteralClass: 11243 case Stmt::ObjCStringLiteralClass: 11244 case Stmt::ObjCBoxedExprClass: 11245 return true; 11246 default: 11247 // Note that ObjCBoolLiteral is NOT an object literal! 11248 return false; 11249 } 11250 } 11251 11252 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11253 const ObjCObjectPointerType *Type = 11254 LHS->getType()->getAs<ObjCObjectPointerType>(); 11255 11256 // If this is not actually an Objective-C object, bail out. 11257 if (!Type) 11258 return false; 11259 11260 // Get the LHS object's interface type. 11261 QualType InterfaceType = Type->getPointeeType(); 11262 11263 // If the RHS isn't an Objective-C object, bail out. 11264 if (!RHS->getType()->isObjCObjectPointerType()) 11265 return false; 11266 11267 // Try to find the -isEqual: method. 11268 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11269 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11270 InterfaceType, 11271 /*IsInstance=*/true); 11272 if (!Method) { 11273 if (Type->isObjCIdType()) { 11274 // For 'id', just check the global pool. 11275 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11276 /*receiverId=*/true); 11277 } else { 11278 // Check protocols. 11279 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11280 /*IsInstance=*/true); 11281 } 11282 } 11283 11284 if (!Method) 11285 return false; 11286 11287 QualType T = Method->parameters()[0]->getType(); 11288 if (!T->isObjCObjectPointerType()) 11289 return false; 11290 11291 QualType R = Method->getReturnType(); 11292 if (!R->isScalarType()) 11293 return false; 11294 11295 return true; 11296 } 11297 11298 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11299 FromE = FromE->IgnoreParenImpCasts(); 11300 switch (FromE->getStmtClass()) { 11301 default: 11302 break; 11303 case Stmt::ObjCStringLiteralClass: 11304 // "string literal" 11305 return LK_String; 11306 case Stmt::ObjCArrayLiteralClass: 11307 // "array literal" 11308 return LK_Array; 11309 case Stmt::ObjCDictionaryLiteralClass: 11310 // "dictionary literal" 11311 return LK_Dictionary; 11312 case Stmt::BlockExprClass: 11313 return LK_Block; 11314 case Stmt::ObjCBoxedExprClass: { 11315 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11316 switch (Inner->getStmtClass()) { 11317 case Stmt::IntegerLiteralClass: 11318 case Stmt::FloatingLiteralClass: 11319 case Stmt::CharacterLiteralClass: 11320 case Stmt::ObjCBoolLiteralExprClass: 11321 case Stmt::CXXBoolLiteralExprClass: 11322 // "numeric literal" 11323 return LK_Numeric; 11324 case Stmt::ImplicitCastExprClass: { 11325 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11326 // Boolean literals can be represented by implicit casts. 11327 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11328 return LK_Numeric; 11329 break; 11330 } 11331 default: 11332 break; 11333 } 11334 return LK_Boxed; 11335 } 11336 } 11337 return LK_None; 11338 } 11339 11340 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11341 ExprResult &LHS, ExprResult &RHS, 11342 BinaryOperator::Opcode Opc){ 11343 Expr *Literal; 11344 Expr *Other; 11345 if (isObjCObjectLiteral(LHS)) { 11346 Literal = LHS.get(); 11347 Other = RHS.get(); 11348 } else { 11349 Literal = RHS.get(); 11350 Other = LHS.get(); 11351 } 11352 11353 // Don't warn on comparisons against nil. 11354 Other = Other->IgnoreParenCasts(); 11355 if (Other->isNullPointerConstant(S.getASTContext(), 11356 Expr::NPC_ValueDependentIsNotNull)) 11357 return; 11358 11359 // This should be kept in sync with warn_objc_literal_comparison. 11360 // LK_String should always be after the other literals, since it has its own 11361 // warning flag. 11362 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11363 assert(LiteralKind != Sema::LK_Block); 11364 if (LiteralKind == Sema::LK_None) { 11365 llvm_unreachable("Unknown Objective-C object literal kind"); 11366 } 11367 11368 if (LiteralKind == Sema::LK_String) 11369 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11370 << Literal->getSourceRange(); 11371 else 11372 S.Diag(Loc, diag::warn_objc_literal_comparison) 11373 << LiteralKind << Literal->getSourceRange(); 11374 11375 if (BinaryOperator::isEqualityOp(Opc) && 11376 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11377 SourceLocation Start = LHS.get()->getBeginLoc(); 11378 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11379 CharSourceRange OpRange = 11380 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11381 11382 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11383 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11384 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11385 << FixItHint::CreateInsertion(End, "]"); 11386 } 11387 } 11388 11389 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11390 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11391 ExprResult &RHS, SourceLocation Loc, 11392 BinaryOperatorKind Opc) { 11393 // Check that left hand side is !something. 11394 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11395 if (!UO || UO->getOpcode() != UO_LNot) return; 11396 11397 // Only check if the right hand side is non-bool arithmetic type. 11398 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11399 11400 // Make sure that the something in !something is not bool. 11401 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11402 if (SubExpr->isKnownToHaveBooleanValue()) return; 11403 11404 // Emit warning. 11405 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11406 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11407 << Loc << IsBitwiseOp; 11408 11409 // First note suggest !(x < y) 11410 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11411 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11412 FirstClose = S.getLocForEndOfToken(FirstClose); 11413 if (FirstClose.isInvalid()) 11414 FirstOpen = SourceLocation(); 11415 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11416 << IsBitwiseOp 11417 << FixItHint::CreateInsertion(FirstOpen, "(") 11418 << FixItHint::CreateInsertion(FirstClose, ")"); 11419 11420 // Second note suggests (!x) < y 11421 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11422 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11423 SecondClose = S.getLocForEndOfToken(SecondClose); 11424 if (SecondClose.isInvalid()) 11425 SecondOpen = SourceLocation(); 11426 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11427 << FixItHint::CreateInsertion(SecondOpen, "(") 11428 << FixItHint::CreateInsertion(SecondClose, ")"); 11429 } 11430 11431 // Returns true if E refers to a non-weak array. 11432 static bool checkForArray(const Expr *E) { 11433 const ValueDecl *D = nullptr; 11434 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11435 D = DR->getDecl(); 11436 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11437 if (Mem->isImplicitAccess()) 11438 D = Mem->getMemberDecl(); 11439 } 11440 if (!D) 11441 return false; 11442 return D->getType()->isArrayType() && !D->isWeak(); 11443 } 11444 11445 /// Diagnose some forms of syntactically-obvious tautological comparison. 11446 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11447 Expr *LHS, Expr *RHS, 11448 BinaryOperatorKind Opc) { 11449 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11450 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11451 11452 QualType LHSType = LHS->getType(); 11453 QualType RHSType = RHS->getType(); 11454 if (LHSType->hasFloatingRepresentation() || 11455 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11456 S.inTemplateInstantiation()) 11457 return; 11458 11459 // Comparisons between two array types are ill-formed for operator<=>, so 11460 // we shouldn't emit any additional warnings about it. 11461 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11462 return; 11463 11464 // For non-floating point types, check for self-comparisons of the form 11465 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11466 // often indicate logic errors in the program. 11467 // 11468 // NOTE: Don't warn about comparison expressions resulting from macro 11469 // expansion. Also don't warn about comparisons which are only self 11470 // comparisons within a template instantiation. The warnings should catch 11471 // obvious cases in the definition of the template anyways. The idea is to 11472 // warn when the typed comparison operator will always evaluate to the same 11473 // result. 11474 11475 // Used for indexing into %select in warn_comparison_always 11476 enum { 11477 AlwaysConstant, 11478 AlwaysTrue, 11479 AlwaysFalse, 11480 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11481 }; 11482 11483 // C++2a [depr.array.comp]: 11484 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11485 // operands of array type are deprecated. 11486 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11487 RHSStripped->getType()->isArrayType()) { 11488 S.Diag(Loc, diag::warn_depr_array_comparison) 11489 << LHS->getSourceRange() << RHS->getSourceRange() 11490 << LHSStripped->getType() << RHSStripped->getType(); 11491 // Carry on to produce the tautological comparison warning, if this 11492 // expression is potentially-evaluated, we can resolve the array to a 11493 // non-weak declaration, and so on. 11494 } 11495 11496 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11497 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11498 unsigned Result; 11499 switch (Opc) { 11500 case BO_EQ: 11501 case BO_LE: 11502 case BO_GE: 11503 Result = AlwaysTrue; 11504 break; 11505 case BO_NE: 11506 case BO_LT: 11507 case BO_GT: 11508 Result = AlwaysFalse; 11509 break; 11510 case BO_Cmp: 11511 Result = AlwaysEqual; 11512 break; 11513 default: 11514 Result = AlwaysConstant; 11515 break; 11516 } 11517 S.DiagRuntimeBehavior(Loc, nullptr, 11518 S.PDiag(diag::warn_comparison_always) 11519 << 0 /*self-comparison*/ 11520 << Result); 11521 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11522 // What is it always going to evaluate to? 11523 unsigned Result; 11524 switch (Opc) { 11525 case BO_EQ: // e.g. array1 == array2 11526 Result = AlwaysFalse; 11527 break; 11528 case BO_NE: // e.g. array1 != array2 11529 Result = AlwaysTrue; 11530 break; 11531 default: // e.g. array1 <= array2 11532 // The best we can say is 'a constant' 11533 Result = AlwaysConstant; 11534 break; 11535 } 11536 S.DiagRuntimeBehavior(Loc, nullptr, 11537 S.PDiag(diag::warn_comparison_always) 11538 << 1 /*array comparison*/ 11539 << Result); 11540 } 11541 } 11542 11543 if (isa<CastExpr>(LHSStripped)) 11544 LHSStripped = LHSStripped->IgnoreParenCasts(); 11545 if (isa<CastExpr>(RHSStripped)) 11546 RHSStripped = RHSStripped->IgnoreParenCasts(); 11547 11548 // Warn about comparisons against a string constant (unless the other 11549 // operand is null); the user probably wants string comparison function. 11550 Expr *LiteralString = nullptr; 11551 Expr *LiteralStringStripped = nullptr; 11552 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11553 !RHSStripped->isNullPointerConstant(S.Context, 11554 Expr::NPC_ValueDependentIsNull)) { 11555 LiteralString = LHS; 11556 LiteralStringStripped = LHSStripped; 11557 } else if ((isa<StringLiteral>(RHSStripped) || 11558 isa<ObjCEncodeExpr>(RHSStripped)) && 11559 !LHSStripped->isNullPointerConstant(S.Context, 11560 Expr::NPC_ValueDependentIsNull)) { 11561 LiteralString = RHS; 11562 LiteralStringStripped = RHSStripped; 11563 } 11564 11565 if (LiteralString) { 11566 S.DiagRuntimeBehavior(Loc, nullptr, 11567 S.PDiag(diag::warn_stringcompare) 11568 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11569 << LiteralString->getSourceRange()); 11570 } 11571 } 11572 11573 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11574 switch (CK) { 11575 default: { 11576 #ifndef NDEBUG 11577 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11578 << "\n"; 11579 #endif 11580 llvm_unreachable("unhandled cast kind"); 11581 } 11582 case CK_UserDefinedConversion: 11583 return ICK_Identity; 11584 case CK_LValueToRValue: 11585 return ICK_Lvalue_To_Rvalue; 11586 case CK_ArrayToPointerDecay: 11587 return ICK_Array_To_Pointer; 11588 case CK_FunctionToPointerDecay: 11589 return ICK_Function_To_Pointer; 11590 case CK_IntegralCast: 11591 return ICK_Integral_Conversion; 11592 case CK_FloatingCast: 11593 return ICK_Floating_Conversion; 11594 case CK_IntegralToFloating: 11595 case CK_FloatingToIntegral: 11596 return ICK_Floating_Integral; 11597 case CK_IntegralComplexCast: 11598 case CK_FloatingComplexCast: 11599 case CK_FloatingComplexToIntegralComplex: 11600 case CK_IntegralComplexToFloatingComplex: 11601 return ICK_Complex_Conversion; 11602 case CK_FloatingComplexToReal: 11603 case CK_FloatingRealToComplex: 11604 case CK_IntegralComplexToReal: 11605 case CK_IntegralRealToComplex: 11606 return ICK_Complex_Real; 11607 } 11608 } 11609 11610 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11611 QualType FromType, 11612 SourceLocation Loc) { 11613 // Check for a narrowing implicit conversion. 11614 StandardConversionSequence SCS; 11615 SCS.setAsIdentityConversion(); 11616 SCS.setToType(0, FromType); 11617 SCS.setToType(1, ToType); 11618 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11619 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11620 11621 APValue PreNarrowingValue; 11622 QualType PreNarrowingType; 11623 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11624 PreNarrowingType, 11625 /*IgnoreFloatToIntegralConversion*/ true)) { 11626 case NK_Dependent_Narrowing: 11627 // Implicit conversion to a narrower type, but the expression is 11628 // value-dependent so we can't tell whether it's actually narrowing. 11629 case NK_Not_Narrowing: 11630 return false; 11631 11632 case NK_Constant_Narrowing: 11633 // Implicit conversion to a narrower type, and the value is not a constant 11634 // expression. 11635 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11636 << /*Constant*/ 1 11637 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11638 return true; 11639 11640 case NK_Variable_Narrowing: 11641 // Implicit conversion to a narrower type, and the value is not a constant 11642 // expression. 11643 case NK_Type_Narrowing: 11644 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11645 << /*Constant*/ 0 << FromType << ToType; 11646 // TODO: It's not a constant expression, but what if the user intended it 11647 // to be? Can we produce notes to help them figure out why it isn't? 11648 return true; 11649 } 11650 llvm_unreachable("unhandled case in switch"); 11651 } 11652 11653 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11654 ExprResult &LHS, 11655 ExprResult &RHS, 11656 SourceLocation Loc) { 11657 QualType LHSType = LHS.get()->getType(); 11658 QualType RHSType = RHS.get()->getType(); 11659 // Dig out the original argument type and expression before implicit casts 11660 // were applied. These are the types/expressions we need to check the 11661 // [expr.spaceship] requirements against. 11662 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11663 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11664 QualType LHSStrippedType = LHSStripped.get()->getType(); 11665 QualType RHSStrippedType = RHSStripped.get()->getType(); 11666 11667 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11668 // other is not, the program is ill-formed. 11669 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11670 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11671 return QualType(); 11672 } 11673 11674 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11675 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11676 RHSStrippedType->isEnumeralType(); 11677 if (NumEnumArgs == 1) { 11678 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11679 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11680 if (OtherTy->hasFloatingRepresentation()) { 11681 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11682 return QualType(); 11683 } 11684 } 11685 if (NumEnumArgs == 2) { 11686 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11687 // type E, the operator yields the result of converting the operands 11688 // to the underlying type of E and applying <=> to the converted operands. 11689 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11690 S.InvalidOperands(Loc, LHS, RHS); 11691 return QualType(); 11692 } 11693 QualType IntType = 11694 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11695 assert(IntType->isArithmeticType()); 11696 11697 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11698 // promote the boolean type, and all other promotable integer types, to 11699 // avoid this. 11700 if (IntType->isPromotableIntegerType()) 11701 IntType = S.Context.getPromotedIntegerType(IntType); 11702 11703 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11704 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11705 LHSType = RHSType = IntType; 11706 } 11707 11708 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11709 // usual arithmetic conversions are applied to the operands. 11710 QualType Type = 11711 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11712 if (LHS.isInvalid() || RHS.isInvalid()) 11713 return QualType(); 11714 if (Type.isNull()) 11715 return S.InvalidOperands(Loc, LHS, RHS); 11716 11717 Optional<ComparisonCategoryType> CCT = 11718 getComparisonCategoryForBuiltinCmp(Type); 11719 if (!CCT) 11720 return S.InvalidOperands(Loc, LHS, RHS); 11721 11722 bool HasNarrowing = checkThreeWayNarrowingConversion( 11723 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11724 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11725 RHS.get()->getBeginLoc()); 11726 if (HasNarrowing) 11727 return QualType(); 11728 11729 assert(!Type.isNull() && "composite type for <=> has not been set"); 11730 11731 return S.CheckComparisonCategoryType( 11732 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11733 } 11734 11735 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11736 ExprResult &RHS, 11737 SourceLocation Loc, 11738 BinaryOperatorKind Opc) { 11739 if (Opc == BO_Cmp) 11740 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11741 11742 // C99 6.5.8p3 / C99 6.5.9p4 11743 QualType Type = 11744 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11745 if (LHS.isInvalid() || RHS.isInvalid()) 11746 return QualType(); 11747 if (Type.isNull()) 11748 return S.InvalidOperands(Loc, LHS, RHS); 11749 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11750 11751 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11752 return S.InvalidOperands(Loc, LHS, RHS); 11753 11754 // Check for comparisons of floating point operands using != and ==. 11755 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11756 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11757 11758 // The result of comparisons is 'bool' in C++, 'int' in C. 11759 return S.Context.getLogicalOperationType(); 11760 } 11761 11762 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11763 if (!NullE.get()->getType()->isAnyPointerType()) 11764 return; 11765 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11766 if (!E.get()->getType()->isAnyPointerType() && 11767 E.get()->isNullPointerConstant(Context, 11768 Expr::NPC_ValueDependentIsNotNull) == 11769 Expr::NPCK_ZeroExpression) { 11770 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11771 if (CL->getValue() == 0) 11772 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11773 << NullValue 11774 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11775 NullValue ? "NULL" : "(void *)0"); 11776 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11777 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11778 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11779 if (T == Context.CharTy) 11780 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11781 << NullValue 11782 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11783 NullValue ? "NULL" : "(void *)0"); 11784 } 11785 } 11786 } 11787 11788 // C99 6.5.8, C++ [expr.rel] 11789 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11790 SourceLocation Loc, 11791 BinaryOperatorKind Opc) { 11792 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11793 bool IsThreeWay = Opc == BO_Cmp; 11794 bool IsOrdered = IsRelational || IsThreeWay; 11795 auto IsAnyPointerType = [](ExprResult E) { 11796 QualType Ty = E.get()->getType(); 11797 return Ty->isPointerType() || Ty->isMemberPointerType(); 11798 }; 11799 11800 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11801 // type, array-to-pointer, ..., conversions are performed on both operands to 11802 // bring them to their composite type. 11803 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11804 // any type-related checks. 11805 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11806 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11807 if (LHS.isInvalid()) 11808 return QualType(); 11809 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11810 if (RHS.isInvalid()) 11811 return QualType(); 11812 } else { 11813 LHS = DefaultLvalueConversion(LHS.get()); 11814 if (LHS.isInvalid()) 11815 return QualType(); 11816 RHS = DefaultLvalueConversion(RHS.get()); 11817 if (RHS.isInvalid()) 11818 return QualType(); 11819 } 11820 11821 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11822 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11823 CheckPtrComparisonWithNullChar(LHS, RHS); 11824 CheckPtrComparisonWithNullChar(RHS, LHS); 11825 } 11826 11827 // Handle vector comparisons separately. 11828 if (LHS.get()->getType()->isVectorType() || 11829 RHS.get()->getType()->isVectorType()) 11830 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11831 11832 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11833 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11834 11835 QualType LHSType = LHS.get()->getType(); 11836 QualType RHSType = RHS.get()->getType(); 11837 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11838 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11839 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11840 11841 const Expr::NullPointerConstantKind LHSNullKind = 11842 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11843 const Expr::NullPointerConstantKind RHSNullKind = 11844 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11845 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11846 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11847 11848 auto computeResultTy = [&]() { 11849 if (Opc != BO_Cmp) 11850 return Context.getLogicalOperationType(); 11851 assert(getLangOpts().CPlusPlus); 11852 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11853 11854 QualType CompositeTy = LHS.get()->getType(); 11855 assert(!CompositeTy->isReferenceType()); 11856 11857 Optional<ComparisonCategoryType> CCT = 11858 getComparisonCategoryForBuiltinCmp(CompositeTy); 11859 if (!CCT) 11860 return InvalidOperands(Loc, LHS, RHS); 11861 11862 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11863 // P0946R0: Comparisons between a null pointer constant and an object 11864 // pointer result in std::strong_equality, which is ill-formed under 11865 // P1959R0. 11866 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11867 << (LHSIsNull ? LHS.get()->getSourceRange() 11868 : RHS.get()->getSourceRange()); 11869 return QualType(); 11870 } 11871 11872 return CheckComparisonCategoryType( 11873 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11874 }; 11875 11876 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11877 bool IsEquality = Opc == BO_EQ; 11878 if (RHSIsNull) 11879 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11880 RHS.get()->getSourceRange()); 11881 else 11882 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11883 LHS.get()->getSourceRange()); 11884 } 11885 11886 if (IsOrdered && LHSType->isFunctionPointerType() && 11887 RHSType->isFunctionPointerType()) { 11888 // Valid unless a relational comparison of function pointers 11889 bool IsError = Opc == BO_Cmp; 11890 auto DiagID = 11891 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 11892 : getLangOpts().CPlusPlus 11893 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 11894 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 11895 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 11896 << RHS.get()->getSourceRange(); 11897 if (IsError) 11898 return QualType(); 11899 } 11900 11901 if ((LHSType->isIntegerType() && !LHSIsNull) || 11902 (RHSType->isIntegerType() && !RHSIsNull)) { 11903 // Skip normal pointer conversion checks in this case; we have better 11904 // diagnostics for this below. 11905 } else if (getLangOpts().CPlusPlus) { 11906 // Equality comparison of a function pointer to a void pointer is invalid, 11907 // but we allow it as an extension. 11908 // FIXME: If we really want to allow this, should it be part of composite 11909 // pointer type computation so it works in conditionals too? 11910 if (!IsOrdered && 11911 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11912 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11913 // This is a gcc extension compatibility comparison. 11914 // In a SFINAE context, we treat this as a hard error to maintain 11915 // conformance with the C++ standard. 11916 diagnoseFunctionPointerToVoidComparison( 11917 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11918 11919 if (isSFINAEContext()) 11920 return QualType(); 11921 11922 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11923 return computeResultTy(); 11924 } 11925 11926 // C++ [expr.eq]p2: 11927 // If at least one operand is a pointer [...] bring them to their 11928 // composite pointer type. 11929 // C++ [expr.spaceship]p6 11930 // If at least one of the operands is of pointer type, [...] bring them 11931 // to their composite pointer type. 11932 // C++ [expr.rel]p2: 11933 // If both operands are pointers, [...] bring them to their composite 11934 // pointer type. 11935 // For <=>, the only valid non-pointer types are arrays and functions, and 11936 // we already decayed those, so this is really the same as the relational 11937 // comparison rule. 11938 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11939 (IsOrdered ? 2 : 1) && 11940 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11941 RHSType->isObjCObjectPointerType()))) { 11942 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11943 return QualType(); 11944 return computeResultTy(); 11945 } 11946 } else if (LHSType->isPointerType() && 11947 RHSType->isPointerType()) { // C99 6.5.8p2 11948 // All of the following pointer-related warnings are GCC extensions, except 11949 // when handling null pointer constants. 11950 QualType LCanPointeeTy = 11951 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11952 QualType RCanPointeeTy = 11953 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11954 11955 // C99 6.5.9p2 and C99 6.5.8p2 11956 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11957 RCanPointeeTy.getUnqualifiedType())) { 11958 if (IsRelational) { 11959 // Pointers both need to point to complete or incomplete types 11960 if ((LCanPointeeTy->isIncompleteType() != 11961 RCanPointeeTy->isIncompleteType()) && 11962 !getLangOpts().C11) { 11963 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11964 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11965 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11966 << RCanPointeeTy->isIncompleteType(); 11967 } 11968 } 11969 } else if (!IsRelational && 11970 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11971 // Valid unless comparison between non-null pointer and function pointer 11972 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11973 && !LHSIsNull && !RHSIsNull) 11974 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11975 /*isError*/false); 11976 } else { 11977 // Invalid 11978 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11979 } 11980 if (LCanPointeeTy != RCanPointeeTy) { 11981 // Treat NULL constant as a special case in OpenCL. 11982 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11983 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11984 Diag(Loc, 11985 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11986 << LHSType << RHSType << 0 /* comparison */ 11987 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11988 } 11989 } 11990 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11991 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11992 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11993 : CK_BitCast; 11994 if (LHSIsNull && !RHSIsNull) 11995 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11996 else 11997 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11998 } 11999 return computeResultTy(); 12000 } 12001 12002 if (getLangOpts().CPlusPlus) { 12003 // C++ [expr.eq]p4: 12004 // Two operands of type std::nullptr_t or one operand of type 12005 // std::nullptr_t and the other a null pointer constant compare equal. 12006 if (!IsOrdered && LHSIsNull && RHSIsNull) { 12007 if (LHSType->isNullPtrType()) { 12008 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12009 return computeResultTy(); 12010 } 12011 if (RHSType->isNullPtrType()) { 12012 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12013 return computeResultTy(); 12014 } 12015 } 12016 12017 // Comparison of Objective-C pointers and block pointers against nullptr_t. 12018 // These aren't covered by the composite pointer type rules. 12019 if (!IsOrdered && RHSType->isNullPtrType() && 12020 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 12021 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12022 return computeResultTy(); 12023 } 12024 if (!IsOrdered && LHSType->isNullPtrType() && 12025 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 12026 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12027 return computeResultTy(); 12028 } 12029 12030 if (IsRelational && 12031 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 12032 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 12033 // HACK: Relational comparison of nullptr_t against a pointer type is 12034 // invalid per DR583, but we allow it within std::less<> and friends, 12035 // since otherwise common uses of it break. 12036 // FIXME: Consider removing this hack once LWG fixes std::less<> and 12037 // friends to have std::nullptr_t overload candidates. 12038 DeclContext *DC = CurContext; 12039 if (isa<FunctionDecl>(DC)) 12040 DC = DC->getParent(); 12041 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 12042 if (CTSD->isInStdNamespace() && 12043 llvm::StringSwitch<bool>(CTSD->getName()) 12044 .Cases("less", "less_equal", "greater", "greater_equal", true) 12045 .Default(false)) { 12046 if (RHSType->isNullPtrType()) 12047 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12048 else 12049 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12050 return computeResultTy(); 12051 } 12052 } 12053 } 12054 12055 // C++ [expr.eq]p2: 12056 // If at least one operand is a pointer to member, [...] bring them to 12057 // their composite pointer type. 12058 if (!IsOrdered && 12059 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 12060 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12061 return QualType(); 12062 else 12063 return computeResultTy(); 12064 } 12065 } 12066 12067 // Handle block pointer types. 12068 if (!IsOrdered && LHSType->isBlockPointerType() && 12069 RHSType->isBlockPointerType()) { 12070 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 12071 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 12072 12073 if (!LHSIsNull && !RHSIsNull && 12074 !Context.typesAreCompatible(lpointee, rpointee)) { 12075 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12076 << LHSType << RHSType << LHS.get()->getSourceRange() 12077 << RHS.get()->getSourceRange(); 12078 } 12079 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12080 return computeResultTy(); 12081 } 12082 12083 // Allow block pointers to be compared with null pointer constants. 12084 if (!IsOrdered 12085 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 12086 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 12087 if (!LHSIsNull && !RHSIsNull) { 12088 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 12089 ->getPointeeType()->isVoidType()) 12090 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12091 ->getPointeeType()->isVoidType()))) 12092 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12093 << LHSType << RHSType << LHS.get()->getSourceRange() 12094 << RHS.get()->getSourceRange(); 12095 } 12096 if (LHSIsNull && !RHSIsNull) 12097 LHS = ImpCastExprToType(LHS.get(), RHSType, 12098 RHSType->isPointerType() ? CK_BitCast 12099 : CK_AnyPointerToBlockPointerCast); 12100 else 12101 RHS = ImpCastExprToType(RHS.get(), LHSType, 12102 LHSType->isPointerType() ? CK_BitCast 12103 : CK_AnyPointerToBlockPointerCast); 12104 return computeResultTy(); 12105 } 12106 12107 if (LHSType->isObjCObjectPointerType() || 12108 RHSType->isObjCObjectPointerType()) { 12109 const PointerType *LPT = LHSType->getAs<PointerType>(); 12110 const PointerType *RPT = RHSType->getAs<PointerType>(); 12111 if (LPT || RPT) { 12112 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12113 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12114 12115 if (!LPtrToVoid && !RPtrToVoid && 12116 !Context.typesAreCompatible(LHSType, RHSType)) { 12117 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12118 /*isError*/false); 12119 } 12120 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12121 // the RHS, but we have test coverage for this behavior. 12122 // FIXME: Consider using convertPointersToCompositeType in C++. 12123 if (LHSIsNull && !RHSIsNull) { 12124 Expr *E = LHS.get(); 12125 if (getLangOpts().ObjCAutoRefCount) 12126 CheckObjCConversion(SourceRange(), RHSType, E, 12127 CCK_ImplicitConversion); 12128 LHS = ImpCastExprToType(E, RHSType, 12129 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12130 } 12131 else { 12132 Expr *E = RHS.get(); 12133 if (getLangOpts().ObjCAutoRefCount) 12134 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12135 /*Diagnose=*/true, 12136 /*DiagnoseCFAudited=*/false, Opc); 12137 RHS = ImpCastExprToType(E, LHSType, 12138 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12139 } 12140 return computeResultTy(); 12141 } 12142 if (LHSType->isObjCObjectPointerType() && 12143 RHSType->isObjCObjectPointerType()) { 12144 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12145 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12146 /*isError*/false); 12147 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12148 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12149 12150 if (LHSIsNull && !RHSIsNull) 12151 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12152 else 12153 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12154 return computeResultTy(); 12155 } 12156 12157 if (!IsOrdered && LHSType->isBlockPointerType() && 12158 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12159 LHS = ImpCastExprToType(LHS.get(), RHSType, 12160 CK_BlockPointerToObjCPointerCast); 12161 return computeResultTy(); 12162 } else if (!IsOrdered && 12163 LHSType->isBlockCompatibleObjCPointerType(Context) && 12164 RHSType->isBlockPointerType()) { 12165 RHS = ImpCastExprToType(RHS.get(), LHSType, 12166 CK_BlockPointerToObjCPointerCast); 12167 return computeResultTy(); 12168 } 12169 } 12170 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12171 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12172 unsigned DiagID = 0; 12173 bool isError = false; 12174 if (LangOpts.DebuggerSupport) { 12175 // Under a debugger, allow the comparison of pointers to integers, 12176 // since users tend to want to compare addresses. 12177 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12178 (RHSIsNull && RHSType->isIntegerType())) { 12179 if (IsOrdered) { 12180 isError = getLangOpts().CPlusPlus; 12181 DiagID = 12182 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12183 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12184 } 12185 } else if (getLangOpts().CPlusPlus) { 12186 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12187 isError = true; 12188 } else if (IsOrdered) 12189 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12190 else 12191 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12192 12193 if (DiagID) { 12194 Diag(Loc, DiagID) 12195 << LHSType << RHSType << LHS.get()->getSourceRange() 12196 << RHS.get()->getSourceRange(); 12197 if (isError) 12198 return QualType(); 12199 } 12200 12201 if (LHSType->isIntegerType()) 12202 LHS = ImpCastExprToType(LHS.get(), RHSType, 12203 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12204 else 12205 RHS = ImpCastExprToType(RHS.get(), LHSType, 12206 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12207 return computeResultTy(); 12208 } 12209 12210 // Handle block pointers. 12211 if (!IsOrdered && RHSIsNull 12212 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12213 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12214 return computeResultTy(); 12215 } 12216 if (!IsOrdered && LHSIsNull 12217 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12218 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12219 return computeResultTy(); 12220 } 12221 12222 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 12223 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12224 return computeResultTy(); 12225 } 12226 12227 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12228 return computeResultTy(); 12229 } 12230 12231 if (LHSIsNull && RHSType->isQueueT()) { 12232 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12233 return computeResultTy(); 12234 } 12235 12236 if (LHSType->isQueueT() && RHSIsNull) { 12237 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12238 return computeResultTy(); 12239 } 12240 } 12241 12242 return InvalidOperands(Loc, LHS, RHS); 12243 } 12244 12245 // Return a signed ext_vector_type that is of identical size and number of 12246 // elements. For floating point vectors, return an integer type of identical 12247 // size and number of elements. In the non ext_vector_type case, search from 12248 // the largest type to the smallest type to avoid cases where long long == long, 12249 // where long gets picked over long long. 12250 QualType Sema::GetSignedVectorType(QualType V) { 12251 const VectorType *VTy = V->castAs<VectorType>(); 12252 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12253 12254 if (isa<ExtVectorType>(VTy)) { 12255 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12256 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12257 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12258 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12259 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12260 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12261 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12262 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12263 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12264 "Unhandled vector element size in vector compare"); 12265 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12266 } 12267 12268 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12269 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12270 VectorType::GenericVector); 12271 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12272 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12273 VectorType::GenericVector); 12274 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12275 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12276 VectorType::GenericVector); 12277 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12278 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12279 VectorType::GenericVector); 12280 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12281 "Unhandled vector element size in vector compare"); 12282 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12283 VectorType::GenericVector); 12284 } 12285 12286 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12287 /// operates on extended vector types. Instead of producing an IntTy result, 12288 /// like a scalar comparison, a vector comparison produces a vector of integer 12289 /// types. 12290 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12291 SourceLocation Loc, 12292 BinaryOperatorKind Opc) { 12293 if (Opc == BO_Cmp) { 12294 Diag(Loc, diag::err_three_way_vector_comparison); 12295 return QualType(); 12296 } 12297 12298 // Check to make sure we're operating on vectors of the same type and width, 12299 // Allowing one side to be a scalar of element type. 12300 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12301 /*AllowBothBool*/true, 12302 /*AllowBoolConversions*/getLangOpts().ZVector); 12303 if (vType.isNull()) 12304 return vType; 12305 12306 QualType LHSType = LHS.get()->getType(); 12307 12308 // Determine the return type of a vector compare. By default clang will return 12309 // a scalar for all vector compares except vector bool and vector pixel. 12310 // With the gcc compiler we will always return a vector type and with the xl 12311 // compiler we will always return a scalar type. This switch allows choosing 12312 // which behavior is prefered. 12313 if (getLangOpts().AltiVec) { 12314 switch (getLangOpts().getAltivecSrcCompat()) { 12315 case LangOptions::AltivecSrcCompatKind::Mixed: 12316 // If AltiVec, the comparison results in a numeric type, i.e. 12317 // bool for C++, int for C 12318 if (vType->castAs<VectorType>()->getVectorKind() == 12319 VectorType::AltiVecVector) 12320 return Context.getLogicalOperationType(); 12321 else 12322 Diag(Loc, diag::warn_deprecated_altivec_src_compat); 12323 break; 12324 case LangOptions::AltivecSrcCompatKind::GCC: 12325 // For GCC we always return the vector type. 12326 break; 12327 case LangOptions::AltivecSrcCompatKind::XL: 12328 return Context.getLogicalOperationType(); 12329 break; 12330 } 12331 } 12332 12333 // For non-floating point types, check for self-comparisons of the form 12334 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12335 // often indicate logic errors in the program. 12336 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12337 12338 // Check for comparisons of floating point operands using != and ==. 12339 if (BinaryOperator::isEqualityOp(Opc) && 12340 LHSType->hasFloatingRepresentation()) { 12341 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12342 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12343 } 12344 12345 // Return a signed type for the vector. 12346 return GetSignedVectorType(vType); 12347 } 12348 12349 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12350 const ExprResult &XorRHS, 12351 const SourceLocation Loc) { 12352 // Do not diagnose macros. 12353 if (Loc.isMacroID()) 12354 return; 12355 12356 // Do not diagnose if both LHS and RHS are macros. 12357 if (XorLHS.get()->getExprLoc().isMacroID() && 12358 XorRHS.get()->getExprLoc().isMacroID()) 12359 return; 12360 12361 bool Negative = false; 12362 bool ExplicitPlus = false; 12363 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12364 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12365 12366 if (!LHSInt) 12367 return; 12368 if (!RHSInt) { 12369 // Check negative literals. 12370 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12371 UnaryOperatorKind Opc = UO->getOpcode(); 12372 if (Opc != UO_Minus && Opc != UO_Plus) 12373 return; 12374 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12375 if (!RHSInt) 12376 return; 12377 Negative = (Opc == UO_Minus); 12378 ExplicitPlus = !Negative; 12379 } else { 12380 return; 12381 } 12382 } 12383 12384 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12385 llvm::APInt RightSideValue = RHSInt->getValue(); 12386 if (LeftSideValue != 2 && LeftSideValue != 10) 12387 return; 12388 12389 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12390 return; 12391 12392 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12393 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12394 llvm::StringRef ExprStr = 12395 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12396 12397 CharSourceRange XorRange = 12398 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12399 llvm::StringRef XorStr = 12400 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12401 // Do not diagnose if xor keyword/macro is used. 12402 if (XorStr == "xor") 12403 return; 12404 12405 std::string LHSStr = std::string(Lexer::getSourceText( 12406 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12407 S.getSourceManager(), S.getLangOpts())); 12408 std::string RHSStr = std::string(Lexer::getSourceText( 12409 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12410 S.getSourceManager(), S.getLangOpts())); 12411 12412 if (Negative) { 12413 RightSideValue = -RightSideValue; 12414 RHSStr = "-" + RHSStr; 12415 } else if (ExplicitPlus) { 12416 RHSStr = "+" + RHSStr; 12417 } 12418 12419 StringRef LHSStrRef = LHSStr; 12420 StringRef RHSStrRef = RHSStr; 12421 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12422 // literals. 12423 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12424 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12425 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12426 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12427 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12428 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12429 LHSStrRef.find('\'') != StringRef::npos || 12430 RHSStrRef.find('\'') != StringRef::npos) 12431 return; 12432 12433 bool SuggestXor = 12434 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12435 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12436 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12437 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12438 std::string SuggestedExpr = "1 << " + RHSStr; 12439 bool Overflow = false; 12440 llvm::APInt One = (LeftSideValue - 1); 12441 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12442 if (Overflow) { 12443 if (RightSideIntValue < 64) 12444 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12445 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 12446 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12447 else if (RightSideIntValue == 64) 12448 S.Diag(Loc, diag::warn_xor_used_as_pow) 12449 << ExprStr << toString(XorValue, 10, true); 12450 else 12451 return; 12452 } else { 12453 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12454 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 12455 << toString(PowValue, 10, true) 12456 << FixItHint::CreateReplacement( 12457 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12458 } 12459 12460 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12461 << ("0x2 ^ " + RHSStr) << SuggestXor; 12462 } else if (LeftSideValue == 10) { 12463 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12464 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12465 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 12466 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12467 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12468 << ("0xA ^ " + RHSStr) << SuggestXor; 12469 } 12470 } 12471 12472 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12473 SourceLocation Loc) { 12474 // Ensure that either both operands are of the same vector type, or 12475 // one operand is of a vector type and the other is of its element type. 12476 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12477 /*AllowBothBool*/true, 12478 /*AllowBoolConversions*/false); 12479 if (vType.isNull()) 12480 return InvalidOperands(Loc, LHS, RHS); 12481 if (getLangOpts().OpenCL && 12482 getLangOpts().getOpenCLCompatibleVersion() < 120 && 12483 vType->hasFloatingRepresentation()) 12484 return InvalidOperands(Loc, LHS, RHS); 12485 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12486 // usage of the logical operators && and || with vectors in C. This 12487 // check could be notionally dropped. 12488 if (!getLangOpts().CPlusPlus && 12489 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12490 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12491 12492 return GetSignedVectorType(LHS.get()->getType()); 12493 } 12494 12495 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12496 SourceLocation Loc, 12497 bool IsCompAssign) { 12498 if (!IsCompAssign) { 12499 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12500 if (LHS.isInvalid()) 12501 return QualType(); 12502 } 12503 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12504 if (RHS.isInvalid()) 12505 return QualType(); 12506 12507 // For conversion purposes, we ignore any qualifiers. 12508 // For example, "const float" and "float" are equivalent. 12509 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12510 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12511 12512 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12513 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12514 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12515 12516 if (Context.hasSameType(LHSType, RHSType)) 12517 return LHSType; 12518 12519 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12520 // case we have to return InvalidOperands. 12521 ExprResult OriginalLHS = LHS; 12522 ExprResult OriginalRHS = RHS; 12523 if (LHSMatType && !RHSMatType) { 12524 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12525 if (!RHS.isInvalid()) 12526 return LHSType; 12527 12528 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12529 } 12530 12531 if (!LHSMatType && RHSMatType) { 12532 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12533 if (!LHS.isInvalid()) 12534 return RHSType; 12535 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12536 } 12537 12538 return InvalidOperands(Loc, LHS, RHS); 12539 } 12540 12541 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12542 SourceLocation Loc, 12543 bool IsCompAssign) { 12544 if (!IsCompAssign) { 12545 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12546 if (LHS.isInvalid()) 12547 return QualType(); 12548 } 12549 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12550 if (RHS.isInvalid()) 12551 return QualType(); 12552 12553 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12554 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12555 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12556 12557 if (LHSMatType && RHSMatType) { 12558 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12559 return InvalidOperands(Loc, LHS, RHS); 12560 12561 if (!Context.hasSameType(LHSMatType->getElementType(), 12562 RHSMatType->getElementType())) 12563 return InvalidOperands(Loc, LHS, RHS); 12564 12565 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12566 LHSMatType->getNumRows(), 12567 RHSMatType->getNumColumns()); 12568 } 12569 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12570 } 12571 12572 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12573 SourceLocation Loc, 12574 BinaryOperatorKind Opc) { 12575 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12576 12577 bool IsCompAssign = 12578 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12579 12580 if (LHS.get()->getType()->isVectorType() || 12581 RHS.get()->getType()->isVectorType()) { 12582 if (LHS.get()->getType()->hasIntegerRepresentation() && 12583 RHS.get()->getType()->hasIntegerRepresentation()) 12584 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12585 /*AllowBothBool*/true, 12586 /*AllowBoolConversions*/getLangOpts().ZVector); 12587 return InvalidOperands(Loc, LHS, RHS); 12588 } 12589 12590 if (Opc == BO_And) 12591 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12592 12593 if (LHS.get()->getType()->hasFloatingRepresentation() || 12594 RHS.get()->getType()->hasFloatingRepresentation()) 12595 return InvalidOperands(Loc, LHS, RHS); 12596 12597 ExprResult LHSResult = LHS, RHSResult = RHS; 12598 QualType compType = UsualArithmeticConversions( 12599 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12600 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12601 return QualType(); 12602 LHS = LHSResult.get(); 12603 RHS = RHSResult.get(); 12604 12605 if (Opc == BO_Xor) 12606 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12607 12608 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12609 return compType; 12610 return InvalidOperands(Loc, LHS, RHS); 12611 } 12612 12613 // C99 6.5.[13,14] 12614 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12615 SourceLocation Loc, 12616 BinaryOperatorKind Opc) { 12617 // Check vector operands differently. 12618 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12619 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12620 12621 bool EnumConstantInBoolContext = false; 12622 for (const ExprResult &HS : {LHS, RHS}) { 12623 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12624 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12625 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12626 EnumConstantInBoolContext = true; 12627 } 12628 } 12629 12630 if (EnumConstantInBoolContext) 12631 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12632 12633 // Diagnose cases where the user write a logical and/or but probably meant a 12634 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12635 // is a constant. 12636 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12637 !LHS.get()->getType()->isBooleanType() && 12638 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12639 // Don't warn in macros or template instantiations. 12640 !Loc.isMacroID() && !inTemplateInstantiation()) { 12641 // If the RHS can be constant folded, and if it constant folds to something 12642 // that isn't 0 or 1 (which indicate a potential logical operation that 12643 // happened to fold to true/false) then warn. 12644 // Parens on the RHS are ignored. 12645 Expr::EvalResult EVResult; 12646 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12647 llvm::APSInt Result = EVResult.Val.getInt(); 12648 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12649 !RHS.get()->getExprLoc().isMacroID()) || 12650 (Result != 0 && Result != 1)) { 12651 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12652 << RHS.get()->getSourceRange() 12653 << (Opc == BO_LAnd ? "&&" : "||"); 12654 // Suggest replacing the logical operator with the bitwise version 12655 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12656 << (Opc == BO_LAnd ? "&" : "|") 12657 << FixItHint::CreateReplacement(SourceRange( 12658 Loc, getLocForEndOfToken(Loc)), 12659 Opc == BO_LAnd ? "&" : "|"); 12660 if (Opc == BO_LAnd) 12661 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12662 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12663 << FixItHint::CreateRemoval( 12664 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12665 RHS.get()->getEndLoc())); 12666 } 12667 } 12668 } 12669 12670 if (!Context.getLangOpts().CPlusPlus) { 12671 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12672 // not operate on the built-in scalar and vector float types. 12673 if (Context.getLangOpts().OpenCL && 12674 Context.getLangOpts().OpenCLVersion < 120) { 12675 if (LHS.get()->getType()->isFloatingType() || 12676 RHS.get()->getType()->isFloatingType()) 12677 return InvalidOperands(Loc, LHS, RHS); 12678 } 12679 12680 LHS = UsualUnaryConversions(LHS.get()); 12681 if (LHS.isInvalid()) 12682 return QualType(); 12683 12684 RHS = UsualUnaryConversions(RHS.get()); 12685 if (RHS.isInvalid()) 12686 return QualType(); 12687 12688 if (!LHS.get()->getType()->isScalarType() || 12689 !RHS.get()->getType()->isScalarType()) 12690 return InvalidOperands(Loc, LHS, RHS); 12691 12692 return Context.IntTy; 12693 } 12694 12695 // The following is safe because we only use this method for 12696 // non-overloadable operands. 12697 12698 // C++ [expr.log.and]p1 12699 // C++ [expr.log.or]p1 12700 // The operands are both contextually converted to type bool. 12701 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12702 if (LHSRes.isInvalid()) 12703 return InvalidOperands(Loc, LHS, RHS); 12704 LHS = LHSRes; 12705 12706 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12707 if (RHSRes.isInvalid()) 12708 return InvalidOperands(Loc, LHS, RHS); 12709 RHS = RHSRes; 12710 12711 // C++ [expr.log.and]p2 12712 // C++ [expr.log.or]p2 12713 // The result is a bool. 12714 return Context.BoolTy; 12715 } 12716 12717 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12718 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12719 if (!ME) return false; 12720 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12721 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12722 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12723 if (!Base) return false; 12724 return Base->getMethodDecl() != nullptr; 12725 } 12726 12727 /// Is the given expression (which must be 'const') a reference to a 12728 /// variable which was originally non-const, but which has become 12729 /// 'const' due to being captured within a block? 12730 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12731 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12732 assert(E->isLValue() && E->getType().isConstQualified()); 12733 E = E->IgnoreParens(); 12734 12735 // Must be a reference to a declaration from an enclosing scope. 12736 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12737 if (!DRE) return NCCK_None; 12738 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12739 12740 // The declaration must be a variable which is not declared 'const'. 12741 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12742 if (!var) return NCCK_None; 12743 if (var->getType().isConstQualified()) return NCCK_None; 12744 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12745 12746 // Decide whether the first capture was for a block or a lambda. 12747 DeclContext *DC = S.CurContext, *Prev = nullptr; 12748 // Decide whether the first capture was for a block or a lambda. 12749 while (DC) { 12750 // For init-capture, it is possible that the variable belongs to the 12751 // template pattern of the current context. 12752 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12753 if (var->isInitCapture() && 12754 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12755 break; 12756 if (DC == var->getDeclContext()) 12757 break; 12758 Prev = DC; 12759 DC = DC->getParent(); 12760 } 12761 // Unless we have an init-capture, we've gone one step too far. 12762 if (!var->isInitCapture()) 12763 DC = Prev; 12764 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12765 } 12766 12767 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12768 Ty = Ty.getNonReferenceType(); 12769 if (IsDereference && Ty->isPointerType()) 12770 Ty = Ty->getPointeeType(); 12771 return !Ty.isConstQualified(); 12772 } 12773 12774 // Update err_typecheck_assign_const and note_typecheck_assign_const 12775 // when this enum is changed. 12776 enum { 12777 ConstFunction, 12778 ConstVariable, 12779 ConstMember, 12780 ConstMethod, 12781 NestedConstMember, 12782 ConstUnknown, // Keep as last element 12783 }; 12784 12785 /// Emit the "read-only variable not assignable" error and print notes to give 12786 /// more information about why the variable is not assignable, such as pointing 12787 /// to the declaration of a const variable, showing that a method is const, or 12788 /// that the function is returning a const reference. 12789 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12790 SourceLocation Loc) { 12791 SourceRange ExprRange = E->getSourceRange(); 12792 12793 // Only emit one error on the first const found. All other consts will emit 12794 // a note to the error. 12795 bool DiagnosticEmitted = false; 12796 12797 // Track if the current expression is the result of a dereference, and if the 12798 // next checked expression is the result of a dereference. 12799 bool IsDereference = false; 12800 bool NextIsDereference = false; 12801 12802 // Loop to process MemberExpr chains. 12803 while (true) { 12804 IsDereference = NextIsDereference; 12805 12806 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12807 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12808 NextIsDereference = ME->isArrow(); 12809 const ValueDecl *VD = ME->getMemberDecl(); 12810 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12811 // Mutable fields can be modified even if the class is const. 12812 if (Field->isMutable()) { 12813 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12814 break; 12815 } 12816 12817 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12818 if (!DiagnosticEmitted) { 12819 S.Diag(Loc, diag::err_typecheck_assign_const) 12820 << ExprRange << ConstMember << false /*static*/ << Field 12821 << Field->getType(); 12822 DiagnosticEmitted = true; 12823 } 12824 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12825 << ConstMember << false /*static*/ << Field << Field->getType() 12826 << Field->getSourceRange(); 12827 } 12828 E = ME->getBase(); 12829 continue; 12830 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12831 if (VDecl->getType().isConstQualified()) { 12832 if (!DiagnosticEmitted) { 12833 S.Diag(Loc, diag::err_typecheck_assign_const) 12834 << ExprRange << ConstMember << true /*static*/ << VDecl 12835 << VDecl->getType(); 12836 DiagnosticEmitted = true; 12837 } 12838 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12839 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12840 << VDecl->getSourceRange(); 12841 } 12842 // Static fields do not inherit constness from parents. 12843 break; 12844 } 12845 break; // End MemberExpr 12846 } else if (const ArraySubscriptExpr *ASE = 12847 dyn_cast<ArraySubscriptExpr>(E)) { 12848 E = ASE->getBase()->IgnoreParenImpCasts(); 12849 continue; 12850 } else if (const ExtVectorElementExpr *EVE = 12851 dyn_cast<ExtVectorElementExpr>(E)) { 12852 E = EVE->getBase()->IgnoreParenImpCasts(); 12853 continue; 12854 } 12855 break; 12856 } 12857 12858 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12859 // Function calls 12860 const FunctionDecl *FD = CE->getDirectCallee(); 12861 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12862 if (!DiagnosticEmitted) { 12863 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12864 << ConstFunction << FD; 12865 DiagnosticEmitted = true; 12866 } 12867 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12868 diag::note_typecheck_assign_const) 12869 << ConstFunction << FD << FD->getReturnType() 12870 << FD->getReturnTypeSourceRange(); 12871 } 12872 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12873 // Point to variable declaration. 12874 if (const ValueDecl *VD = DRE->getDecl()) { 12875 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12876 if (!DiagnosticEmitted) { 12877 S.Diag(Loc, diag::err_typecheck_assign_const) 12878 << ExprRange << ConstVariable << VD << VD->getType(); 12879 DiagnosticEmitted = true; 12880 } 12881 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12882 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12883 } 12884 } 12885 } else if (isa<CXXThisExpr>(E)) { 12886 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12887 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12888 if (MD->isConst()) { 12889 if (!DiagnosticEmitted) { 12890 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12891 << ConstMethod << MD; 12892 DiagnosticEmitted = true; 12893 } 12894 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12895 << ConstMethod << MD << MD->getSourceRange(); 12896 } 12897 } 12898 } 12899 } 12900 12901 if (DiagnosticEmitted) 12902 return; 12903 12904 // Can't determine a more specific message, so display the generic error. 12905 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12906 } 12907 12908 enum OriginalExprKind { 12909 OEK_Variable, 12910 OEK_Member, 12911 OEK_LValue 12912 }; 12913 12914 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12915 const RecordType *Ty, 12916 SourceLocation Loc, SourceRange Range, 12917 OriginalExprKind OEK, 12918 bool &DiagnosticEmitted) { 12919 std::vector<const RecordType *> RecordTypeList; 12920 RecordTypeList.push_back(Ty); 12921 unsigned NextToCheckIndex = 0; 12922 // We walk the record hierarchy breadth-first to ensure that we print 12923 // diagnostics in field nesting order. 12924 while (RecordTypeList.size() > NextToCheckIndex) { 12925 bool IsNested = NextToCheckIndex > 0; 12926 for (const FieldDecl *Field : 12927 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12928 // First, check every field for constness. 12929 QualType FieldTy = Field->getType(); 12930 if (FieldTy.isConstQualified()) { 12931 if (!DiagnosticEmitted) { 12932 S.Diag(Loc, diag::err_typecheck_assign_const) 12933 << Range << NestedConstMember << OEK << VD 12934 << IsNested << Field; 12935 DiagnosticEmitted = true; 12936 } 12937 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12938 << NestedConstMember << IsNested << Field 12939 << FieldTy << Field->getSourceRange(); 12940 } 12941 12942 // Then we append it to the list to check next in order. 12943 FieldTy = FieldTy.getCanonicalType(); 12944 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12945 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12946 RecordTypeList.push_back(FieldRecTy); 12947 } 12948 } 12949 ++NextToCheckIndex; 12950 } 12951 } 12952 12953 /// Emit an error for the case where a record we are trying to assign to has a 12954 /// const-qualified field somewhere in its hierarchy. 12955 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12956 SourceLocation Loc) { 12957 QualType Ty = E->getType(); 12958 assert(Ty->isRecordType() && "lvalue was not record?"); 12959 SourceRange Range = E->getSourceRange(); 12960 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12961 bool DiagEmitted = false; 12962 12963 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12964 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12965 Range, OEK_Member, DiagEmitted); 12966 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12967 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12968 Range, OEK_Variable, DiagEmitted); 12969 else 12970 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12971 Range, OEK_LValue, DiagEmitted); 12972 if (!DiagEmitted) 12973 DiagnoseConstAssignment(S, E, Loc); 12974 } 12975 12976 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12977 /// emit an error and return true. If so, return false. 12978 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12979 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12980 12981 S.CheckShadowingDeclModification(E, Loc); 12982 12983 SourceLocation OrigLoc = Loc; 12984 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12985 &Loc); 12986 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12987 IsLV = Expr::MLV_InvalidMessageExpression; 12988 if (IsLV == Expr::MLV_Valid) 12989 return false; 12990 12991 unsigned DiagID = 0; 12992 bool NeedType = false; 12993 switch (IsLV) { // C99 6.5.16p2 12994 case Expr::MLV_ConstQualified: 12995 // Use a specialized diagnostic when we're assigning to an object 12996 // from an enclosing function or block. 12997 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12998 if (NCCK == NCCK_Block) 12999 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 13000 else 13001 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 13002 break; 13003 } 13004 13005 // In ARC, use some specialized diagnostics for occasions where we 13006 // infer 'const'. These are always pseudo-strong variables. 13007 if (S.getLangOpts().ObjCAutoRefCount) { 13008 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 13009 if (declRef && isa<VarDecl>(declRef->getDecl())) { 13010 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 13011 13012 // Use the normal diagnostic if it's pseudo-__strong but the 13013 // user actually wrote 'const'. 13014 if (var->isARCPseudoStrong() && 13015 (!var->getTypeSourceInfo() || 13016 !var->getTypeSourceInfo()->getType().isConstQualified())) { 13017 // There are three pseudo-strong cases: 13018 // - self 13019 ObjCMethodDecl *method = S.getCurMethodDecl(); 13020 if (method && var == method->getSelfDecl()) { 13021 DiagID = method->isClassMethod() 13022 ? diag::err_typecheck_arc_assign_self_class_method 13023 : diag::err_typecheck_arc_assign_self; 13024 13025 // - Objective-C externally_retained attribute. 13026 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 13027 isa<ParmVarDecl>(var)) { 13028 DiagID = diag::err_typecheck_arc_assign_externally_retained; 13029 13030 // - fast enumeration variables 13031 } else { 13032 DiagID = diag::err_typecheck_arr_assign_enumeration; 13033 } 13034 13035 SourceRange Assign; 13036 if (Loc != OrigLoc) 13037 Assign = SourceRange(OrigLoc, OrigLoc); 13038 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13039 // We need to preserve the AST regardless, so migration tool 13040 // can do its job. 13041 return false; 13042 } 13043 } 13044 } 13045 13046 // If none of the special cases above are triggered, then this is a 13047 // simple const assignment. 13048 if (DiagID == 0) { 13049 DiagnoseConstAssignment(S, E, Loc); 13050 return true; 13051 } 13052 13053 break; 13054 case Expr::MLV_ConstAddrSpace: 13055 DiagnoseConstAssignment(S, E, Loc); 13056 return true; 13057 case Expr::MLV_ConstQualifiedField: 13058 DiagnoseRecursiveConstFields(S, E, Loc); 13059 return true; 13060 case Expr::MLV_ArrayType: 13061 case Expr::MLV_ArrayTemporary: 13062 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 13063 NeedType = true; 13064 break; 13065 case Expr::MLV_NotObjectType: 13066 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 13067 NeedType = true; 13068 break; 13069 case Expr::MLV_LValueCast: 13070 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 13071 break; 13072 case Expr::MLV_Valid: 13073 llvm_unreachable("did not take early return for MLV_Valid"); 13074 case Expr::MLV_InvalidExpression: 13075 case Expr::MLV_MemberFunction: 13076 case Expr::MLV_ClassTemporary: 13077 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 13078 break; 13079 case Expr::MLV_IncompleteType: 13080 case Expr::MLV_IncompleteVoidType: 13081 return S.RequireCompleteType(Loc, E->getType(), 13082 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 13083 case Expr::MLV_DuplicateVectorComponents: 13084 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 13085 break; 13086 case Expr::MLV_NoSetterProperty: 13087 llvm_unreachable("readonly properties should be processed differently"); 13088 case Expr::MLV_InvalidMessageExpression: 13089 DiagID = diag::err_readonly_message_assignment; 13090 break; 13091 case Expr::MLV_SubObjCPropertySetting: 13092 DiagID = diag::err_no_subobject_property_setting; 13093 break; 13094 } 13095 13096 SourceRange Assign; 13097 if (Loc != OrigLoc) 13098 Assign = SourceRange(OrigLoc, OrigLoc); 13099 if (NeedType) 13100 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 13101 else 13102 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13103 return true; 13104 } 13105 13106 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 13107 SourceLocation Loc, 13108 Sema &Sema) { 13109 if (Sema.inTemplateInstantiation()) 13110 return; 13111 if (Sema.isUnevaluatedContext()) 13112 return; 13113 if (Loc.isInvalid() || Loc.isMacroID()) 13114 return; 13115 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 13116 return; 13117 13118 // C / C++ fields 13119 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 13120 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 13121 if (ML && MR) { 13122 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 13123 return; 13124 const ValueDecl *LHSDecl = 13125 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 13126 const ValueDecl *RHSDecl = 13127 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13128 if (LHSDecl != RHSDecl) 13129 return; 13130 if (LHSDecl->getType().isVolatileQualified()) 13131 return; 13132 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13133 if (RefTy->getPointeeType().isVolatileQualified()) 13134 return; 13135 13136 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13137 } 13138 13139 // Objective-C instance variables 13140 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13141 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13142 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13143 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13144 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13145 if (RL && RR && RL->getDecl() == RR->getDecl()) 13146 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13147 } 13148 } 13149 13150 // C99 6.5.16.1 13151 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13152 SourceLocation Loc, 13153 QualType CompoundType) { 13154 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13155 13156 // Verify that LHS is a modifiable lvalue, and emit error if not. 13157 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13158 return QualType(); 13159 13160 QualType LHSType = LHSExpr->getType(); 13161 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13162 CompoundType; 13163 // OpenCL v1.2 s6.1.1.1 p2: 13164 // The half data type can only be used to declare a pointer to a buffer that 13165 // contains half values 13166 if (getLangOpts().OpenCL && 13167 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13168 LHSType->isHalfType()) { 13169 Diag(Loc, diag::err_opencl_half_load_store) << 1 13170 << LHSType.getUnqualifiedType(); 13171 return QualType(); 13172 } 13173 13174 AssignConvertType ConvTy; 13175 if (CompoundType.isNull()) { 13176 Expr *RHSCheck = RHS.get(); 13177 13178 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13179 13180 QualType LHSTy(LHSType); 13181 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13182 if (RHS.isInvalid()) 13183 return QualType(); 13184 // Special case of NSObject attributes on c-style pointer types. 13185 if (ConvTy == IncompatiblePointer && 13186 ((Context.isObjCNSObjectType(LHSType) && 13187 RHSType->isObjCObjectPointerType()) || 13188 (Context.isObjCNSObjectType(RHSType) && 13189 LHSType->isObjCObjectPointerType()))) 13190 ConvTy = Compatible; 13191 13192 if (ConvTy == Compatible && 13193 LHSType->isObjCObjectType()) 13194 Diag(Loc, diag::err_objc_object_assignment) 13195 << LHSType; 13196 13197 // If the RHS is a unary plus or minus, check to see if they = and + are 13198 // right next to each other. If so, the user may have typo'd "x =+ 4" 13199 // instead of "x += 4". 13200 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13201 RHSCheck = ICE->getSubExpr(); 13202 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13203 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13204 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13205 // Only if the two operators are exactly adjacent. 13206 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13207 // And there is a space or other character before the subexpr of the 13208 // unary +/-. We don't want to warn on "x=-1". 13209 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13210 UO->getSubExpr()->getBeginLoc().isFileID()) { 13211 Diag(Loc, diag::warn_not_compound_assign) 13212 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13213 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13214 } 13215 } 13216 13217 if (ConvTy == Compatible) { 13218 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13219 // Warn about retain cycles where a block captures the LHS, but 13220 // not if the LHS is a simple variable into which the block is 13221 // being stored...unless that variable can be captured by reference! 13222 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13223 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13224 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13225 checkRetainCycles(LHSExpr, RHS.get()); 13226 } 13227 13228 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13229 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13230 // It is safe to assign a weak reference into a strong variable. 13231 // Although this code can still have problems: 13232 // id x = self.weakProp; 13233 // id y = self.weakProp; 13234 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13235 // paths through the function. This should be revisited if 13236 // -Wrepeated-use-of-weak is made flow-sensitive. 13237 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13238 // variable, which will be valid for the current autorelease scope. 13239 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13240 RHS.get()->getBeginLoc())) 13241 getCurFunction()->markSafeWeakUse(RHS.get()); 13242 13243 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13244 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13245 } 13246 } 13247 } else { 13248 // Compound assignment "x += y" 13249 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13250 } 13251 13252 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13253 RHS.get(), AA_Assigning)) 13254 return QualType(); 13255 13256 CheckForNullPointerDereference(*this, LHSExpr); 13257 13258 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13259 if (CompoundType.isNull()) { 13260 // C++2a [expr.ass]p5: 13261 // A simple-assignment whose left operand is of a volatile-qualified 13262 // type is deprecated unless the assignment is either a discarded-value 13263 // expression or an unevaluated operand 13264 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13265 } else { 13266 // C++2a [expr.ass]p6: 13267 // [Compound-assignment] expressions are deprecated if E1 has 13268 // volatile-qualified type 13269 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13270 } 13271 } 13272 13273 // C99 6.5.16p3: The type of an assignment expression is the type of the 13274 // left operand unless the left operand has qualified type, in which case 13275 // it is the unqualified version of the type of the left operand. 13276 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13277 // is converted to the type of the assignment expression (above). 13278 // C++ 5.17p1: the type of the assignment expression is that of its left 13279 // operand. 13280 return (getLangOpts().CPlusPlus 13281 ? LHSType : LHSType.getUnqualifiedType()); 13282 } 13283 13284 // Only ignore explicit casts to void. 13285 static bool IgnoreCommaOperand(const Expr *E) { 13286 E = E->IgnoreParens(); 13287 13288 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13289 if (CE->getCastKind() == CK_ToVoid) { 13290 return true; 13291 } 13292 13293 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13294 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13295 CE->getSubExpr()->getType()->isDependentType()) { 13296 return true; 13297 } 13298 } 13299 13300 return false; 13301 } 13302 13303 // Look for instances where it is likely the comma operator is confused with 13304 // another operator. There is an explicit list of acceptable expressions for 13305 // the left hand side of the comma operator, otherwise emit a warning. 13306 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13307 // No warnings in macros 13308 if (Loc.isMacroID()) 13309 return; 13310 13311 // Don't warn in template instantiations. 13312 if (inTemplateInstantiation()) 13313 return; 13314 13315 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13316 // instead, skip more than needed, then call back into here with the 13317 // CommaVisitor in SemaStmt.cpp. 13318 // The listed locations are the initialization and increment portions 13319 // of a for loop. The additional checks are on the condition of 13320 // if statements, do/while loops, and for loops. 13321 // Differences in scope flags for C89 mode requires the extra logic. 13322 const unsigned ForIncrementFlags = 13323 getLangOpts().C99 || getLangOpts().CPlusPlus 13324 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13325 : Scope::ContinueScope | Scope::BreakScope; 13326 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13327 const unsigned ScopeFlags = getCurScope()->getFlags(); 13328 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13329 (ScopeFlags & ForInitFlags) == ForInitFlags) 13330 return; 13331 13332 // If there are multiple comma operators used together, get the RHS of the 13333 // of the comma operator as the LHS. 13334 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13335 if (BO->getOpcode() != BO_Comma) 13336 break; 13337 LHS = BO->getRHS(); 13338 } 13339 13340 // Only allow some expressions on LHS to not warn. 13341 if (IgnoreCommaOperand(LHS)) 13342 return; 13343 13344 Diag(Loc, diag::warn_comma_operator); 13345 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13346 << LHS->getSourceRange() 13347 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13348 LangOpts.CPlusPlus ? "static_cast<void>(" 13349 : "(void)(") 13350 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13351 ")"); 13352 } 13353 13354 // C99 6.5.17 13355 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13356 SourceLocation Loc) { 13357 LHS = S.CheckPlaceholderExpr(LHS.get()); 13358 RHS = S.CheckPlaceholderExpr(RHS.get()); 13359 if (LHS.isInvalid() || RHS.isInvalid()) 13360 return QualType(); 13361 13362 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13363 // operands, but not unary promotions. 13364 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13365 13366 // So we treat the LHS as a ignored value, and in C++ we allow the 13367 // containing site to determine what should be done with the RHS. 13368 LHS = S.IgnoredValueConversions(LHS.get()); 13369 if (LHS.isInvalid()) 13370 return QualType(); 13371 13372 S.DiagnoseUnusedExprResult(LHS.get()); 13373 13374 if (!S.getLangOpts().CPlusPlus) { 13375 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13376 if (RHS.isInvalid()) 13377 return QualType(); 13378 if (!RHS.get()->getType()->isVoidType()) 13379 S.RequireCompleteType(Loc, RHS.get()->getType(), 13380 diag::err_incomplete_type); 13381 } 13382 13383 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13384 S.DiagnoseCommaOperator(LHS.get(), Loc); 13385 13386 return RHS.get()->getType(); 13387 } 13388 13389 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13390 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13391 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13392 ExprValueKind &VK, 13393 ExprObjectKind &OK, 13394 SourceLocation OpLoc, 13395 bool IsInc, bool IsPrefix) { 13396 if (Op->isTypeDependent()) 13397 return S.Context.DependentTy; 13398 13399 QualType ResType = Op->getType(); 13400 // Atomic types can be used for increment / decrement where the non-atomic 13401 // versions can, so ignore the _Atomic() specifier for the purpose of 13402 // checking. 13403 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13404 ResType = ResAtomicType->getValueType(); 13405 13406 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13407 13408 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13409 // Decrement of bool is not allowed. 13410 if (!IsInc) { 13411 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13412 return QualType(); 13413 } 13414 // Increment of bool sets it to true, but is deprecated. 13415 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13416 : diag::warn_increment_bool) 13417 << Op->getSourceRange(); 13418 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13419 // Error on enum increments and decrements in C++ mode 13420 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13421 return QualType(); 13422 } else if (ResType->isRealType()) { 13423 // OK! 13424 } else if (ResType->isPointerType()) { 13425 // C99 6.5.2.4p2, 6.5.6p2 13426 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13427 return QualType(); 13428 } else if (ResType->isObjCObjectPointerType()) { 13429 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13430 // Otherwise, we just need a complete type. 13431 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13432 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13433 return QualType(); 13434 } else if (ResType->isAnyComplexType()) { 13435 // C99 does not support ++/-- on complex types, we allow as an extension. 13436 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13437 << ResType << Op->getSourceRange(); 13438 } else if (ResType->isPlaceholderType()) { 13439 ExprResult PR = S.CheckPlaceholderExpr(Op); 13440 if (PR.isInvalid()) return QualType(); 13441 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13442 IsInc, IsPrefix); 13443 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13444 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13445 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13446 (ResType->castAs<VectorType>()->getVectorKind() != 13447 VectorType::AltiVecBool)) { 13448 // The z vector extensions allow ++ and -- for non-bool vectors. 13449 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13450 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13451 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13452 } else { 13453 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13454 << ResType << int(IsInc) << Op->getSourceRange(); 13455 return QualType(); 13456 } 13457 // At this point, we know we have a real, complex or pointer type. 13458 // Now make sure the operand is a modifiable lvalue. 13459 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13460 return QualType(); 13461 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13462 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13463 // An operand with volatile-qualified type is deprecated 13464 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13465 << IsInc << ResType; 13466 } 13467 // In C++, a prefix increment is the same type as the operand. Otherwise 13468 // (in C or with postfix), the increment is the unqualified type of the 13469 // operand. 13470 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13471 VK = VK_LValue; 13472 OK = Op->getObjectKind(); 13473 return ResType; 13474 } else { 13475 VK = VK_PRValue; 13476 return ResType.getUnqualifiedType(); 13477 } 13478 } 13479 13480 13481 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13482 /// This routine allows us to typecheck complex/recursive expressions 13483 /// where the declaration is needed for type checking. We only need to 13484 /// handle cases when the expression references a function designator 13485 /// or is an lvalue. Here are some examples: 13486 /// - &(x) => x 13487 /// - &*****f => f for f a function designator. 13488 /// - &s.xx => s 13489 /// - &s.zz[1].yy -> s, if zz is an array 13490 /// - *(x + 1) -> x, if x is an array 13491 /// - &"123"[2] -> 0 13492 /// - & __real__ x -> x 13493 /// 13494 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13495 /// members. 13496 static ValueDecl *getPrimaryDecl(Expr *E) { 13497 switch (E->getStmtClass()) { 13498 case Stmt::DeclRefExprClass: 13499 return cast<DeclRefExpr>(E)->getDecl(); 13500 case Stmt::MemberExprClass: 13501 // If this is an arrow operator, the address is an offset from 13502 // the base's value, so the object the base refers to is 13503 // irrelevant. 13504 if (cast<MemberExpr>(E)->isArrow()) 13505 return nullptr; 13506 // Otherwise, the expression refers to a part of the base 13507 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13508 case Stmt::ArraySubscriptExprClass: { 13509 // FIXME: This code shouldn't be necessary! We should catch the implicit 13510 // promotion of register arrays earlier. 13511 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13512 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13513 if (ICE->getSubExpr()->getType()->isArrayType()) 13514 return getPrimaryDecl(ICE->getSubExpr()); 13515 } 13516 return nullptr; 13517 } 13518 case Stmt::UnaryOperatorClass: { 13519 UnaryOperator *UO = cast<UnaryOperator>(E); 13520 13521 switch(UO->getOpcode()) { 13522 case UO_Real: 13523 case UO_Imag: 13524 case UO_Extension: 13525 return getPrimaryDecl(UO->getSubExpr()); 13526 default: 13527 return nullptr; 13528 } 13529 } 13530 case Stmt::ParenExprClass: 13531 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13532 case Stmt::ImplicitCastExprClass: 13533 // If the result of an implicit cast is an l-value, we care about 13534 // the sub-expression; otherwise, the result here doesn't matter. 13535 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13536 case Stmt::CXXUuidofExprClass: 13537 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13538 default: 13539 return nullptr; 13540 } 13541 } 13542 13543 namespace { 13544 enum { 13545 AO_Bit_Field = 0, 13546 AO_Vector_Element = 1, 13547 AO_Property_Expansion = 2, 13548 AO_Register_Variable = 3, 13549 AO_Matrix_Element = 4, 13550 AO_No_Error = 5 13551 }; 13552 } 13553 /// Diagnose invalid operand for address of operations. 13554 /// 13555 /// \param Type The type of operand which cannot have its address taken. 13556 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13557 Expr *E, unsigned Type) { 13558 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13559 } 13560 13561 /// CheckAddressOfOperand - The operand of & must be either a function 13562 /// designator or an lvalue designating an object. If it is an lvalue, the 13563 /// object cannot be declared with storage class register or be a bit field. 13564 /// Note: The usual conversions are *not* applied to the operand of the & 13565 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13566 /// In C++, the operand might be an overloaded function name, in which case 13567 /// we allow the '&' but retain the overloaded-function type. 13568 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13569 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13570 if (PTy->getKind() == BuiltinType::Overload) { 13571 Expr *E = OrigOp.get()->IgnoreParens(); 13572 if (!isa<OverloadExpr>(E)) { 13573 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13574 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13575 << OrigOp.get()->getSourceRange(); 13576 return QualType(); 13577 } 13578 13579 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13580 if (isa<UnresolvedMemberExpr>(Ovl)) 13581 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13582 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13583 << OrigOp.get()->getSourceRange(); 13584 return QualType(); 13585 } 13586 13587 return Context.OverloadTy; 13588 } 13589 13590 if (PTy->getKind() == BuiltinType::UnknownAny) 13591 return Context.UnknownAnyTy; 13592 13593 if (PTy->getKind() == BuiltinType::BoundMember) { 13594 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13595 << OrigOp.get()->getSourceRange(); 13596 return QualType(); 13597 } 13598 13599 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13600 if (OrigOp.isInvalid()) return QualType(); 13601 } 13602 13603 if (OrigOp.get()->isTypeDependent()) 13604 return Context.DependentTy; 13605 13606 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13607 13608 // Make sure to ignore parentheses in subsequent checks 13609 Expr *op = OrigOp.get()->IgnoreParens(); 13610 13611 // In OpenCL captures for blocks called as lambda functions 13612 // are located in the private address space. Blocks used in 13613 // enqueue_kernel can be located in a different address space 13614 // depending on a vendor implementation. Thus preventing 13615 // taking an address of the capture to avoid invalid AS casts. 13616 if (LangOpts.OpenCL) { 13617 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13618 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13619 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13620 return QualType(); 13621 } 13622 } 13623 13624 if (getLangOpts().C99) { 13625 // Implement C99-only parts of addressof rules. 13626 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13627 if (uOp->getOpcode() == UO_Deref) 13628 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13629 // (assuming the deref expression is valid). 13630 return uOp->getSubExpr()->getType(); 13631 } 13632 // Technically, there should be a check for array subscript 13633 // expressions here, but the result of one is always an lvalue anyway. 13634 } 13635 ValueDecl *dcl = getPrimaryDecl(op); 13636 13637 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13638 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13639 op->getBeginLoc())) 13640 return QualType(); 13641 13642 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13643 unsigned AddressOfError = AO_No_Error; 13644 13645 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13646 bool sfinae = (bool)isSFINAEContext(); 13647 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13648 : diag::ext_typecheck_addrof_temporary) 13649 << op->getType() << op->getSourceRange(); 13650 if (sfinae) 13651 return QualType(); 13652 // Materialize the temporary as an lvalue so that we can take its address. 13653 OrigOp = op = 13654 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13655 } else if (isa<ObjCSelectorExpr>(op)) { 13656 return Context.getPointerType(op->getType()); 13657 } else if (lval == Expr::LV_MemberFunction) { 13658 // If it's an instance method, make a member pointer. 13659 // The expression must have exactly the form &A::foo. 13660 13661 // If the underlying expression isn't a decl ref, give up. 13662 if (!isa<DeclRefExpr>(op)) { 13663 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13664 << OrigOp.get()->getSourceRange(); 13665 return QualType(); 13666 } 13667 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13668 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13669 13670 // The id-expression was parenthesized. 13671 if (OrigOp.get() != DRE) { 13672 Diag(OpLoc, diag::err_parens_pointer_member_function) 13673 << OrigOp.get()->getSourceRange(); 13674 13675 // The method was named without a qualifier. 13676 } else if (!DRE->getQualifier()) { 13677 if (MD->getParent()->getName().empty()) 13678 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13679 << op->getSourceRange(); 13680 else { 13681 SmallString<32> Str; 13682 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13683 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13684 << op->getSourceRange() 13685 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13686 } 13687 } 13688 13689 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13690 if (isa<CXXDestructorDecl>(MD)) 13691 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13692 13693 QualType MPTy = Context.getMemberPointerType( 13694 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13695 // Under the MS ABI, lock down the inheritance model now. 13696 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13697 (void)isCompleteType(OpLoc, MPTy); 13698 return MPTy; 13699 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13700 // C99 6.5.3.2p1 13701 // The operand must be either an l-value or a function designator 13702 if (!op->getType()->isFunctionType()) { 13703 // Use a special diagnostic for loads from property references. 13704 if (isa<PseudoObjectExpr>(op)) { 13705 AddressOfError = AO_Property_Expansion; 13706 } else { 13707 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13708 << op->getType() << op->getSourceRange(); 13709 return QualType(); 13710 } 13711 } 13712 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13713 // The operand cannot be a bit-field 13714 AddressOfError = AO_Bit_Field; 13715 } else if (op->getObjectKind() == OK_VectorComponent) { 13716 // The operand cannot be an element of a vector 13717 AddressOfError = AO_Vector_Element; 13718 } else if (op->getObjectKind() == OK_MatrixComponent) { 13719 // The operand cannot be an element of a matrix. 13720 AddressOfError = AO_Matrix_Element; 13721 } else if (dcl) { // C99 6.5.3.2p1 13722 // We have an lvalue with a decl. Make sure the decl is not declared 13723 // with the register storage-class specifier. 13724 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13725 // in C++ it is not error to take address of a register 13726 // variable (c++03 7.1.1P3) 13727 if (vd->getStorageClass() == SC_Register && 13728 !getLangOpts().CPlusPlus) { 13729 AddressOfError = AO_Register_Variable; 13730 } 13731 } else if (isa<MSPropertyDecl>(dcl)) { 13732 AddressOfError = AO_Property_Expansion; 13733 } else if (isa<FunctionTemplateDecl>(dcl)) { 13734 return Context.OverloadTy; 13735 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13736 // Okay: we can take the address of a field. 13737 // Could be a pointer to member, though, if there is an explicit 13738 // scope qualifier for the class. 13739 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13740 DeclContext *Ctx = dcl->getDeclContext(); 13741 if (Ctx && Ctx->isRecord()) { 13742 if (dcl->getType()->isReferenceType()) { 13743 Diag(OpLoc, 13744 diag::err_cannot_form_pointer_to_member_of_reference_type) 13745 << dcl->getDeclName() << dcl->getType(); 13746 return QualType(); 13747 } 13748 13749 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13750 Ctx = Ctx->getParent(); 13751 13752 QualType MPTy = Context.getMemberPointerType( 13753 op->getType(), 13754 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13755 // Under the MS ABI, lock down the inheritance model now. 13756 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13757 (void)isCompleteType(OpLoc, MPTy); 13758 return MPTy; 13759 } 13760 } 13761 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13762 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13763 llvm_unreachable("Unknown/unexpected decl type"); 13764 } 13765 13766 if (AddressOfError != AO_No_Error) { 13767 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13768 return QualType(); 13769 } 13770 13771 if (lval == Expr::LV_IncompleteVoidType) { 13772 // Taking the address of a void variable is technically illegal, but we 13773 // allow it in cases which are otherwise valid. 13774 // Example: "extern void x; void* y = &x;". 13775 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13776 } 13777 13778 // If the operand has type "type", the result has type "pointer to type". 13779 if (op->getType()->isObjCObjectType()) 13780 return Context.getObjCObjectPointerType(op->getType()); 13781 13782 CheckAddressOfPackedMember(op); 13783 13784 return Context.getPointerType(op->getType()); 13785 } 13786 13787 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13788 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13789 if (!DRE) 13790 return; 13791 const Decl *D = DRE->getDecl(); 13792 if (!D) 13793 return; 13794 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13795 if (!Param) 13796 return; 13797 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13798 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13799 return; 13800 if (FunctionScopeInfo *FD = S.getCurFunction()) 13801 if (!FD->ModifiedNonNullParams.count(Param)) 13802 FD->ModifiedNonNullParams.insert(Param); 13803 } 13804 13805 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13806 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13807 SourceLocation OpLoc) { 13808 if (Op->isTypeDependent()) 13809 return S.Context.DependentTy; 13810 13811 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13812 if (ConvResult.isInvalid()) 13813 return QualType(); 13814 Op = ConvResult.get(); 13815 QualType OpTy = Op->getType(); 13816 QualType Result; 13817 13818 if (isa<CXXReinterpretCastExpr>(Op)) { 13819 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13820 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13821 Op->getSourceRange()); 13822 } 13823 13824 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13825 { 13826 Result = PT->getPointeeType(); 13827 } 13828 else if (const ObjCObjectPointerType *OPT = 13829 OpTy->getAs<ObjCObjectPointerType>()) 13830 Result = OPT->getPointeeType(); 13831 else { 13832 ExprResult PR = S.CheckPlaceholderExpr(Op); 13833 if (PR.isInvalid()) return QualType(); 13834 if (PR.get() != Op) 13835 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13836 } 13837 13838 if (Result.isNull()) { 13839 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13840 << OpTy << Op->getSourceRange(); 13841 return QualType(); 13842 } 13843 13844 // Note that per both C89 and C99, indirection is always legal, even if Result 13845 // is an incomplete type or void. It would be possible to warn about 13846 // dereferencing a void pointer, but it's completely well-defined, and such a 13847 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13848 // for pointers to 'void' but is fine for any other pointer type: 13849 // 13850 // C++ [expr.unary.op]p1: 13851 // [...] the expression to which [the unary * operator] is applied shall 13852 // be a pointer to an object type, or a pointer to a function type 13853 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13854 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13855 << OpTy << Op->getSourceRange(); 13856 13857 // Dereferences are usually l-values... 13858 VK = VK_LValue; 13859 13860 // ...except that certain expressions are never l-values in C. 13861 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13862 VK = VK_PRValue; 13863 13864 return Result; 13865 } 13866 13867 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13868 BinaryOperatorKind Opc; 13869 switch (Kind) { 13870 default: llvm_unreachable("Unknown binop!"); 13871 case tok::periodstar: Opc = BO_PtrMemD; break; 13872 case tok::arrowstar: Opc = BO_PtrMemI; break; 13873 case tok::star: Opc = BO_Mul; break; 13874 case tok::slash: Opc = BO_Div; break; 13875 case tok::percent: Opc = BO_Rem; break; 13876 case tok::plus: Opc = BO_Add; break; 13877 case tok::minus: Opc = BO_Sub; break; 13878 case tok::lessless: Opc = BO_Shl; break; 13879 case tok::greatergreater: Opc = BO_Shr; break; 13880 case tok::lessequal: Opc = BO_LE; break; 13881 case tok::less: Opc = BO_LT; break; 13882 case tok::greaterequal: Opc = BO_GE; break; 13883 case tok::greater: Opc = BO_GT; break; 13884 case tok::exclaimequal: Opc = BO_NE; break; 13885 case tok::equalequal: Opc = BO_EQ; break; 13886 case tok::spaceship: Opc = BO_Cmp; break; 13887 case tok::amp: Opc = BO_And; break; 13888 case tok::caret: Opc = BO_Xor; break; 13889 case tok::pipe: Opc = BO_Or; break; 13890 case tok::ampamp: Opc = BO_LAnd; break; 13891 case tok::pipepipe: Opc = BO_LOr; break; 13892 case tok::equal: Opc = BO_Assign; break; 13893 case tok::starequal: Opc = BO_MulAssign; break; 13894 case tok::slashequal: Opc = BO_DivAssign; break; 13895 case tok::percentequal: Opc = BO_RemAssign; break; 13896 case tok::plusequal: Opc = BO_AddAssign; break; 13897 case tok::minusequal: Opc = BO_SubAssign; break; 13898 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13899 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13900 case tok::ampequal: Opc = BO_AndAssign; break; 13901 case tok::caretequal: Opc = BO_XorAssign; break; 13902 case tok::pipeequal: Opc = BO_OrAssign; break; 13903 case tok::comma: Opc = BO_Comma; break; 13904 } 13905 return Opc; 13906 } 13907 13908 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13909 tok::TokenKind Kind) { 13910 UnaryOperatorKind Opc; 13911 switch (Kind) { 13912 default: llvm_unreachable("Unknown unary op!"); 13913 case tok::plusplus: Opc = UO_PreInc; break; 13914 case tok::minusminus: Opc = UO_PreDec; break; 13915 case tok::amp: Opc = UO_AddrOf; break; 13916 case tok::star: Opc = UO_Deref; break; 13917 case tok::plus: Opc = UO_Plus; break; 13918 case tok::minus: Opc = UO_Minus; break; 13919 case tok::tilde: Opc = UO_Not; break; 13920 case tok::exclaim: Opc = UO_LNot; break; 13921 case tok::kw___real: Opc = UO_Real; break; 13922 case tok::kw___imag: Opc = UO_Imag; break; 13923 case tok::kw___extension__: Opc = UO_Extension; break; 13924 } 13925 return Opc; 13926 } 13927 13928 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13929 /// This warning suppressed in the event of macro expansions. 13930 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13931 SourceLocation OpLoc, bool IsBuiltin) { 13932 if (S.inTemplateInstantiation()) 13933 return; 13934 if (S.isUnevaluatedContext()) 13935 return; 13936 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13937 return; 13938 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13939 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13940 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13941 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13942 if (!LHSDeclRef || !RHSDeclRef || 13943 LHSDeclRef->getLocation().isMacroID() || 13944 RHSDeclRef->getLocation().isMacroID()) 13945 return; 13946 const ValueDecl *LHSDecl = 13947 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13948 const ValueDecl *RHSDecl = 13949 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13950 if (LHSDecl != RHSDecl) 13951 return; 13952 if (LHSDecl->getType().isVolatileQualified()) 13953 return; 13954 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13955 if (RefTy->getPointeeType().isVolatileQualified()) 13956 return; 13957 13958 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13959 : diag::warn_self_assignment_overloaded) 13960 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13961 << RHSExpr->getSourceRange(); 13962 } 13963 13964 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13965 /// is usually indicative of introspection within the Objective-C pointer. 13966 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13967 SourceLocation OpLoc) { 13968 if (!S.getLangOpts().ObjC) 13969 return; 13970 13971 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13972 const Expr *LHS = L.get(); 13973 const Expr *RHS = R.get(); 13974 13975 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13976 ObjCPointerExpr = LHS; 13977 OtherExpr = RHS; 13978 } 13979 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13980 ObjCPointerExpr = RHS; 13981 OtherExpr = LHS; 13982 } 13983 13984 // This warning is deliberately made very specific to reduce false 13985 // positives with logic that uses '&' for hashing. This logic mainly 13986 // looks for code trying to introspect into tagged pointers, which 13987 // code should generally never do. 13988 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13989 unsigned Diag = diag::warn_objc_pointer_masking; 13990 // Determine if we are introspecting the result of performSelectorXXX. 13991 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13992 // Special case messages to -performSelector and friends, which 13993 // can return non-pointer values boxed in a pointer value. 13994 // Some clients may wish to silence warnings in this subcase. 13995 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13996 Selector S = ME->getSelector(); 13997 StringRef SelArg0 = S.getNameForSlot(0); 13998 if (SelArg0.startswith("performSelector")) 13999 Diag = diag::warn_objc_pointer_masking_performSelector; 14000 } 14001 14002 S.Diag(OpLoc, Diag) 14003 << ObjCPointerExpr->getSourceRange(); 14004 } 14005 } 14006 14007 static NamedDecl *getDeclFromExpr(Expr *E) { 14008 if (!E) 14009 return nullptr; 14010 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 14011 return DRE->getDecl(); 14012 if (auto *ME = dyn_cast<MemberExpr>(E)) 14013 return ME->getMemberDecl(); 14014 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 14015 return IRE->getDecl(); 14016 return nullptr; 14017 } 14018 14019 // This helper function promotes a binary operator's operands (which are of a 14020 // half vector type) to a vector of floats and then truncates the result to 14021 // a vector of either half or short. 14022 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 14023 BinaryOperatorKind Opc, QualType ResultTy, 14024 ExprValueKind VK, ExprObjectKind OK, 14025 bool IsCompAssign, SourceLocation OpLoc, 14026 FPOptionsOverride FPFeatures) { 14027 auto &Context = S.getASTContext(); 14028 assert((isVector(ResultTy, Context.HalfTy) || 14029 isVector(ResultTy, Context.ShortTy)) && 14030 "Result must be a vector of half or short"); 14031 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 14032 isVector(RHS.get()->getType(), Context.HalfTy) && 14033 "both operands expected to be a half vector"); 14034 14035 RHS = convertVector(RHS.get(), Context.FloatTy, S); 14036 QualType BinOpResTy = RHS.get()->getType(); 14037 14038 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 14039 // change BinOpResTy to a vector of ints. 14040 if (isVector(ResultTy, Context.ShortTy)) 14041 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 14042 14043 if (IsCompAssign) 14044 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14045 ResultTy, VK, OK, OpLoc, FPFeatures, 14046 BinOpResTy, BinOpResTy); 14047 14048 LHS = convertVector(LHS.get(), Context.FloatTy, S); 14049 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14050 BinOpResTy, VK, OK, OpLoc, FPFeatures); 14051 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 14052 } 14053 14054 static std::pair<ExprResult, ExprResult> 14055 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 14056 Expr *RHSExpr) { 14057 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14058 if (!S.Context.isDependenceAllowed()) { 14059 // C cannot handle TypoExpr nodes on either side of a binop because it 14060 // doesn't handle dependent types properly, so make sure any TypoExprs have 14061 // been dealt with before checking the operands. 14062 LHS = S.CorrectDelayedTyposInExpr(LHS); 14063 RHS = S.CorrectDelayedTyposInExpr( 14064 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 14065 [Opc, LHS](Expr *E) { 14066 if (Opc != BO_Assign) 14067 return ExprResult(E); 14068 // Avoid correcting the RHS to the same Expr as the LHS. 14069 Decl *D = getDeclFromExpr(E); 14070 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 14071 }); 14072 } 14073 return std::make_pair(LHS, RHS); 14074 } 14075 14076 /// Returns true if conversion between vectors of halfs and vectors of floats 14077 /// is needed. 14078 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 14079 Expr *E0, Expr *E1 = nullptr) { 14080 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 14081 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 14082 return false; 14083 14084 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 14085 QualType Ty = E->IgnoreImplicit()->getType(); 14086 14087 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 14088 // to vectors of floats. Although the element type of the vectors is __fp16, 14089 // the vectors shouldn't be treated as storage-only types. See the 14090 // discussion here: https://reviews.llvm.org/rG825235c140e7 14091 if (const VectorType *VT = Ty->getAs<VectorType>()) { 14092 if (VT->getVectorKind() == VectorType::NeonVector) 14093 return false; 14094 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 14095 } 14096 return false; 14097 }; 14098 14099 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 14100 } 14101 14102 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 14103 /// operator @p Opc at location @c TokLoc. This routine only supports 14104 /// built-in operations; ActOnBinOp handles overloaded operators. 14105 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 14106 BinaryOperatorKind Opc, 14107 Expr *LHSExpr, Expr *RHSExpr) { 14108 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 14109 // The syntax only allows initializer lists on the RHS of assignment, 14110 // so we don't need to worry about accepting invalid code for 14111 // non-assignment operators. 14112 // C++11 5.17p9: 14113 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 14114 // of x = {} is x = T(). 14115 InitializationKind Kind = InitializationKind::CreateDirectList( 14116 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14117 InitializedEntity Entity = 14118 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 14119 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 14120 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 14121 if (Init.isInvalid()) 14122 return Init; 14123 RHSExpr = Init.get(); 14124 } 14125 14126 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14127 QualType ResultTy; // Result type of the binary operator. 14128 // The following two variables are used for compound assignment operators 14129 QualType CompLHSTy; // Type of LHS after promotions for computation 14130 QualType CompResultTy; // Type of computation result 14131 ExprValueKind VK = VK_PRValue; 14132 ExprObjectKind OK = OK_Ordinary; 14133 bool ConvertHalfVec = false; 14134 14135 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14136 if (!LHS.isUsable() || !RHS.isUsable()) 14137 return ExprError(); 14138 14139 if (getLangOpts().OpenCL) { 14140 QualType LHSTy = LHSExpr->getType(); 14141 QualType RHSTy = RHSExpr->getType(); 14142 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14143 // the ATOMIC_VAR_INIT macro. 14144 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14145 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14146 if (BO_Assign == Opc) 14147 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14148 else 14149 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14150 return ExprError(); 14151 } 14152 14153 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14154 // only with a builtin functions and therefore should be disallowed here. 14155 if (LHSTy->isImageType() || RHSTy->isImageType() || 14156 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14157 LHSTy->isPipeType() || RHSTy->isPipeType() || 14158 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14159 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14160 return ExprError(); 14161 } 14162 } 14163 14164 switch (Opc) { 14165 case BO_Assign: 14166 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14167 if (getLangOpts().CPlusPlus && 14168 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14169 VK = LHS.get()->getValueKind(); 14170 OK = LHS.get()->getObjectKind(); 14171 } 14172 if (!ResultTy.isNull()) { 14173 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14174 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14175 14176 // Avoid copying a block to the heap if the block is assigned to a local 14177 // auto variable that is declared in the same scope as the block. This 14178 // optimization is unsafe if the local variable is declared in an outer 14179 // scope. For example: 14180 // 14181 // BlockTy b; 14182 // { 14183 // b = ^{...}; 14184 // } 14185 // // It is unsafe to invoke the block here if it wasn't copied to the 14186 // // heap. 14187 // b(); 14188 14189 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14190 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14191 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14192 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14193 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14194 14195 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14196 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14197 NTCUC_Assignment, NTCUK_Copy); 14198 } 14199 RecordModifiableNonNullParam(*this, LHS.get()); 14200 break; 14201 case BO_PtrMemD: 14202 case BO_PtrMemI: 14203 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14204 Opc == BO_PtrMemI); 14205 break; 14206 case BO_Mul: 14207 case BO_Div: 14208 ConvertHalfVec = true; 14209 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14210 Opc == BO_Div); 14211 break; 14212 case BO_Rem: 14213 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14214 break; 14215 case BO_Add: 14216 ConvertHalfVec = true; 14217 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14218 break; 14219 case BO_Sub: 14220 ConvertHalfVec = true; 14221 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14222 break; 14223 case BO_Shl: 14224 case BO_Shr: 14225 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14226 break; 14227 case BO_LE: 14228 case BO_LT: 14229 case BO_GE: 14230 case BO_GT: 14231 ConvertHalfVec = true; 14232 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14233 break; 14234 case BO_EQ: 14235 case BO_NE: 14236 ConvertHalfVec = true; 14237 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14238 break; 14239 case BO_Cmp: 14240 ConvertHalfVec = true; 14241 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14242 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14243 break; 14244 case BO_And: 14245 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14246 LLVM_FALLTHROUGH; 14247 case BO_Xor: 14248 case BO_Or: 14249 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14250 break; 14251 case BO_LAnd: 14252 case BO_LOr: 14253 ConvertHalfVec = true; 14254 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14255 break; 14256 case BO_MulAssign: 14257 case BO_DivAssign: 14258 ConvertHalfVec = true; 14259 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14260 Opc == BO_DivAssign); 14261 CompLHSTy = CompResultTy; 14262 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14263 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14264 break; 14265 case BO_RemAssign: 14266 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14267 CompLHSTy = CompResultTy; 14268 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14269 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14270 break; 14271 case BO_AddAssign: 14272 ConvertHalfVec = true; 14273 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14274 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14275 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14276 break; 14277 case BO_SubAssign: 14278 ConvertHalfVec = true; 14279 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14280 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14281 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14282 break; 14283 case BO_ShlAssign: 14284 case BO_ShrAssign: 14285 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14286 CompLHSTy = CompResultTy; 14287 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14288 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14289 break; 14290 case BO_AndAssign: 14291 case BO_OrAssign: // fallthrough 14292 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14293 LLVM_FALLTHROUGH; 14294 case BO_XorAssign: 14295 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14296 CompLHSTy = CompResultTy; 14297 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14298 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14299 break; 14300 case BO_Comma: 14301 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14302 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14303 VK = RHS.get()->getValueKind(); 14304 OK = RHS.get()->getObjectKind(); 14305 } 14306 break; 14307 } 14308 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14309 return ExprError(); 14310 14311 // Some of the binary operations require promoting operands of half vector to 14312 // float vectors and truncating the result back to half vector. For now, we do 14313 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14314 // arm64). 14315 assert( 14316 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14317 isVector(LHS.get()->getType(), Context.HalfTy)) && 14318 "both sides are half vectors or neither sides are"); 14319 ConvertHalfVec = 14320 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14321 14322 // Check for array bounds violations for both sides of the BinaryOperator 14323 CheckArrayAccess(LHS.get()); 14324 CheckArrayAccess(RHS.get()); 14325 14326 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14327 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14328 &Context.Idents.get("object_setClass"), 14329 SourceLocation(), LookupOrdinaryName); 14330 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14331 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14332 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14333 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14334 "object_setClass(") 14335 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14336 ",") 14337 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14338 } 14339 else 14340 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14341 } 14342 else if (const ObjCIvarRefExpr *OIRE = 14343 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14344 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14345 14346 // Opc is not a compound assignment if CompResultTy is null. 14347 if (CompResultTy.isNull()) { 14348 if (ConvertHalfVec) 14349 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14350 OpLoc, CurFPFeatureOverrides()); 14351 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14352 VK, OK, OpLoc, CurFPFeatureOverrides()); 14353 } 14354 14355 // Handle compound assignments. 14356 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14357 OK_ObjCProperty) { 14358 VK = VK_LValue; 14359 OK = LHS.get()->getObjectKind(); 14360 } 14361 14362 // The LHS is not converted to the result type for fixed-point compound 14363 // assignment as the common type is computed on demand. Reset the CompLHSTy 14364 // to the LHS type we would have gotten after unary conversions. 14365 if (CompResultTy->isFixedPointType()) 14366 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14367 14368 if (ConvertHalfVec) 14369 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14370 OpLoc, CurFPFeatureOverrides()); 14371 14372 return CompoundAssignOperator::Create( 14373 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14374 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14375 } 14376 14377 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14378 /// operators are mixed in a way that suggests that the programmer forgot that 14379 /// comparison operators have higher precedence. The most typical example of 14380 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14381 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14382 SourceLocation OpLoc, Expr *LHSExpr, 14383 Expr *RHSExpr) { 14384 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14385 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14386 14387 // Check that one of the sides is a comparison operator and the other isn't. 14388 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14389 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14390 if (isLeftComp == isRightComp) 14391 return; 14392 14393 // Bitwise operations are sometimes used as eager logical ops. 14394 // Don't diagnose this. 14395 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14396 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14397 if (isLeftBitwise || isRightBitwise) 14398 return; 14399 14400 SourceRange DiagRange = isLeftComp 14401 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14402 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14403 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14404 SourceRange ParensRange = 14405 isLeftComp 14406 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14407 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14408 14409 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14410 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14411 SuggestParentheses(Self, OpLoc, 14412 Self.PDiag(diag::note_precedence_silence) << OpStr, 14413 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14414 SuggestParentheses(Self, OpLoc, 14415 Self.PDiag(diag::note_precedence_bitwise_first) 14416 << BinaryOperator::getOpcodeStr(Opc), 14417 ParensRange); 14418 } 14419 14420 /// It accepts a '&&' expr that is inside a '||' one. 14421 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14422 /// in parentheses. 14423 static void 14424 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14425 BinaryOperator *Bop) { 14426 assert(Bop->getOpcode() == BO_LAnd); 14427 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14428 << Bop->getSourceRange() << OpLoc; 14429 SuggestParentheses(Self, Bop->getOperatorLoc(), 14430 Self.PDiag(diag::note_precedence_silence) 14431 << Bop->getOpcodeStr(), 14432 Bop->getSourceRange()); 14433 } 14434 14435 /// Returns true if the given expression can be evaluated as a constant 14436 /// 'true'. 14437 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14438 bool Res; 14439 return !E->isValueDependent() && 14440 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14441 } 14442 14443 /// Returns true if the given expression can be evaluated as a constant 14444 /// 'false'. 14445 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14446 bool Res; 14447 return !E->isValueDependent() && 14448 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14449 } 14450 14451 /// Look for '&&' in the left hand of a '||' expr. 14452 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14453 Expr *LHSExpr, Expr *RHSExpr) { 14454 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14455 if (Bop->getOpcode() == BO_LAnd) { 14456 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14457 if (EvaluatesAsFalse(S, RHSExpr)) 14458 return; 14459 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14460 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14461 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14462 } else if (Bop->getOpcode() == BO_LOr) { 14463 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14464 // If it's "a || b && 1 || c" we didn't warn earlier for 14465 // "a || b && 1", but warn now. 14466 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14467 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14468 } 14469 } 14470 } 14471 } 14472 14473 /// Look for '&&' in the right hand of a '||' expr. 14474 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14475 Expr *LHSExpr, Expr *RHSExpr) { 14476 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14477 if (Bop->getOpcode() == BO_LAnd) { 14478 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14479 if (EvaluatesAsFalse(S, LHSExpr)) 14480 return; 14481 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14482 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14483 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14484 } 14485 } 14486 } 14487 14488 /// Look for bitwise op in the left or right hand of a bitwise op with 14489 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14490 /// the '&' expression in parentheses. 14491 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14492 SourceLocation OpLoc, Expr *SubExpr) { 14493 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14494 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14495 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14496 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14497 << Bop->getSourceRange() << OpLoc; 14498 SuggestParentheses(S, Bop->getOperatorLoc(), 14499 S.PDiag(diag::note_precedence_silence) 14500 << Bop->getOpcodeStr(), 14501 Bop->getSourceRange()); 14502 } 14503 } 14504 } 14505 14506 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14507 Expr *SubExpr, StringRef Shift) { 14508 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14509 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14510 StringRef Op = Bop->getOpcodeStr(); 14511 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14512 << Bop->getSourceRange() << OpLoc << Shift << Op; 14513 SuggestParentheses(S, Bop->getOperatorLoc(), 14514 S.PDiag(diag::note_precedence_silence) << Op, 14515 Bop->getSourceRange()); 14516 } 14517 } 14518 } 14519 14520 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14521 Expr *LHSExpr, Expr *RHSExpr) { 14522 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14523 if (!OCE) 14524 return; 14525 14526 FunctionDecl *FD = OCE->getDirectCallee(); 14527 if (!FD || !FD->isOverloadedOperator()) 14528 return; 14529 14530 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14531 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14532 return; 14533 14534 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14535 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14536 << (Kind == OO_LessLess); 14537 SuggestParentheses(S, OCE->getOperatorLoc(), 14538 S.PDiag(diag::note_precedence_silence) 14539 << (Kind == OO_LessLess ? "<<" : ">>"), 14540 OCE->getSourceRange()); 14541 SuggestParentheses( 14542 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14543 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14544 } 14545 14546 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14547 /// precedence. 14548 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14549 SourceLocation OpLoc, Expr *LHSExpr, 14550 Expr *RHSExpr){ 14551 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14552 if (BinaryOperator::isBitwiseOp(Opc)) 14553 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14554 14555 // Diagnose "arg1 & arg2 | arg3" 14556 if ((Opc == BO_Or || Opc == BO_Xor) && 14557 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14558 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14559 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14560 } 14561 14562 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14563 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14564 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14565 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14566 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14567 } 14568 14569 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14570 || Opc == BO_Shr) { 14571 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14572 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14573 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14574 } 14575 14576 // Warn on overloaded shift operators and comparisons, such as: 14577 // cout << 5 == 4; 14578 if (BinaryOperator::isComparisonOp(Opc)) 14579 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14580 } 14581 14582 // Binary Operators. 'Tok' is the token for the operator. 14583 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14584 tok::TokenKind Kind, 14585 Expr *LHSExpr, Expr *RHSExpr) { 14586 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14587 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14588 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14589 14590 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14591 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14592 14593 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14594 } 14595 14596 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14597 UnresolvedSetImpl &Functions) { 14598 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14599 if (OverOp != OO_None && OverOp != OO_Equal) 14600 LookupOverloadedOperatorName(OverOp, S, Functions); 14601 14602 // In C++20 onwards, we may have a second operator to look up. 14603 if (getLangOpts().CPlusPlus20) { 14604 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14605 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14606 } 14607 } 14608 14609 /// Build an overloaded binary operator expression in the given scope. 14610 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14611 BinaryOperatorKind Opc, 14612 Expr *LHS, Expr *RHS) { 14613 switch (Opc) { 14614 case BO_Assign: 14615 case BO_DivAssign: 14616 case BO_RemAssign: 14617 case BO_SubAssign: 14618 case BO_AndAssign: 14619 case BO_OrAssign: 14620 case BO_XorAssign: 14621 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14622 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14623 break; 14624 default: 14625 break; 14626 } 14627 14628 // Find all of the overloaded operators visible from this point. 14629 UnresolvedSet<16> Functions; 14630 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14631 14632 // Build the (potentially-overloaded, potentially-dependent) 14633 // binary operation. 14634 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14635 } 14636 14637 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14638 BinaryOperatorKind Opc, 14639 Expr *LHSExpr, Expr *RHSExpr) { 14640 ExprResult LHS, RHS; 14641 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14642 if (!LHS.isUsable() || !RHS.isUsable()) 14643 return ExprError(); 14644 LHSExpr = LHS.get(); 14645 RHSExpr = RHS.get(); 14646 14647 // We want to end up calling one of checkPseudoObjectAssignment 14648 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14649 // both expressions are overloadable or either is type-dependent), 14650 // or CreateBuiltinBinOp (in any other case). We also want to get 14651 // any placeholder types out of the way. 14652 14653 // Handle pseudo-objects in the LHS. 14654 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14655 // Assignments with a pseudo-object l-value need special analysis. 14656 if (pty->getKind() == BuiltinType::PseudoObject && 14657 BinaryOperator::isAssignmentOp(Opc)) 14658 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14659 14660 // Don't resolve overloads if the other type is overloadable. 14661 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14662 // We can't actually test that if we still have a placeholder, 14663 // though. Fortunately, none of the exceptions we see in that 14664 // code below are valid when the LHS is an overload set. Note 14665 // that an overload set can be dependently-typed, but it never 14666 // instantiates to having an overloadable type. 14667 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14668 if (resolvedRHS.isInvalid()) return ExprError(); 14669 RHSExpr = resolvedRHS.get(); 14670 14671 if (RHSExpr->isTypeDependent() || 14672 RHSExpr->getType()->isOverloadableType()) 14673 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14674 } 14675 14676 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14677 // template, diagnose the missing 'template' keyword instead of diagnosing 14678 // an invalid use of a bound member function. 14679 // 14680 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14681 // to C++1z [over.over]/1.4, but we already checked for that case above. 14682 if (Opc == BO_LT && inTemplateInstantiation() && 14683 (pty->getKind() == BuiltinType::BoundMember || 14684 pty->getKind() == BuiltinType::Overload)) { 14685 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14686 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14687 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14688 return isa<FunctionTemplateDecl>(ND); 14689 })) { 14690 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14691 : OE->getNameLoc(), 14692 diag::err_template_kw_missing) 14693 << OE->getName().getAsString() << ""; 14694 return ExprError(); 14695 } 14696 } 14697 14698 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14699 if (LHS.isInvalid()) return ExprError(); 14700 LHSExpr = LHS.get(); 14701 } 14702 14703 // Handle pseudo-objects in the RHS. 14704 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14705 // An overload in the RHS can potentially be resolved by the type 14706 // being assigned to. 14707 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14708 if (getLangOpts().CPlusPlus && 14709 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14710 LHSExpr->getType()->isOverloadableType())) 14711 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14712 14713 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14714 } 14715 14716 // Don't resolve overloads if the other type is overloadable. 14717 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14718 LHSExpr->getType()->isOverloadableType()) 14719 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14720 14721 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14722 if (!resolvedRHS.isUsable()) return ExprError(); 14723 RHSExpr = resolvedRHS.get(); 14724 } 14725 14726 if (getLangOpts().CPlusPlus) { 14727 // If either expression is type-dependent, always build an 14728 // overloaded op. 14729 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14730 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14731 14732 // Otherwise, build an overloaded op if either expression has an 14733 // overloadable type. 14734 if (LHSExpr->getType()->isOverloadableType() || 14735 RHSExpr->getType()->isOverloadableType()) 14736 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14737 } 14738 14739 if (getLangOpts().RecoveryAST && 14740 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14741 assert(!getLangOpts().CPlusPlus); 14742 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14743 "Should only occur in error-recovery path."); 14744 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14745 // C [6.15.16] p3: 14746 // An assignment expression has the value of the left operand after the 14747 // assignment, but is not an lvalue. 14748 return CompoundAssignOperator::Create( 14749 Context, LHSExpr, RHSExpr, Opc, 14750 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 14751 OpLoc, CurFPFeatureOverrides()); 14752 QualType ResultType; 14753 switch (Opc) { 14754 case BO_Assign: 14755 ResultType = LHSExpr->getType().getUnqualifiedType(); 14756 break; 14757 case BO_LT: 14758 case BO_GT: 14759 case BO_LE: 14760 case BO_GE: 14761 case BO_EQ: 14762 case BO_NE: 14763 case BO_LAnd: 14764 case BO_LOr: 14765 // These operators have a fixed result type regardless of operands. 14766 ResultType = Context.IntTy; 14767 break; 14768 case BO_Comma: 14769 ResultType = RHSExpr->getType(); 14770 break; 14771 default: 14772 ResultType = Context.DependentTy; 14773 break; 14774 } 14775 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14776 VK_PRValue, OK_Ordinary, OpLoc, 14777 CurFPFeatureOverrides()); 14778 } 14779 14780 // Build a built-in binary operation. 14781 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14782 } 14783 14784 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14785 if (T.isNull() || T->isDependentType()) 14786 return false; 14787 14788 if (!T->isPromotableIntegerType()) 14789 return true; 14790 14791 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14792 } 14793 14794 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14795 UnaryOperatorKind Opc, 14796 Expr *InputExpr) { 14797 ExprResult Input = InputExpr; 14798 ExprValueKind VK = VK_PRValue; 14799 ExprObjectKind OK = OK_Ordinary; 14800 QualType resultType; 14801 bool CanOverflow = false; 14802 14803 bool ConvertHalfVec = false; 14804 if (getLangOpts().OpenCL) { 14805 QualType Ty = InputExpr->getType(); 14806 // The only legal unary operation for atomics is '&'. 14807 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14808 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14809 // only with a builtin functions and therefore should be disallowed here. 14810 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14811 || Ty->isBlockPointerType())) { 14812 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14813 << InputExpr->getType() 14814 << Input.get()->getSourceRange()); 14815 } 14816 } 14817 14818 switch (Opc) { 14819 case UO_PreInc: 14820 case UO_PreDec: 14821 case UO_PostInc: 14822 case UO_PostDec: 14823 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14824 OpLoc, 14825 Opc == UO_PreInc || 14826 Opc == UO_PostInc, 14827 Opc == UO_PreInc || 14828 Opc == UO_PreDec); 14829 CanOverflow = isOverflowingIntegerType(Context, resultType); 14830 break; 14831 case UO_AddrOf: 14832 resultType = CheckAddressOfOperand(Input, OpLoc); 14833 CheckAddressOfNoDeref(InputExpr); 14834 RecordModifiableNonNullParam(*this, InputExpr); 14835 break; 14836 case UO_Deref: { 14837 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14838 if (Input.isInvalid()) return ExprError(); 14839 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14840 break; 14841 } 14842 case UO_Plus: 14843 case UO_Minus: 14844 CanOverflow = Opc == UO_Minus && 14845 isOverflowingIntegerType(Context, Input.get()->getType()); 14846 Input = UsualUnaryConversions(Input.get()); 14847 if (Input.isInvalid()) return ExprError(); 14848 // Unary plus and minus require promoting an operand of half vector to a 14849 // float vector and truncating the result back to a half vector. For now, we 14850 // do this only when HalfArgsAndReturns is set (that is, when the target is 14851 // arm or arm64). 14852 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14853 14854 // If the operand is a half vector, promote it to a float vector. 14855 if (ConvertHalfVec) 14856 Input = convertVector(Input.get(), Context.FloatTy, *this); 14857 resultType = Input.get()->getType(); 14858 if (resultType->isDependentType()) 14859 break; 14860 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14861 break; 14862 else if (resultType->isVectorType() && 14863 // The z vector extensions don't allow + or - with bool vectors. 14864 (!Context.getLangOpts().ZVector || 14865 resultType->castAs<VectorType>()->getVectorKind() != 14866 VectorType::AltiVecBool)) 14867 break; 14868 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14869 Opc == UO_Plus && 14870 resultType->isPointerType()) 14871 break; 14872 14873 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14874 << resultType << Input.get()->getSourceRange()); 14875 14876 case UO_Not: // bitwise complement 14877 Input = UsualUnaryConversions(Input.get()); 14878 if (Input.isInvalid()) 14879 return ExprError(); 14880 resultType = Input.get()->getType(); 14881 if (resultType->isDependentType()) 14882 break; 14883 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14884 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14885 // C99 does not support '~' for complex conjugation. 14886 Diag(OpLoc, diag::ext_integer_complement_complex) 14887 << resultType << Input.get()->getSourceRange(); 14888 else if (resultType->hasIntegerRepresentation()) 14889 break; 14890 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14891 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14892 // on vector float types. 14893 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14894 if (!T->isIntegerType()) 14895 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14896 << resultType << Input.get()->getSourceRange()); 14897 } else { 14898 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14899 << resultType << Input.get()->getSourceRange()); 14900 } 14901 break; 14902 14903 case UO_LNot: // logical negation 14904 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14905 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14906 if (Input.isInvalid()) return ExprError(); 14907 resultType = Input.get()->getType(); 14908 14909 // Though we still have to promote half FP to float... 14910 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14911 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14912 resultType = Context.FloatTy; 14913 } 14914 14915 if (resultType->isDependentType()) 14916 break; 14917 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14918 // C99 6.5.3.3p1: ok, fallthrough; 14919 if (Context.getLangOpts().CPlusPlus) { 14920 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14921 // operand contextually converted to bool. 14922 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14923 ScalarTypeToBooleanCastKind(resultType)); 14924 } else if (Context.getLangOpts().OpenCL && 14925 Context.getLangOpts().OpenCLVersion < 120) { 14926 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14927 // operate on scalar float types. 14928 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14929 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14930 << resultType << Input.get()->getSourceRange()); 14931 } 14932 } else if (resultType->isExtVectorType()) { 14933 if (Context.getLangOpts().OpenCL && 14934 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { 14935 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14936 // operate on vector float types. 14937 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14938 if (!T->isIntegerType()) 14939 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14940 << resultType << Input.get()->getSourceRange()); 14941 } 14942 // Vector logical not returns the signed variant of the operand type. 14943 resultType = GetSignedVectorType(resultType); 14944 break; 14945 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14946 const VectorType *VTy = resultType->castAs<VectorType>(); 14947 if (VTy->getVectorKind() != VectorType::GenericVector) 14948 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14949 << resultType << Input.get()->getSourceRange()); 14950 14951 // Vector logical not returns the signed variant of the operand type. 14952 resultType = GetSignedVectorType(resultType); 14953 break; 14954 } else { 14955 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14956 << resultType << Input.get()->getSourceRange()); 14957 } 14958 14959 // LNot always has type int. C99 6.5.3.3p5. 14960 // In C++, it's bool. C++ 5.3.1p8 14961 resultType = Context.getLogicalOperationType(); 14962 break; 14963 case UO_Real: 14964 case UO_Imag: 14965 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14966 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14967 // complex l-values to ordinary l-values and all other values to r-values. 14968 if (Input.isInvalid()) return ExprError(); 14969 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14970 if (Input.get()->isGLValue() && 14971 Input.get()->getObjectKind() == OK_Ordinary) 14972 VK = Input.get()->getValueKind(); 14973 } else if (!getLangOpts().CPlusPlus) { 14974 // In C, a volatile scalar is read by __imag. In C++, it is not. 14975 Input = DefaultLvalueConversion(Input.get()); 14976 } 14977 break; 14978 case UO_Extension: 14979 resultType = Input.get()->getType(); 14980 VK = Input.get()->getValueKind(); 14981 OK = Input.get()->getObjectKind(); 14982 break; 14983 case UO_Coawait: 14984 // It's unnecessary to represent the pass-through operator co_await in the 14985 // AST; just return the input expression instead. 14986 assert(!Input.get()->getType()->isDependentType() && 14987 "the co_await expression must be non-dependant before " 14988 "building operator co_await"); 14989 return Input; 14990 } 14991 if (resultType.isNull() || Input.isInvalid()) 14992 return ExprError(); 14993 14994 // Check for array bounds violations in the operand of the UnaryOperator, 14995 // except for the '*' and '&' operators that have to be handled specially 14996 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14997 // that are explicitly defined as valid by the standard). 14998 if (Opc != UO_AddrOf && Opc != UO_Deref) 14999 CheckArrayAccess(Input.get()); 15000 15001 auto *UO = 15002 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 15003 OpLoc, CanOverflow, CurFPFeatureOverrides()); 15004 15005 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 15006 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 15007 !isUnevaluatedContext()) 15008 ExprEvalContexts.back().PossibleDerefs.insert(UO); 15009 15010 // Convert the result back to a half vector. 15011 if (ConvertHalfVec) 15012 return convertVector(UO, Context.HalfTy, *this); 15013 return UO; 15014 } 15015 15016 /// Determine whether the given expression is a qualified member 15017 /// access expression, of a form that could be turned into a pointer to member 15018 /// with the address-of operator. 15019 bool Sema::isQualifiedMemberAccess(Expr *E) { 15020 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15021 if (!DRE->getQualifier()) 15022 return false; 15023 15024 ValueDecl *VD = DRE->getDecl(); 15025 if (!VD->isCXXClassMember()) 15026 return false; 15027 15028 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 15029 return true; 15030 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 15031 return Method->isInstance(); 15032 15033 return false; 15034 } 15035 15036 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15037 if (!ULE->getQualifier()) 15038 return false; 15039 15040 for (NamedDecl *D : ULE->decls()) { 15041 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 15042 if (Method->isInstance()) 15043 return true; 15044 } else { 15045 // Overload set does not contain methods. 15046 break; 15047 } 15048 } 15049 15050 return false; 15051 } 15052 15053 return false; 15054 } 15055 15056 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 15057 UnaryOperatorKind Opc, Expr *Input) { 15058 // First things first: handle placeholders so that the 15059 // overloaded-operator check considers the right type. 15060 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 15061 // Increment and decrement of pseudo-object references. 15062 if (pty->getKind() == BuiltinType::PseudoObject && 15063 UnaryOperator::isIncrementDecrementOp(Opc)) 15064 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 15065 15066 // extension is always a builtin operator. 15067 if (Opc == UO_Extension) 15068 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15069 15070 // & gets special logic for several kinds of placeholder. 15071 // The builtin code knows what to do. 15072 if (Opc == UO_AddrOf && 15073 (pty->getKind() == BuiltinType::Overload || 15074 pty->getKind() == BuiltinType::UnknownAny || 15075 pty->getKind() == BuiltinType::BoundMember)) 15076 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15077 15078 // Anything else needs to be handled now. 15079 ExprResult Result = CheckPlaceholderExpr(Input); 15080 if (Result.isInvalid()) return ExprError(); 15081 Input = Result.get(); 15082 } 15083 15084 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 15085 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 15086 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 15087 // Find all of the overloaded operators visible from this point. 15088 UnresolvedSet<16> Functions; 15089 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 15090 if (S && OverOp != OO_None) 15091 LookupOverloadedOperatorName(OverOp, S, Functions); 15092 15093 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 15094 } 15095 15096 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15097 } 15098 15099 // Unary Operators. 'Tok' is the token for the operator. 15100 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 15101 tok::TokenKind Op, Expr *Input) { 15102 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 15103 } 15104 15105 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 15106 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 15107 LabelDecl *TheDecl) { 15108 TheDecl->markUsed(Context); 15109 // Create the AST node. The address of a label always has type 'void*'. 15110 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 15111 Context.getPointerType(Context.VoidTy)); 15112 } 15113 15114 void Sema::ActOnStartStmtExpr() { 15115 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15116 } 15117 15118 void Sema::ActOnStmtExprError() { 15119 // Note that function is also called by TreeTransform when leaving a 15120 // StmtExpr scope without rebuilding anything. 15121 15122 DiscardCleanupsInEvaluationContext(); 15123 PopExpressionEvaluationContext(); 15124 } 15125 15126 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15127 SourceLocation RPLoc) { 15128 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15129 } 15130 15131 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15132 SourceLocation RPLoc, unsigned TemplateDepth) { 15133 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15134 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15135 15136 if (hasAnyUnrecoverableErrorsInThisFunction()) 15137 DiscardCleanupsInEvaluationContext(); 15138 assert(!Cleanup.exprNeedsCleanups() && 15139 "cleanups within StmtExpr not correctly bound!"); 15140 PopExpressionEvaluationContext(); 15141 15142 // FIXME: there are a variety of strange constraints to enforce here, for 15143 // example, it is not possible to goto into a stmt expression apparently. 15144 // More semantic analysis is needed. 15145 15146 // If there are sub-stmts in the compound stmt, take the type of the last one 15147 // as the type of the stmtexpr. 15148 QualType Ty = Context.VoidTy; 15149 bool StmtExprMayBindToTemp = false; 15150 if (!Compound->body_empty()) { 15151 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15152 if (const auto *LastStmt = 15153 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15154 if (const Expr *Value = LastStmt->getExprStmt()) { 15155 StmtExprMayBindToTemp = true; 15156 Ty = Value->getType(); 15157 } 15158 } 15159 } 15160 15161 // FIXME: Check that expression type is complete/non-abstract; statement 15162 // expressions are not lvalues. 15163 Expr *ResStmtExpr = 15164 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15165 if (StmtExprMayBindToTemp) 15166 return MaybeBindToTemporary(ResStmtExpr); 15167 return ResStmtExpr; 15168 } 15169 15170 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15171 if (ER.isInvalid()) 15172 return ExprError(); 15173 15174 // Do function/array conversion on the last expression, but not 15175 // lvalue-to-rvalue. However, initialize an unqualified type. 15176 ER = DefaultFunctionArrayConversion(ER.get()); 15177 if (ER.isInvalid()) 15178 return ExprError(); 15179 Expr *E = ER.get(); 15180 15181 if (E->isTypeDependent()) 15182 return E; 15183 15184 // In ARC, if the final expression ends in a consume, splice 15185 // the consume out and bind it later. In the alternate case 15186 // (when dealing with a retainable type), the result 15187 // initialization will create a produce. In both cases the 15188 // result will be +1, and we'll need to balance that out with 15189 // a bind. 15190 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15191 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15192 return Cast->getSubExpr(); 15193 15194 // FIXME: Provide a better location for the initialization. 15195 return PerformCopyInitialization( 15196 InitializedEntity::InitializeStmtExprResult( 15197 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15198 SourceLocation(), E); 15199 } 15200 15201 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15202 TypeSourceInfo *TInfo, 15203 ArrayRef<OffsetOfComponent> Components, 15204 SourceLocation RParenLoc) { 15205 QualType ArgTy = TInfo->getType(); 15206 bool Dependent = ArgTy->isDependentType(); 15207 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15208 15209 // We must have at least one component that refers to the type, and the first 15210 // one is known to be a field designator. Verify that the ArgTy represents 15211 // a struct/union/class. 15212 if (!Dependent && !ArgTy->isRecordType()) 15213 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15214 << ArgTy << TypeRange); 15215 15216 // Type must be complete per C99 7.17p3 because a declaring a variable 15217 // with an incomplete type would be ill-formed. 15218 if (!Dependent 15219 && RequireCompleteType(BuiltinLoc, ArgTy, 15220 diag::err_offsetof_incomplete_type, TypeRange)) 15221 return ExprError(); 15222 15223 bool DidWarnAboutNonPOD = false; 15224 QualType CurrentType = ArgTy; 15225 SmallVector<OffsetOfNode, 4> Comps; 15226 SmallVector<Expr*, 4> Exprs; 15227 for (const OffsetOfComponent &OC : Components) { 15228 if (OC.isBrackets) { 15229 // Offset of an array sub-field. TODO: Should we allow vector elements? 15230 if (!CurrentType->isDependentType()) { 15231 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15232 if(!AT) 15233 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15234 << CurrentType); 15235 CurrentType = AT->getElementType(); 15236 } else 15237 CurrentType = Context.DependentTy; 15238 15239 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15240 if (IdxRval.isInvalid()) 15241 return ExprError(); 15242 Expr *Idx = IdxRval.get(); 15243 15244 // The expression must be an integral expression. 15245 // FIXME: An integral constant expression? 15246 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15247 !Idx->getType()->isIntegerType()) 15248 return ExprError( 15249 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15250 << Idx->getSourceRange()); 15251 15252 // Record this array index. 15253 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15254 Exprs.push_back(Idx); 15255 continue; 15256 } 15257 15258 // Offset of a field. 15259 if (CurrentType->isDependentType()) { 15260 // We have the offset of a field, but we can't look into the dependent 15261 // type. Just record the identifier of the field. 15262 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15263 CurrentType = Context.DependentTy; 15264 continue; 15265 } 15266 15267 // We need to have a complete type to look into. 15268 if (RequireCompleteType(OC.LocStart, CurrentType, 15269 diag::err_offsetof_incomplete_type)) 15270 return ExprError(); 15271 15272 // Look for the designated field. 15273 const RecordType *RC = CurrentType->getAs<RecordType>(); 15274 if (!RC) 15275 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15276 << CurrentType); 15277 RecordDecl *RD = RC->getDecl(); 15278 15279 // C++ [lib.support.types]p5: 15280 // The macro offsetof accepts a restricted set of type arguments in this 15281 // International Standard. type shall be a POD structure or a POD union 15282 // (clause 9). 15283 // C++11 [support.types]p4: 15284 // If type is not a standard-layout class (Clause 9), the results are 15285 // undefined. 15286 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15287 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15288 unsigned DiagID = 15289 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15290 : diag::ext_offsetof_non_pod_type; 15291 15292 if (!IsSafe && !DidWarnAboutNonPOD && 15293 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15294 PDiag(DiagID) 15295 << SourceRange(Components[0].LocStart, OC.LocEnd) 15296 << CurrentType)) 15297 DidWarnAboutNonPOD = true; 15298 } 15299 15300 // Look for the field. 15301 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15302 LookupQualifiedName(R, RD); 15303 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15304 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15305 if (!MemberDecl) { 15306 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15307 MemberDecl = IndirectMemberDecl->getAnonField(); 15308 } 15309 15310 if (!MemberDecl) 15311 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15312 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15313 OC.LocEnd)); 15314 15315 // C99 7.17p3: 15316 // (If the specified member is a bit-field, the behavior is undefined.) 15317 // 15318 // We diagnose this as an error. 15319 if (MemberDecl->isBitField()) { 15320 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15321 << MemberDecl->getDeclName() 15322 << SourceRange(BuiltinLoc, RParenLoc); 15323 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15324 return ExprError(); 15325 } 15326 15327 RecordDecl *Parent = MemberDecl->getParent(); 15328 if (IndirectMemberDecl) 15329 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15330 15331 // If the member was found in a base class, introduce OffsetOfNodes for 15332 // the base class indirections. 15333 CXXBasePaths Paths; 15334 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15335 Paths)) { 15336 if (Paths.getDetectedVirtual()) { 15337 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15338 << MemberDecl->getDeclName() 15339 << SourceRange(BuiltinLoc, RParenLoc); 15340 return ExprError(); 15341 } 15342 15343 CXXBasePath &Path = Paths.front(); 15344 for (const CXXBasePathElement &B : Path) 15345 Comps.push_back(OffsetOfNode(B.Base)); 15346 } 15347 15348 if (IndirectMemberDecl) { 15349 for (auto *FI : IndirectMemberDecl->chain()) { 15350 assert(isa<FieldDecl>(FI)); 15351 Comps.push_back(OffsetOfNode(OC.LocStart, 15352 cast<FieldDecl>(FI), OC.LocEnd)); 15353 } 15354 } else 15355 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15356 15357 CurrentType = MemberDecl->getType().getNonReferenceType(); 15358 } 15359 15360 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15361 Comps, Exprs, RParenLoc); 15362 } 15363 15364 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15365 SourceLocation BuiltinLoc, 15366 SourceLocation TypeLoc, 15367 ParsedType ParsedArgTy, 15368 ArrayRef<OffsetOfComponent> Components, 15369 SourceLocation RParenLoc) { 15370 15371 TypeSourceInfo *ArgTInfo; 15372 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15373 if (ArgTy.isNull()) 15374 return ExprError(); 15375 15376 if (!ArgTInfo) 15377 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15378 15379 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15380 } 15381 15382 15383 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15384 Expr *CondExpr, 15385 Expr *LHSExpr, Expr *RHSExpr, 15386 SourceLocation RPLoc) { 15387 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15388 15389 ExprValueKind VK = VK_PRValue; 15390 ExprObjectKind OK = OK_Ordinary; 15391 QualType resType; 15392 bool CondIsTrue = false; 15393 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15394 resType = Context.DependentTy; 15395 } else { 15396 // The conditional expression is required to be a constant expression. 15397 llvm::APSInt condEval(32); 15398 ExprResult CondICE = VerifyIntegerConstantExpression( 15399 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15400 if (CondICE.isInvalid()) 15401 return ExprError(); 15402 CondExpr = CondICE.get(); 15403 CondIsTrue = condEval.getZExtValue(); 15404 15405 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15406 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15407 15408 resType = ActiveExpr->getType(); 15409 VK = ActiveExpr->getValueKind(); 15410 OK = ActiveExpr->getObjectKind(); 15411 } 15412 15413 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15414 resType, VK, OK, RPLoc, CondIsTrue); 15415 } 15416 15417 //===----------------------------------------------------------------------===// 15418 // Clang Extensions. 15419 //===----------------------------------------------------------------------===// 15420 15421 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15422 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15423 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15424 15425 if (LangOpts.CPlusPlus) { 15426 MangleNumberingContext *MCtx; 15427 Decl *ManglingContextDecl; 15428 std::tie(MCtx, ManglingContextDecl) = 15429 getCurrentMangleNumberContext(Block->getDeclContext()); 15430 if (MCtx) { 15431 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15432 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15433 } 15434 } 15435 15436 PushBlockScope(CurScope, Block); 15437 CurContext->addDecl(Block); 15438 if (CurScope) 15439 PushDeclContext(CurScope, Block); 15440 else 15441 CurContext = Block; 15442 15443 getCurBlock()->HasImplicitReturnType = true; 15444 15445 // Enter a new evaluation context to insulate the block from any 15446 // cleanups from the enclosing full-expression. 15447 PushExpressionEvaluationContext( 15448 ExpressionEvaluationContext::PotentiallyEvaluated); 15449 } 15450 15451 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15452 Scope *CurScope) { 15453 assert(ParamInfo.getIdentifier() == nullptr && 15454 "block-id should have no identifier!"); 15455 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15456 BlockScopeInfo *CurBlock = getCurBlock(); 15457 15458 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15459 QualType T = Sig->getType(); 15460 15461 // FIXME: We should allow unexpanded parameter packs here, but that would, 15462 // in turn, make the block expression contain unexpanded parameter packs. 15463 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15464 // Drop the parameters. 15465 FunctionProtoType::ExtProtoInfo EPI; 15466 EPI.HasTrailingReturn = false; 15467 EPI.TypeQuals.addConst(); 15468 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15469 Sig = Context.getTrivialTypeSourceInfo(T); 15470 } 15471 15472 // GetTypeForDeclarator always produces a function type for a block 15473 // literal signature. Furthermore, it is always a FunctionProtoType 15474 // unless the function was written with a typedef. 15475 assert(T->isFunctionType() && 15476 "GetTypeForDeclarator made a non-function block signature"); 15477 15478 // Look for an explicit signature in that function type. 15479 FunctionProtoTypeLoc ExplicitSignature; 15480 15481 if ((ExplicitSignature = Sig->getTypeLoc() 15482 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15483 15484 // Check whether that explicit signature was synthesized by 15485 // GetTypeForDeclarator. If so, don't save that as part of the 15486 // written signature. 15487 if (ExplicitSignature.getLocalRangeBegin() == 15488 ExplicitSignature.getLocalRangeEnd()) { 15489 // This would be much cheaper if we stored TypeLocs instead of 15490 // TypeSourceInfos. 15491 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15492 unsigned Size = Result.getFullDataSize(); 15493 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15494 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15495 15496 ExplicitSignature = FunctionProtoTypeLoc(); 15497 } 15498 } 15499 15500 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15501 CurBlock->FunctionType = T; 15502 15503 const auto *Fn = T->castAs<FunctionType>(); 15504 QualType RetTy = Fn->getReturnType(); 15505 bool isVariadic = 15506 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15507 15508 CurBlock->TheDecl->setIsVariadic(isVariadic); 15509 15510 // Context.DependentTy is used as a placeholder for a missing block 15511 // return type. TODO: what should we do with declarators like: 15512 // ^ * { ... } 15513 // If the answer is "apply template argument deduction".... 15514 if (RetTy != Context.DependentTy) { 15515 CurBlock->ReturnType = RetTy; 15516 CurBlock->TheDecl->setBlockMissingReturnType(false); 15517 CurBlock->HasImplicitReturnType = false; 15518 } 15519 15520 // Push block parameters from the declarator if we had them. 15521 SmallVector<ParmVarDecl*, 8> Params; 15522 if (ExplicitSignature) { 15523 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15524 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15525 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15526 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15527 // Diagnose this as an extension in C17 and earlier. 15528 if (!getLangOpts().C2x) 15529 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15530 } 15531 Params.push_back(Param); 15532 } 15533 15534 // Fake up parameter variables if we have a typedef, like 15535 // ^ fntype { ... } 15536 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15537 for (const auto &I : Fn->param_types()) { 15538 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15539 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15540 Params.push_back(Param); 15541 } 15542 } 15543 15544 // Set the parameters on the block decl. 15545 if (!Params.empty()) { 15546 CurBlock->TheDecl->setParams(Params); 15547 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15548 /*CheckParameterNames=*/false); 15549 } 15550 15551 // Finally we can process decl attributes. 15552 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15553 15554 // Put the parameter variables in scope. 15555 for (auto AI : CurBlock->TheDecl->parameters()) { 15556 AI->setOwningFunction(CurBlock->TheDecl); 15557 15558 // If this has an identifier, add it to the scope stack. 15559 if (AI->getIdentifier()) { 15560 CheckShadow(CurBlock->TheScope, AI); 15561 15562 PushOnScopeChains(AI, CurBlock->TheScope); 15563 } 15564 } 15565 } 15566 15567 /// ActOnBlockError - If there is an error parsing a block, this callback 15568 /// is invoked to pop the information about the block from the action impl. 15569 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15570 // Leave the expression-evaluation context. 15571 DiscardCleanupsInEvaluationContext(); 15572 PopExpressionEvaluationContext(); 15573 15574 // Pop off CurBlock, handle nested blocks. 15575 PopDeclContext(); 15576 PopFunctionScopeInfo(); 15577 } 15578 15579 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15580 /// literal was successfully completed. ^(int x){...} 15581 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15582 Stmt *Body, Scope *CurScope) { 15583 // If blocks are disabled, emit an error. 15584 if (!LangOpts.Blocks) 15585 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15586 15587 // Leave the expression-evaluation context. 15588 if (hasAnyUnrecoverableErrorsInThisFunction()) 15589 DiscardCleanupsInEvaluationContext(); 15590 assert(!Cleanup.exprNeedsCleanups() && 15591 "cleanups within block not correctly bound!"); 15592 PopExpressionEvaluationContext(); 15593 15594 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15595 BlockDecl *BD = BSI->TheDecl; 15596 15597 if (BSI->HasImplicitReturnType) 15598 deduceClosureReturnType(*BSI); 15599 15600 QualType RetTy = Context.VoidTy; 15601 if (!BSI->ReturnType.isNull()) 15602 RetTy = BSI->ReturnType; 15603 15604 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15605 QualType BlockTy; 15606 15607 // If the user wrote a function type in some form, try to use that. 15608 if (!BSI->FunctionType.isNull()) { 15609 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15610 15611 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15612 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15613 15614 // Turn protoless block types into nullary block types. 15615 if (isa<FunctionNoProtoType>(FTy)) { 15616 FunctionProtoType::ExtProtoInfo EPI; 15617 EPI.ExtInfo = Ext; 15618 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15619 15620 // Otherwise, if we don't need to change anything about the function type, 15621 // preserve its sugar structure. 15622 } else if (FTy->getReturnType() == RetTy && 15623 (!NoReturn || FTy->getNoReturnAttr())) { 15624 BlockTy = BSI->FunctionType; 15625 15626 // Otherwise, make the minimal modifications to the function type. 15627 } else { 15628 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15629 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15630 EPI.TypeQuals = Qualifiers(); 15631 EPI.ExtInfo = Ext; 15632 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15633 } 15634 15635 // If we don't have a function type, just build one from nothing. 15636 } else { 15637 FunctionProtoType::ExtProtoInfo EPI; 15638 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15639 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15640 } 15641 15642 DiagnoseUnusedParameters(BD->parameters()); 15643 BlockTy = Context.getBlockPointerType(BlockTy); 15644 15645 // If needed, diagnose invalid gotos and switches in the block. 15646 if (getCurFunction()->NeedsScopeChecking() && 15647 !PP.isCodeCompletionEnabled()) 15648 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15649 15650 BD->setBody(cast<CompoundStmt>(Body)); 15651 15652 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15653 DiagnoseUnguardedAvailabilityViolations(BD); 15654 15655 // Try to apply the named return value optimization. We have to check again 15656 // if we can do this, though, because blocks keep return statements around 15657 // to deduce an implicit return type. 15658 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15659 !BD->isDependentContext()) 15660 computeNRVO(Body, BSI); 15661 15662 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15663 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15664 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15665 NTCUK_Destruct|NTCUK_Copy); 15666 15667 PopDeclContext(); 15668 15669 // Set the captured variables on the block. 15670 SmallVector<BlockDecl::Capture, 4> Captures; 15671 for (Capture &Cap : BSI->Captures) { 15672 if (Cap.isInvalid() || Cap.isThisCapture()) 15673 continue; 15674 15675 VarDecl *Var = Cap.getVariable(); 15676 Expr *CopyExpr = nullptr; 15677 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15678 if (const RecordType *Record = 15679 Cap.getCaptureType()->getAs<RecordType>()) { 15680 // The capture logic needs the destructor, so make sure we mark it. 15681 // Usually this is unnecessary because most local variables have 15682 // their destructors marked at declaration time, but parameters are 15683 // an exception because it's technically only the call site that 15684 // actually requires the destructor. 15685 if (isa<ParmVarDecl>(Var)) 15686 FinalizeVarWithDestructor(Var, Record); 15687 15688 // Enter a separate potentially-evaluated context while building block 15689 // initializers to isolate their cleanups from those of the block 15690 // itself. 15691 // FIXME: Is this appropriate even when the block itself occurs in an 15692 // unevaluated operand? 15693 EnterExpressionEvaluationContext EvalContext( 15694 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15695 15696 SourceLocation Loc = Cap.getLocation(); 15697 15698 ExprResult Result = BuildDeclarationNameExpr( 15699 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15700 15701 // According to the blocks spec, the capture of a variable from 15702 // the stack requires a const copy constructor. This is not true 15703 // of the copy/move done to move a __block variable to the heap. 15704 if (!Result.isInvalid() && 15705 !Result.get()->getType().isConstQualified()) { 15706 Result = ImpCastExprToType(Result.get(), 15707 Result.get()->getType().withConst(), 15708 CK_NoOp, VK_LValue); 15709 } 15710 15711 if (!Result.isInvalid()) { 15712 Result = PerformCopyInitialization( 15713 InitializedEntity::InitializeBlock(Var->getLocation(), 15714 Cap.getCaptureType(), false), 15715 Loc, Result.get()); 15716 } 15717 15718 // Build a full-expression copy expression if initialization 15719 // succeeded and used a non-trivial constructor. Recover from 15720 // errors by pretending that the copy isn't necessary. 15721 if (!Result.isInvalid() && 15722 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15723 ->isTrivial()) { 15724 Result = MaybeCreateExprWithCleanups(Result); 15725 CopyExpr = Result.get(); 15726 } 15727 } 15728 } 15729 15730 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15731 CopyExpr); 15732 Captures.push_back(NewCap); 15733 } 15734 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15735 15736 // Pop the block scope now but keep it alive to the end of this function. 15737 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15738 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15739 15740 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15741 15742 // If the block isn't obviously global, i.e. it captures anything at 15743 // all, then we need to do a few things in the surrounding context: 15744 if (Result->getBlockDecl()->hasCaptures()) { 15745 // First, this expression has a new cleanup object. 15746 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15747 Cleanup.setExprNeedsCleanups(true); 15748 15749 // It also gets a branch-protected scope if any of the captured 15750 // variables needs destruction. 15751 for (const auto &CI : Result->getBlockDecl()->captures()) { 15752 const VarDecl *var = CI.getVariable(); 15753 if (var->getType().isDestructedType() != QualType::DK_none) { 15754 setFunctionHasBranchProtectedScope(); 15755 break; 15756 } 15757 } 15758 } 15759 15760 if (getCurFunction()) 15761 getCurFunction()->addBlock(BD); 15762 15763 return Result; 15764 } 15765 15766 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15767 SourceLocation RPLoc) { 15768 TypeSourceInfo *TInfo; 15769 GetTypeFromParser(Ty, &TInfo); 15770 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15771 } 15772 15773 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15774 Expr *E, TypeSourceInfo *TInfo, 15775 SourceLocation RPLoc) { 15776 Expr *OrigExpr = E; 15777 bool IsMS = false; 15778 15779 // CUDA device code does not support varargs. 15780 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15781 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15782 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15783 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15784 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15785 } 15786 } 15787 15788 // NVPTX does not support va_arg expression. 15789 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15790 Context.getTargetInfo().getTriple().isNVPTX()) 15791 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15792 15793 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15794 // as Microsoft ABI on an actual Microsoft platform, where 15795 // __builtin_ms_va_list and __builtin_va_list are the same.) 15796 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15797 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15798 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15799 if (Context.hasSameType(MSVaListType, E->getType())) { 15800 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15801 return ExprError(); 15802 IsMS = true; 15803 } 15804 } 15805 15806 // Get the va_list type 15807 QualType VaListType = Context.getBuiltinVaListType(); 15808 if (!IsMS) { 15809 if (VaListType->isArrayType()) { 15810 // Deal with implicit array decay; for example, on x86-64, 15811 // va_list is an array, but it's supposed to decay to 15812 // a pointer for va_arg. 15813 VaListType = Context.getArrayDecayedType(VaListType); 15814 // Make sure the input expression also decays appropriately. 15815 ExprResult Result = UsualUnaryConversions(E); 15816 if (Result.isInvalid()) 15817 return ExprError(); 15818 E = Result.get(); 15819 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15820 // If va_list is a record type and we are compiling in C++ mode, 15821 // check the argument using reference binding. 15822 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15823 Context, Context.getLValueReferenceType(VaListType), false); 15824 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15825 if (Init.isInvalid()) 15826 return ExprError(); 15827 E = Init.getAs<Expr>(); 15828 } else { 15829 // Otherwise, the va_list argument must be an l-value because 15830 // it is modified by va_arg. 15831 if (!E->isTypeDependent() && 15832 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15833 return ExprError(); 15834 } 15835 } 15836 15837 if (!IsMS && !E->isTypeDependent() && 15838 !Context.hasSameType(VaListType, E->getType())) 15839 return ExprError( 15840 Diag(E->getBeginLoc(), 15841 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15842 << OrigExpr->getType() << E->getSourceRange()); 15843 15844 if (!TInfo->getType()->isDependentType()) { 15845 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15846 diag::err_second_parameter_to_va_arg_incomplete, 15847 TInfo->getTypeLoc())) 15848 return ExprError(); 15849 15850 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15851 TInfo->getType(), 15852 diag::err_second_parameter_to_va_arg_abstract, 15853 TInfo->getTypeLoc())) 15854 return ExprError(); 15855 15856 if (!TInfo->getType().isPODType(Context)) { 15857 Diag(TInfo->getTypeLoc().getBeginLoc(), 15858 TInfo->getType()->isObjCLifetimeType() 15859 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15860 : diag::warn_second_parameter_to_va_arg_not_pod) 15861 << TInfo->getType() 15862 << TInfo->getTypeLoc().getSourceRange(); 15863 } 15864 15865 // Check for va_arg where arguments of the given type will be promoted 15866 // (i.e. this va_arg is guaranteed to have undefined behavior). 15867 QualType PromoteType; 15868 if (TInfo->getType()->isPromotableIntegerType()) { 15869 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15870 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 15871 // and C2x 7.16.1.1p2 says, in part: 15872 // If type is not compatible with the type of the actual next argument 15873 // (as promoted according to the default argument promotions), the 15874 // behavior is undefined, except for the following cases: 15875 // - both types are pointers to qualified or unqualified versions of 15876 // compatible types; 15877 // - one type is a signed integer type, the other type is the 15878 // corresponding unsigned integer type, and the value is 15879 // representable in both types; 15880 // - one type is pointer to qualified or unqualified void and the 15881 // other is a pointer to a qualified or unqualified character type. 15882 // Given that type compatibility is the primary requirement (ignoring 15883 // qualifications), you would think we could call typesAreCompatible() 15884 // directly to test this. However, in C++, that checks for *same type*, 15885 // which causes false positives when passing an enumeration type to 15886 // va_arg. Instead, get the underlying type of the enumeration and pass 15887 // that. 15888 QualType UnderlyingType = TInfo->getType(); 15889 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 15890 UnderlyingType = ET->getDecl()->getIntegerType(); 15891 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15892 /*CompareUnqualified*/ true)) 15893 PromoteType = QualType(); 15894 15895 // If the types are still not compatible, we need to test whether the 15896 // promoted type and the underlying type are the same except for 15897 // signedness. Ask the AST for the correctly corresponding type and see 15898 // if that's compatible. 15899 if (!PromoteType.isNull() && 15900 PromoteType->isUnsignedIntegerType() != 15901 UnderlyingType->isUnsignedIntegerType()) { 15902 UnderlyingType = 15903 UnderlyingType->isUnsignedIntegerType() 15904 ? Context.getCorrespondingSignedType(UnderlyingType) 15905 : Context.getCorrespondingUnsignedType(UnderlyingType); 15906 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15907 /*CompareUnqualified*/ true)) 15908 PromoteType = QualType(); 15909 } 15910 } 15911 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15912 PromoteType = Context.DoubleTy; 15913 if (!PromoteType.isNull()) 15914 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15915 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15916 << TInfo->getType() 15917 << PromoteType 15918 << TInfo->getTypeLoc().getSourceRange()); 15919 } 15920 15921 QualType T = TInfo->getType().getNonLValueExprType(Context); 15922 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15923 } 15924 15925 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15926 // The type of __null will be int or long, depending on the size of 15927 // pointers on the target. 15928 QualType Ty; 15929 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15930 if (pw == Context.getTargetInfo().getIntWidth()) 15931 Ty = Context.IntTy; 15932 else if (pw == Context.getTargetInfo().getLongWidth()) 15933 Ty = Context.LongTy; 15934 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15935 Ty = Context.LongLongTy; 15936 else { 15937 llvm_unreachable("I don't know size of pointer!"); 15938 } 15939 15940 return new (Context) GNUNullExpr(Ty, TokenLoc); 15941 } 15942 15943 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15944 SourceLocation BuiltinLoc, 15945 SourceLocation RPLoc) { 15946 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15947 } 15948 15949 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15950 SourceLocation BuiltinLoc, 15951 SourceLocation RPLoc, 15952 DeclContext *ParentContext) { 15953 return new (Context) 15954 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15955 } 15956 15957 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15958 bool Diagnose) { 15959 if (!getLangOpts().ObjC) 15960 return false; 15961 15962 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15963 if (!PT) 15964 return false; 15965 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15966 15967 // Ignore any parens, implicit casts (should only be 15968 // array-to-pointer decays), and not-so-opaque values. The last is 15969 // important for making this trigger for property assignments. 15970 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15971 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15972 if (OV->getSourceExpr()) 15973 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15974 15975 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15976 if (!PT->isObjCIdType() && 15977 !(ID && ID->getIdentifier()->isStr("NSString"))) 15978 return false; 15979 if (!SL->isAscii()) 15980 return false; 15981 15982 if (Diagnose) { 15983 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15984 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15985 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15986 } 15987 return true; 15988 } 15989 15990 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15991 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15992 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15993 !SrcExpr->isNullPointerConstant( 15994 getASTContext(), Expr::NPC_NeverValueDependent)) { 15995 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15996 return false; 15997 if (Diagnose) { 15998 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15999 << /*number*/1 16000 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 16001 Expr *NumLit = 16002 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 16003 if (NumLit) 16004 Exp = NumLit; 16005 } 16006 return true; 16007 } 16008 16009 return false; 16010 } 16011 16012 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 16013 const Expr *SrcExpr) { 16014 if (!DstType->isFunctionPointerType() || 16015 !SrcExpr->getType()->isFunctionType()) 16016 return false; 16017 16018 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 16019 if (!DRE) 16020 return false; 16021 16022 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 16023 if (!FD) 16024 return false; 16025 16026 return !S.checkAddressOfFunctionIsAvailable(FD, 16027 /*Complain=*/true, 16028 SrcExpr->getBeginLoc()); 16029 } 16030 16031 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 16032 SourceLocation Loc, 16033 QualType DstType, QualType SrcType, 16034 Expr *SrcExpr, AssignmentAction Action, 16035 bool *Complained) { 16036 if (Complained) 16037 *Complained = false; 16038 16039 // Decode the result (notice that AST's are still created for extensions). 16040 bool CheckInferredResultType = false; 16041 bool isInvalid = false; 16042 unsigned DiagKind = 0; 16043 ConversionFixItGenerator ConvHints; 16044 bool MayHaveConvFixit = false; 16045 bool MayHaveFunctionDiff = false; 16046 const ObjCInterfaceDecl *IFace = nullptr; 16047 const ObjCProtocolDecl *PDecl = nullptr; 16048 16049 switch (ConvTy) { 16050 case Compatible: 16051 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 16052 return false; 16053 16054 case PointerToInt: 16055 if (getLangOpts().CPlusPlus) { 16056 DiagKind = diag::err_typecheck_convert_pointer_int; 16057 isInvalid = true; 16058 } else { 16059 DiagKind = diag::ext_typecheck_convert_pointer_int; 16060 } 16061 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16062 MayHaveConvFixit = true; 16063 break; 16064 case IntToPointer: 16065 if (getLangOpts().CPlusPlus) { 16066 DiagKind = diag::err_typecheck_convert_int_pointer; 16067 isInvalid = true; 16068 } else { 16069 DiagKind = diag::ext_typecheck_convert_int_pointer; 16070 } 16071 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16072 MayHaveConvFixit = true; 16073 break; 16074 case IncompatibleFunctionPointer: 16075 if (getLangOpts().CPlusPlus) { 16076 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 16077 isInvalid = true; 16078 } else { 16079 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 16080 } 16081 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16082 MayHaveConvFixit = true; 16083 break; 16084 case IncompatiblePointer: 16085 if (Action == AA_Passing_CFAudited) { 16086 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 16087 } else if (getLangOpts().CPlusPlus) { 16088 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 16089 isInvalid = true; 16090 } else { 16091 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 16092 } 16093 CheckInferredResultType = DstType->isObjCObjectPointerType() && 16094 SrcType->isObjCObjectPointerType(); 16095 if (!CheckInferredResultType) { 16096 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16097 } else if (CheckInferredResultType) { 16098 SrcType = SrcType.getUnqualifiedType(); 16099 DstType = DstType.getUnqualifiedType(); 16100 } 16101 MayHaveConvFixit = true; 16102 break; 16103 case IncompatiblePointerSign: 16104 if (getLangOpts().CPlusPlus) { 16105 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 16106 isInvalid = true; 16107 } else { 16108 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 16109 } 16110 break; 16111 case FunctionVoidPointer: 16112 if (getLangOpts().CPlusPlus) { 16113 DiagKind = diag::err_typecheck_convert_pointer_void_func; 16114 isInvalid = true; 16115 } else { 16116 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 16117 } 16118 break; 16119 case IncompatiblePointerDiscardsQualifiers: { 16120 // Perform array-to-pointer decay if necessary. 16121 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 16122 16123 isInvalid = true; 16124 16125 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 16126 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 16127 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 16128 DiagKind = diag::err_typecheck_incompatible_address_space; 16129 break; 16130 16131 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 16132 DiagKind = diag::err_typecheck_incompatible_ownership; 16133 break; 16134 } 16135 16136 llvm_unreachable("unknown error case for discarding qualifiers!"); 16137 // fallthrough 16138 } 16139 case CompatiblePointerDiscardsQualifiers: 16140 // If the qualifiers lost were because we were applying the 16141 // (deprecated) C++ conversion from a string literal to a char* 16142 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 16143 // Ideally, this check would be performed in 16144 // checkPointerTypesForAssignment. However, that would require a 16145 // bit of refactoring (so that the second argument is an 16146 // expression, rather than a type), which should be done as part 16147 // of a larger effort to fix checkPointerTypesForAssignment for 16148 // C++ semantics. 16149 if (getLangOpts().CPlusPlus && 16150 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 16151 return false; 16152 if (getLangOpts().CPlusPlus) { 16153 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 16154 isInvalid = true; 16155 } else { 16156 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 16157 } 16158 16159 break; 16160 case IncompatibleNestedPointerQualifiers: 16161 if (getLangOpts().CPlusPlus) { 16162 isInvalid = true; 16163 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 16164 } else { 16165 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16166 } 16167 break; 16168 case IncompatibleNestedPointerAddressSpaceMismatch: 16169 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16170 isInvalid = true; 16171 break; 16172 case IntToBlockPointer: 16173 DiagKind = diag::err_int_to_block_pointer; 16174 isInvalid = true; 16175 break; 16176 case IncompatibleBlockPointer: 16177 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16178 isInvalid = true; 16179 break; 16180 case IncompatibleObjCQualifiedId: { 16181 if (SrcType->isObjCQualifiedIdType()) { 16182 const ObjCObjectPointerType *srcOPT = 16183 SrcType->castAs<ObjCObjectPointerType>(); 16184 for (auto *srcProto : srcOPT->quals()) { 16185 PDecl = srcProto; 16186 break; 16187 } 16188 if (const ObjCInterfaceType *IFaceT = 16189 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16190 IFace = IFaceT->getDecl(); 16191 } 16192 else if (DstType->isObjCQualifiedIdType()) { 16193 const ObjCObjectPointerType *dstOPT = 16194 DstType->castAs<ObjCObjectPointerType>(); 16195 for (auto *dstProto : dstOPT->quals()) { 16196 PDecl = dstProto; 16197 break; 16198 } 16199 if (const ObjCInterfaceType *IFaceT = 16200 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16201 IFace = IFaceT->getDecl(); 16202 } 16203 if (getLangOpts().CPlusPlus) { 16204 DiagKind = diag::err_incompatible_qualified_id; 16205 isInvalid = true; 16206 } else { 16207 DiagKind = diag::warn_incompatible_qualified_id; 16208 } 16209 break; 16210 } 16211 case IncompatibleVectors: 16212 if (getLangOpts().CPlusPlus) { 16213 DiagKind = diag::err_incompatible_vectors; 16214 isInvalid = true; 16215 } else { 16216 DiagKind = diag::warn_incompatible_vectors; 16217 } 16218 break; 16219 case IncompatibleObjCWeakRef: 16220 DiagKind = diag::err_arc_weak_unavailable_assign; 16221 isInvalid = true; 16222 break; 16223 case Incompatible: 16224 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16225 if (Complained) 16226 *Complained = true; 16227 return true; 16228 } 16229 16230 DiagKind = diag::err_typecheck_convert_incompatible; 16231 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16232 MayHaveConvFixit = true; 16233 isInvalid = true; 16234 MayHaveFunctionDiff = true; 16235 break; 16236 } 16237 16238 QualType FirstType, SecondType; 16239 switch (Action) { 16240 case AA_Assigning: 16241 case AA_Initializing: 16242 // The destination type comes first. 16243 FirstType = DstType; 16244 SecondType = SrcType; 16245 break; 16246 16247 case AA_Returning: 16248 case AA_Passing: 16249 case AA_Passing_CFAudited: 16250 case AA_Converting: 16251 case AA_Sending: 16252 case AA_Casting: 16253 // The source type comes first. 16254 FirstType = SrcType; 16255 SecondType = DstType; 16256 break; 16257 } 16258 16259 PartialDiagnostic FDiag = PDiag(DiagKind); 16260 if (Action == AA_Passing_CFAudited) 16261 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16262 else 16263 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16264 16265 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16266 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16267 auto isPlainChar = [](const clang::Type *Type) { 16268 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16269 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16270 }; 16271 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16272 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16273 } 16274 16275 // If we can fix the conversion, suggest the FixIts. 16276 if (!ConvHints.isNull()) { 16277 for (FixItHint &H : ConvHints.Hints) 16278 FDiag << H; 16279 } 16280 16281 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16282 16283 if (MayHaveFunctionDiff) 16284 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16285 16286 Diag(Loc, FDiag); 16287 if ((DiagKind == diag::warn_incompatible_qualified_id || 16288 DiagKind == diag::err_incompatible_qualified_id) && 16289 PDecl && IFace && !IFace->hasDefinition()) 16290 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16291 << IFace << PDecl; 16292 16293 if (SecondType == Context.OverloadTy) 16294 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16295 FirstType, /*TakingAddress=*/true); 16296 16297 if (CheckInferredResultType) 16298 EmitRelatedResultTypeNote(SrcExpr); 16299 16300 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16301 EmitRelatedResultTypeNoteForReturn(DstType); 16302 16303 if (Complained) 16304 *Complained = true; 16305 return isInvalid; 16306 } 16307 16308 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16309 llvm::APSInt *Result, 16310 AllowFoldKind CanFold) { 16311 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16312 public: 16313 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16314 QualType T) override { 16315 return S.Diag(Loc, diag::err_ice_not_integral) 16316 << T << S.LangOpts.CPlusPlus; 16317 } 16318 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16319 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16320 } 16321 } Diagnoser; 16322 16323 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16324 } 16325 16326 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16327 llvm::APSInt *Result, 16328 unsigned DiagID, 16329 AllowFoldKind CanFold) { 16330 class IDDiagnoser : public VerifyICEDiagnoser { 16331 unsigned DiagID; 16332 16333 public: 16334 IDDiagnoser(unsigned DiagID) 16335 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16336 16337 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16338 return S.Diag(Loc, DiagID); 16339 } 16340 } Diagnoser(DiagID); 16341 16342 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16343 } 16344 16345 Sema::SemaDiagnosticBuilder 16346 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16347 QualType T) { 16348 return diagnoseNotICE(S, Loc); 16349 } 16350 16351 Sema::SemaDiagnosticBuilder 16352 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16353 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16354 } 16355 16356 ExprResult 16357 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16358 VerifyICEDiagnoser &Diagnoser, 16359 AllowFoldKind CanFold) { 16360 SourceLocation DiagLoc = E->getBeginLoc(); 16361 16362 if (getLangOpts().CPlusPlus11) { 16363 // C++11 [expr.const]p5: 16364 // If an expression of literal class type is used in a context where an 16365 // integral constant expression is required, then that class type shall 16366 // have a single non-explicit conversion function to an integral or 16367 // unscoped enumeration type 16368 ExprResult Converted; 16369 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16370 VerifyICEDiagnoser &BaseDiagnoser; 16371 public: 16372 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16373 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16374 BaseDiagnoser.Suppress, true), 16375 BaseDiagnoser(BaseDiagnoser) {} 16376 16377 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16378 QualType T) override { 16379 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16380 } 16381 16382 SemaDiagnosticBuilder diagnoseIncomplete( 16383 Sema &S, SourceLocation Loc, QualType T) override { 16384 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16385 } 16386 16387 SemaDiagnosticBuilder diagnoseExplicitConv( 16388 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16389 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16390 } 16391 16392 SemaDiagnosticBuilder noteExplicitConv( 16393 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16394 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16395 << ConvTy->isEnumeralType() << ConvTy; 16396 } 16397 16398 SemaDiagnosticBuilder diagnoseAmbiguous( 16399 Sema &S, SourceLocation Loc, QualType T) override { 16400 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16401 } 16402 16403 SemaDiagnosticBuilder noteAmbiguous( 16404 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16405 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16406 << ConvTy->isEnumeralType() << ConvTy; 16407 } 16408 16409 SemaDiagnosticBuilder diagnoseConversion( 16410 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16411 llvm_unreachable("conversion functions are permitted"); 16412 } 16413 } ConvertDiagnoser(Diagnoser); 16414 16415 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16416 ConvertDiagnoser); 16417 if (Converted.isInvalid()) 16418 return Converted; 16419 E = Converted.get(); 16420 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16421 return ExprError(); 16422 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16423 // An ICE must be of integral or unscoped enumeration type. 16424 if (!Diagnoser.Suppress) 16425 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16426 << E->getSourceRange(); 16427 return ExprError(); 16428 } 16429 16430 ExprResult RValueExpr = DefaultLvalueConversion(E); 16431 if (RValueExpr.isInvalid()) 16432 return ExprError(); 16433 16434 E = RValueExpr.get(); 16435 16436 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16437 // in the non-ICE case. 16438 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16439 if (Result) 16440 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16441 if (!isa<ConstantExpr>(E)) 16442 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16443 : ConstantExpr::Create(Context, E); 16444 return E; 16445 } 16446 16447 Expr::EvalResult EvalResult; 16448 SmallVector<PartialDiagnosticAt, 8> Notes; 16449 EvalResult.Diag = &Notes; 16450 16451 // Try to evaluate the expression, and produce diagnostics explaining why it's 16452 // not a constant expression as a side-effect. 16453 bool Folded = 16454 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16455 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16456 16457 if (!isa<ConstantExpr>(E)) 16458 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16459 16460 // In C++11, we can rely on diagnostics being produced for any expression 16461 // which is not a constant expression. If no diagnostics were produced, then 16462 // this is a constant expression. 16463 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16464 if (Result) 16465 *Result = EvalResult.Val.getInt(); 16466 return E; 16467 } 16468 16469 // If our only note is the usual "invalid subexpression" note, just point 16470 // the caret at its location rather than producing an essentially 16471 // redundant note. 16472 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16473 diag::note_invalid_subexpr_in_const_expr) { 16474 DiagLoc = Notes[0].first; 16475 Notes.clear(); 16476 } 16477 16478 if (!Folded || !CanFold) { 16479 if (!Diagnoser.Suppress) { 16480 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16481 for (const PartialDiagnosticAt &Note : Notes) 16482 Diag(Note.first, Note.second); 16483 } 16484 16485 return ExprError(); 16486 } 16487 16488 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16489 for (const PartialDiagnosticAt &Note : Notes) 16490 Diag(Note.first, Note.second); 16491 16492 if (Result) 16493 *Result = EvalResult.Val.getInt(); 16494 return E; 16495 } 16496 16497 namespace { 16498 // Handle the case where we conclude a expression which we speculatively 16499 // considered to be unevaluated is actually evaluated. 16500 class TransformToPE : public TreeTransform<TransformToPE> { 16501 typedef TreeTransform<TransformToPE> BaseTransform; 16502 16503 public: 16504 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16505 16506 // Make sure we redo semantic analysis 16507 bool AlwaysRebuild() { return true; } 16508 bool ReplacingOriginal() { return true; } 16509 16510 // We need to special-case DeclRefExprs referring to FieldDecls which 16511 // are not part of a member pointer formation; normal TreeTransforming 16512 // doesn't catch this case because of the way we represent them in the AST. 16513 // FIXME: This is a bit ugly; is it really the best way to handle this 16514 // case? 16515 // 16516 // Error on DeclRefExprs referring to FieldDecls. 16517 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16518 if (isa<FieldDecl>(E->getDecl()) && 16519 !SemaRef.isUnevaluatedContext()) 16520 return SemaRef.Diag(E->getLocation(), 16521 diag::err_invalid_non_static_member_use) 16522 << E->getDecl() << E->getSourceRange(); 16523 16524 return BaseTransform::TransformDeclRefExpr(E); 16525 } 16526 16527 // Exception: filter out member pointer formation 16528 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16529 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16530 return E; 16531 16532 return BaseTransform::TransformUnaryOperator(E); 16533 } 16534 16535 // The body of a lambda-expression is in a separate expression evaluation 16536 // context so never needs to be transformed. 16537 // FIXME: Ideally we wouldn't transform the closure type either, and would 16538 // just recreate the capture expressions and lambda expression. 16539 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16540 return SkipLambdaBody(E, Body); 16541 } 16542 }; 16543 } 16544 16545 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16546 assert(isUnevaluatedContext() && 16547 "Should only transform unevaluated expressions"); 16548 ExprEvalContexts.back().Context = 16549 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16550 if (isUnevaluatedContext()) 16551 return E; 16552 return TransformToPE(*this).TransformExpr(E); 16553 } 16554 16555 void 16556 Sema::PushExpressionEvaluationContext( 16557 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16558 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16559 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16560 LambdaContextDecl, ExprContext); 16561 Cleanup.reset(); 16562 if (!MaybeODRUseExprs.empty()) 16563 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16564 } 16565 16566 void 16567 Sema::PushExpressionEvaluationContext( 16568 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16569 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16570 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16571 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16572 } 16573 16574 namespace { 16575 16576 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16577 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16578 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16579 if (E->getOpcode() == UO_Deref) 16580 return CheckPossibleDeref(S, E->getSubExpr()); 16581 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16582 return CheckPossibleDeref(S, E->getBase()); 16583 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16584 return CheckPossibleDeref(S, E->getBase()); 16585 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16586 QualType Inner; 16587 QualType Ty = E->getType(); 16588 if (const auto *Ptr = Ty->getAs<PointerType>()) 16589 Inner = Ptr->getPointeeType(); 16590 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16591 Inner = Arr->getElementType(); 16592 else 16593 return nullptr; 16594 16595 if (Inner->hasAttr(attr::NoDeref)) 16596 return E; 16597 } 16598 return nullptr; 16599 } 16600 16601 } // namespace 16602 16603 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16604 for (const Expr *E : Rec.PossibleDerefs) { 16605 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16606 if (DeclRef) { 16607 const ValueDecl *Decl = DeclRef->getDecl(); 16608 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16609 << Decl->getName() << E->getSourceRange(); 16610 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16611 } else { 16612 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16613 << E->getSourceRange(); 16614 } 16615 } 16616 Rec.PossibleDerefs.clear(); 16617 } 16618 16619 /// Check whether E, which is either a discarded-value expression or an 16620 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16621 /// and if so, remove it from the list of volatile-qualified assignments that 16622 /// we are going to warn are deprecated. 16623 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16624 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16625 return; 16626 16627 // Note: ignoring parens here is not justified by the standard rules, but 16628 // ignoring parentheses seems like a more reasonable approach, and this only 16629 // drives a deprecation warning so doesn't affect conformance. 16630 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16631 if (BO->getOpcode() == BO_Assign) { 16632 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16633 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16634 LHSs.end()); 16635 } 16636 } 16637 } 16638 16639 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16640 if (isUnevaluatedContext() || !E.isUsable() || !Decl || 16641 !Decl->isConsteval() || isConstantEvaluated() || 16642 RebuildingImmediateInvocation) 16643 return E; 16644 16645 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16646 /// It's OK if this fails; we'll also remove this in 16647 /// HandleImmediateInvocations, but catching it here allows us to avoid 16648 /// walking the AST looking for it in simple cases. 16649 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16650 if (auto *DeclRef = 16651 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16652 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16653 16654 E = MaybeCreateExprWithCleanups(E); 16655 16656 ConstantExpr *Res = ConstantExpr::Create( 16657 getASTContext(), E.get(), 16658 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16659 getASTContext()), 16660 /*IsImmediateInvocation*/ true); 16661 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16662 return Res; 16663 } 16664 16665 static void EvaluateAndDiagnoseImmediateInvocation( 16666 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16667 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16668 Expr::EvalResult Eval; 16669 Eval.Diag = &Notes; 16670 ConstantExpr *CE = Candidate.getPointer(); 16671 bool Result = CE->EvaluateAsConstantExpr( 16672 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16673 if (!Result || !Notes.empty()) { 16674 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16675 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16676 InnerExpr = FunctionalCast->getSubExpr(); 16677 FunctionDecl *FD = nullptr; 16678 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16679 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16680 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16681 FD = Call->getConstructor(); 16682 else 16683 llvm_unreachable("unhandled decl kind"); 16684 assert(FD->isConsteval()); 16685 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16686 for (auto &Note : Notes) 16687 SemaRef.Diag(Note.first, Note.second); 16688 return; 16689 } 16690 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16691 } 16692 16693 static void RemoveNestedImmediateInvocation( 16694 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16695 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16696 struct ComplexRemove : TreeTransform<ComplexRemove> { 16697 using Base = TreeTransform<ComplexRemove>; 16698 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16699 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16700 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16701 CurrentII; 16702 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16703 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16704 SmallVector<Sema::ImmediateInvocationCandidate, 16705 4>::reverse_iterator Current) 16706 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16707 void RemoveImmediateInvocation(ConstantExpr* E) { 16708 auto It = std::find_if(CurrentII, IISet.rend(), 16709 [E](Sema::ImmediateInvocationCandidate Elem) { 16710 return Elem.getPointer() == E; 16711 }); 16712 assert(It != IISet.rend() && 16713 "ConstantExpr marked IsImmediateInvocation should " 16714 "be present"); 16715 It->setInt(1); // Mark as deleted 16716 } 16717 ExprResult TransformConstantExpr(ConstantExpr *E) { 16718 if (!E->isImmediateInvocation()) 16719 return Base::TransformConstantExpr(E); 16720 RemoveImmediateInvocation(E); 16721 return Base::TransformExpr(E->getSubExpr()); 16722 } 16723 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16724 /// we need to remove its DeclRefExpr from the DRSet. 16725 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16726 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16727 return Base::TransformCXXOperatorCallExpr(E); 16728 } 16729 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16730 /// here. 16731 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16732 if (!Init) 16733 return Init; 16734 /// ConstantExpr are the first layer of implicit node to be removed so if 16735 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16736 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16737 if (CE->isImmediateInvocation()) 16738 RemoveImmediateInvocation(CE); 16739 return Base::TransformInitializer(Init, NotCopyInit); 16740 } 16741 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16742 DRSet.erase(E); 16743 return E; 16744 } 16745 bool AlwaysRebuild() { return false; } 16746 bool ReplacingOriginal() { return true; } 16747 bool AllowSkippingCXXConstructExpr() { 16748 bool Res = AllowSkippingFirstCXXConstructExpr; 16749 AllowSkippingFirstCXXConstructExpr = true; 16750 return Res; 16751 } 16752 bool AllowSkippingFirstCXXConstructExpr = true; 16753 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16754 Rec.ImmediateInvocationCandidates, It); 16755 16756 /// CXXConstructExpr with a single argument are getting skipped by 16757 /// TreeTransform in some situtation because they could be implicit. This 16758 /// can only occur for the top-level CXXConstructExpr because it is used 16759 /// nowhere in the expression being transformed therefore will not be rebuilt. 16760 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16761 /// skipping the first CXXConstructExpr. 16762 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16763 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16764 16765 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16766 assert(Res.isUsable()); 16767 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16768 It->getPointer()->setSubExpr(Res.get()); 16769 } 16770 16771 static void 16772 HandleImmediateInvocations(Sema &SemaRef, 16773 Sema::ExpressionEvaluationContextRecord &Rec) { 16774 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16775 Rec.ReferenceToConsteval.size() == 0) || 16776 SemaRef.RebuildingImmediateInvocation) 16777 return; 16778 16779 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16780 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16781 /// need to remove ReferenceToConsteval in the immediate invocation. 16782 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16783 16784 /// Prevent sema calls during the tree transform from adding pointers that 16785 /// are already in the sets. 16786 llvm::SaveAndRestore<bool> DisableIITracking( 16787 SemaRef.RebuildingImmediateInvocation, true); 16788 16789 /// Prevent diagnostic during tree transfrom as they are duplicates 16790 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16791 16792 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16793 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16794 if (!It->getInt()) 16795 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16796 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16797 Rec.ReferenceToConsteval.size()) { 16798 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16799 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16800 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16801 bool VisitDeclRefExpr(DeclRefExpr *E) { 16802 DRSet.erase(E); 16803 return DRSet.size(); 16804 } 16805 } Visitor(Rec.ReferenceToConsteval); 16806 Visitor.TraverseStmt( 16807 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16808 } 16809 for (auto CE : Rec.ImmediateInvocationCandidates) 16810 if (!CE.getInt()) 16811 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16812 for (auto DR : Rec.ReferenceToConsteval) { 16813 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16814 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16815 << FD; 16816 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16817 } 16818 } 16819 16820 void Sema::PopExpressionEvaluationContext() { 16821 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16822 unsigned NumTypos = Rec.NumTypos; 16823 16824 if (!Rec.Lambdas.empty()) { 16825 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16826 if (!getLangOpts().CPlusPlus20 && 16827 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 16828 Rec.isUnevaluated() || 16829 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 16830 unsigned D; 16831 if (Rec.isUnevaluated()) { 16832 // C++11 [expr.prim.lambda]p2: 16833 // A lambda-expression shall not appear in an unevaluated operand 16834 // (Clause 5). 16835 D = diag::err_lambda_unevaluated_operand; 16836 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16837 // C++1y [expr.const]p2: 16838 // A conditional-expression e is a core constant expression unless the 16839 // evaluation of e, following the rules of the abstract machine, would 16840 // evaluate [...] a lambda-expression. 16841 D = diag::err_lambda_in_constant_expression; 16842 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16843 // C++17 [expr.prim.lamda]p2: 16844 // A lambda-expression shall not appear [...] in a template-argument. 16845 D = diag::err_lambda_in_invalid_context; 16846 } else 16847 llvm_unreachable("Couldn't infer lambda error message."); 16848 16849 for (const auto *L : Rec.Lambdas) 16850 Diag(L->getBeginLoc(), D); 16851 } 16852 } 16853 16854 WarnOnPendingNoDerefs(Rec); 16855 HandleImmediateInvocations(*this, Rec); 16856 16857 // Warn on any volatile-qualified simple-assignments that are not discarded- 16858 // value expressions nor unevaluated operands (those cases get removed from 16859 // this list by CheckUnusedVolatileAssignment). 16860 for (auto *BO : Rec.VolatileAssignmentLHSs) 16861 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16862 << BO->getType(); 16863 16864 // When are coming out of an unevaluated context, clear out any 16865 // temporaries that we may have created as part of the evaluation of 16866 // the expression in that context: they aren't relevant because they 16867 // will never be constructed. 16868 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16869 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16870 ExprCleanupObjects.end()); 16871 Cleanup = Rec.ParentCleanup; 16872 CleanupVarDeclMarking(); 16873 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16874 // Otherwise, merge the contexts together. 16875 } else { 16876 Cleanup.mergeFrom(Rec.ParentCleanup); 16877 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16878 Rec.SavedMaybeODRUseExprs.end()); 16879 } 16880 16881 // Pop the current expression evaluation context off the stack. 16882 ExprEvalContexts.pop_back(); 16883 16884 // The global expression evaluation context record is never popped. 16885 ExprEvalContexts.back().NumTypos += NumTypos; 16886 } 16887 16888 void Sema::DiscardCleanupsInEvaluationContext() { 16889 ExprCleanupObjects.erase( 16890 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16891 ExprCleanupObjects.end()); 16892 Cleanup.reset(); 16893 MaybeODRUseExprs.clear(); 16894 } 16895 16896 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16897 ExprResult Result = CheckPlaceholderExpr(E); 16898 if (Result.isInvalid()) 16899 return ExprError(); 16900 E = Result.get(); 16901 if (!E->getType()->isVariablyModifiedType()) 16902 return E; 16903 return TransformToPotentiallyEvaluated(E); 16904 } 16905 16906 /// Are we in a context that is potentially constant evaluated per C++20 16907 /// [expr.const]p12? 16908 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16909 /// C++2a [expr.const]p12: 16910 // An expression or conversion is potentially constant evaluated if it is 16911 switch (SemaRef.ExprEvalContexts.back().Context) { 16912 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16913 // -- a manifestly constant-evaluated expression, 16914 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16915 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16916 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16917 // -- a potentially-evaluated expression, 16918 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16919 // -- an immediate subexpression of a braced-init-list, 16920 16921 // -- [FIXME] an expression of the form & cast-expression that occurs 16922 // within a templated entity 16923 // -- a subexpression of one of the above that is not a subexpression of 16924 // a nested unevaluated operand. 16925 return true; 16926 16927 case Sema::ExpressionEvaluationContext::Unevaluated: 16928 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16929 // Expressions in this context are never evaluated. 16930 return false; 16931 } 16932 llvm_unreachable("Invalid context"); 16933 } 16934 16935 /// Return true if this function has a calling convention that requires mangling 16936 /// in the size of the parameter pack. 16937 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16938 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16939 // we don't need parameter type sizes. 16940 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16941 if (!TT.isOSWindows() || !TT.isX86()) 16942 return false; 16943 16944 // If this is C++ and this isn't an extern "C" function, parameters do not 16945 // need to be complete. In this case, C++ mangling will apply, which doesn't 16946 // use the size of the parameters. 16947 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16948 return false; 16949 16950 // Stdcall, fastcall, and vectorcall need this special treatment. 16951 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16952 switch (CC) { 16953 case CC_X86StdCall: 16954 case CC_X86FastCall: 16955 case CC_X86VectorCall: 16956 return true; 16957 default: 16958 break; 16959 } 16960 return false; 16961 } 16962 16963 /// Require that all of the parameter types of function be complete. Normally, 16964 /// parameter types are only required to be complete when a function is called 16965 /// or defined, but to mangle functions with certain calling conventions, the 16966 /// mangler needs to know the size of the parameter list. In this situation, 16967 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16968 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16969 /// result in a linker error. Clang doesn't implement this behavior, and instead 16970 /// attempts to error at compile time. 16971 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16972 SourceLocation Loc) { 16973 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16974 FunctionDecl *FD; 16975 ParmVarDecl *Param; 16976 16977 public: 16978 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16979 : FD(FD), Param(Param) {} 16980 16981 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16982 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16983 StringRef CCName; 16984 switch (CC) { 16985 case CC_X86StdCall: 16986 CCName = "stdcall"; 16987 break; 16988 case CC_X86FastCall: 16989 CCName = "fastcall"; 16990 break; 16991 case CC_X86VectorCall: 16992 CCName = "vectorcall"; 16993 break; 16994 default: 16995 llvm_unreachable("CC does not need mangling"); 16996 } 16997 16998 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16999 << Param->getDeclName() << FD->getDeclName() << CCName; 17000 } 17001 }; 17002 17003 for (ParmVarDecl *Param : FD->parameters()) { 17004 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 17005 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 17006 } 17007 } 17008 17009 namespace { 17010 enum class OdrUseContext { 17011 /// Declarations in this context are not odr-used. 17012 None, 17013 /// Declarations in this context are formally odr-used, but this is a 17014 /// dependent context. 17015 Dependent, 17016 /// Declarations in this context are odr-used but not actually used (yet). 17017 FormallyOdrUsed, 17018 /// Declarations in this context are used. 17019 Used 17020 }; 17021 } 17022 17023 /// Are we within a context in which references to resolved functions or to 17024 /// variables result in odr-use? 17025 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 17026 OdrUseContext Result; 17027 17028 switch (SemaRef.ExprEvalContexts.back().Context) { 17029 case Sema::ExpressionEvaluationContext::Unevaluated: 17030 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17031 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17032 return OdrUseContext::None; 17033 17034 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17035 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17036 Result = OdrUseContext::Used; 17037 break; 17038 17039 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17040 Result = OdrUseContext::FormallyOdrUsed; 17041 break; 17042 17043 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17044 // A default argument formally results in odr-use, but doesn't actually 17045 // result in a use in any real sense until it itself is used. 17046 Result = OdrUseContext::FormallyOdrUsed; 17047 break; 17048 } 17049 17050 if (SemaRef.CurContext->isDependentContext()) 17051 return OdrUseContext::Dependent; 17052 17053 return Result; 17054 } 17055 17056 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 17057 if (!Func->isConstexpr()) 17058 return false; 17059 17060 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 17061 return true; 17062 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 17063 return CCD && CCD->getInheritedConstructor(); 17064 } 17065 17066 /// Mark a function referenced, and check whether it is odr-used 17067 /// (C++ [basic.def.odr]p2, C99 6.9p3) 17068 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 17069 bool MightBeOdrUse) { 17070 assert(Func && "No function?"); 17071 17072 Func->setReferenced(); 17073 17074 // Recursive functions aren't really used until they're used from some other 17075 // context. 17076 bool IsRecursiveCall = CurContext == Func; 17077 17078 // C++11 [basic.def.odr]p3: 17079 // A function whose name appears as a potentially-evaluated expression is 17080 // odr-used if it is the unique lookup result or the selected member of a 17081 // set of overloaded functions [...]. 17082 // 17083 // We (incorrectly) mark overload resolution as an unevaluated context, so we 17084 // can just check that here. 17085 OdrUseContext OdrUse = 17086 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 17087 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 17088 OdrUse = OdrUseContext::FormallyOdrUsed; 17089 17090 // Trivial default constructors and destructors are never actually used. 17091 // FIXME: What about other special members? 17092 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 17093 OdrUse == OdrUseContext::Used) { 17094 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 17095 if (Constructor->isDefaultConstructor()) 17096 OdrUse = OdrUseContext::FormallyOdrUsed; 17097 if (isa<CXXDestructorDecl>(Func)) 17098 OdrUse = OdrUseContext::FormallyOdrUsed; 17099 } 17100 17101 // C++20 [expr.const]p12: 17102 // A function [...] is needed for constant evaluation if it is [...] a 17103 // constexpr function that is named by an expression that is potentially 17104 // constant evaluated 17105 bool NeededForConstantEvaluation = 17106 isPotentiallyConstantEvaluatedContext(*this) && 17107 isImplicitlyDefinableConstexprFunction(Func); 17108 17109 // Determine whether we require a function definition to exist, per 17110 // C++11 [temp.inst]p3: 17111 // Unless a function template specialization has been explicitly 17112 // instantiated or explicitly specialized, the function template 17113 // specialization is implicitly instantiated when the specialization is 17114 // referenced in a context that requires a function definition to exist. 17115 // C++20 [temp.inst]p7: 17116 // The existence of a definition of a [...] function is considered to 17117 // affect the semantics of the program if the [...] function is needed for 17118 // constant evaluation by an expression 17119 // C++20 [basic.def.odr]p10: 17120 // Every program shall contain exactly one definition of every non-inline 17121 // function or variable that is odr-used in that program outside of a 17122 // discarded statement 17123 // C++20 [special]p1: 17124 // The implementation will implicitly define [defaulted special members] 17125 // if they are odr-used or needed for constant evaluation. 17126 // 17127 // Note that we skip the implicit instantiation of templates that are only 17128 // used in unused default arguments or by recursive calls to themselves. 17129 // This is formally non-conforming, but seems reasonable in practice. 17130 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 17131 NeededForConstantEvaluation); 17132 17133 // C++14 [temp.expl.spec]p6: 17134 // If a template [...] is explicitly specialized then that specialization 17135 // shall be declared before the first use of that specialization that would 17136 // cause an implicit instantiation to take place, in every translation unit 17137 // in which such a use occurs 17138 if (NeedDefinition && 17139 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 17140 Func->getMemberSpecializationInfo())) 17141 checkSpecializationVisibility(Loc, Func); 17142 17143 if (getLangOpts().CUDA) 17144 CheckCUDACall(Loc, Func); 17145 17146 if (getLangOpts().SYCLIsDevice) 17147 checkSYCLDeviceFunction(Loc, Func); 17148 17149 // If we need a definition, try to create one. 17150 if (NeedDefinition && !Func->getBody()) { 17151 runWithSufficientStackSpace(Loc, [&] { 17152 if (CXXConstructorDecl *Constructor = 17153 dyn_cast<CXXConstructorDecl>(Func)) { 17154 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 17155 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 17156 if (Constructor->isDefaultConstructor()) { 17157 if (Constructor->isTrivial() && 17158 !Constructor->hasAttr<DLLExportAttr>()) 17159 return; 17160 DefineImplicitDefaultConstructor(Loc, Constructor); 17161 } else if (Constructor->isCopyConstructor()) { 17162 DefineImplicitCopyConstructor(Loc, Constructor); 17163 } else if (Constructor->isMoveConstructor()) { 17164 DefineImplicitMoveConstructor(Loc, Constructor); 17165 } 17166 } else if (Constructor->getInheritedConstructor()) { 17167 DefineInheritingConstructor(Loc, Constructor); 17168 } 17169 } else if (CXXDestructorDecl *Destructor = 17170 dyn_cast<CXXDestructorDecl>(Func)) { 17171 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17172 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17173 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17174 return; 17175 DefineImplicitDestructor(Loc, Destructor); 17176 } 17177 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17178 MarkVTableUsed(Loc, Destructor->getParent()); 17179 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17180 if (MethodDecl->isOverloadedOperator() && 17181 MethodDecl->getOverloadedOperator() == OO_Equal) { 17182 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17183 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17184 if (MethodDecl->isCopyAssignmentOperator()) 17185 DefineImplicitCopyAssignment(Loc, MethodDecl); 17186 else if (MethodDecl->isMoveAssignmentOperator()) 17187 DefineImplicitMoveAssignment(Loc, MethodDecl); 17188 } 17189 } else if (isa<CXXConversionDecl>(MethodDecl) && 17190 MethodDecl->getParent()->isLambda()) { 17191 CXXConversionDecl *Conversion = 17192 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17193 if (Conversion->isLambdaToBlockPointerConversion()) 17194 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17195 else 17196 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17197 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17198 MarkVTableUsed(Loc, MethodDecl->getParent()); 17199 } 17200 17201 if (Func->isDefaulted() && !Func->isDeleted()) { 17202 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17203 if (DCK != DefaultedComparisonKind::None) 17204 DefineDefaultedComparison(Loc, Func, DCK); 17205 } 17206 17207 // Implicit instantiation of function templates and member functions of 17208 // class templates. 17209 if (Func->isImplicitlyInstantiable()) { 17210 TemplateSpecializationKind TSK = 17211 Func->getTemplateSpecializationKindForInstantiation(); 17212 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17213 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17214 if (FirstInstantiation) { 17215 PointOfInstantiation = Loc; 17216 if (auto *MSI = Func->getMemberSpecializationInfo()) 17217 MSI->setPointOfInstantiation(Loc); 17218 // FIXME: Notify listener. 17219 else 17220 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17221 } else if (TSK != TSK_ImplicitInstantiation) { 17222 // Use the point of use as the point of instantiation, instead of the 17223 // point of explicit instantiation (which we track as the actual point 17224 // of instantiation). This gives better backtraces in diagnostics. 17225 PointOfInstantiation = Loc; 17226 } 17227 17228 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17229 Func->isConstexpr()) { 17230 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17231 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17232 CodeSynthesisContexts.size()) 17233 PendingLocalImplicitInstantiations.push_back( 17234 std::make_pair(Func, PointOfInstantiation)); 17235 else if (Func->isConstexpr()) 17236 // Do not defer instantiations of constexpr functions, to avoid the 17237 // expression evaluator needing to call back into Sema if it sees a 17238 // call to such a function. 17239 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17240 else { 17241 Func->setInstantiationIsPending(true); 17242 PendingInstantiations.push_back( 17243 std::make_pair(Func, PointOfInstantiation)); 17244 // Notify the consumer that a function was implicitly instantiated. 17245 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17246 } 17247 } 17248 } else { 17249 // Walk redefinitions, as some of them may be instantiable. 17250 for (auto i : Func->redecls()) { 17251 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17252 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17253 } 17254 } 17255 }); 17256 } 17257 17258 // C++14 [except.spec]p17: 17259 // An exception-specification is considered to be needed when: 17260 // - the function is odr-used or, if it appears in an unevaluated operand, 17261 // would be odr-used if the expression were potentially-evaluated; 17262 // 17263 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17264 // function is a pure virtual function we're calling, and in that case the 17265 // function was selected by overload resolution and we need to resolve its 17266 // exception specification for a different reason. 17267 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17268 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17269 ResolveExceptionSpec(Loc, FPT); 17270 17271 // If this is the first "real" use, act on that. 17272 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17273 // Keep track of used but undefined functions. 17274 if (!Func->isDefined()) { 17275 if (mightHaveNonExternalLinkage(Func)) 17276 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17277 else if (Func->getMostRecentDecl()->isInlined() && 17278 !LangOpts.GNUInline && 17279 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17280 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17281 else if (isExternalWithNoLinkageType(Func)) 17282 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17283 } 17284 17285 // Some x86 Windows calling conventions mangle the size of the parameter 17286 // pack into the name. Computing the size of the parameters requires the 17287 // parameter types to be complete. Check that now. 17288 if (funcHasParameterSizeMangling(*this, Func)) 17289 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17290 17291 // In the MS C++ ABI, the compiler emits destructor variants where they are 17292 // used. If the destructor is used here but defined elsewhere, mark the 17293 // virtual base destructors referenced. If those virtual base destructors 17294 // are inline, this will ensure they are defined when emitting the complete 17295 // destructor variant. This checking may be redundant if the destructor is 17296 // provided later in this TU. 17297 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17298 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17299 CXXRecordDecl *Parent = Dtor->getParent(); 17300 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17301 CheckCompleteDestructorVariant(Loc, Dtor); 17302 } 17303 } 17304 17305 Func->markUsed(Context); 17306 } 17307 } 17308 17309 /// Directly mark a variable odr-used. Given a choice, prefer to use 17310 /// MarkVariableReferenced since it does additional checks and then 17311 /// calls MarkVarDeclODRUsed. 17312 /// If the variable must be captured: 17313 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17314 /// - else capture it in the DeclContext that maps to the 17315 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17316 static void 17317 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17318 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17319 // Keep track of used but undefined variables. 17320 // FIXME: We shouldn't suppress this warning for static data members. 17321 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17322 (!Var->isExternallyVisible() || Var->isInline() || 17323 SemaRef.isExternalWithNoLinkageType(Var)) && 17324 !(Var->isStaticDataMember() && Var->hasInit())) { 17325 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17326 if (old.isInvalid()) 17327 old = Loc; 17328 } 17329 QualType CaptureType, DeclRefType; 17330 if (SemaRef.LangOpts.OpenMP) 17331 SemaRef.tryCaptureOpenMPLambdas(Var); 17332 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17333 /*EllipsisLoc*/ SourceLocation(), 17334 /*BuildAndDiagnose*/ true, 17335 CaptureType, DeclRefType, 17336 FunctionScopeIndexToStopAt); 17337 17338 if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) { 17339 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 17340 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 17341 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 17342 if (VarTarget == Sema::CVT_Host && 17343 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 17344 UserTarget == Sema::CFT_Global)) { 17345 // Diagnose ODR-use of host global variables in device functions. 17346 // Reference of device global variables in host functions is allowed 17347 // through shadow variables therefore it is not diagnosed. 17348 if (SemaRef.LangOpts.CUDAIsDevice) { 17349 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 17350 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 17351 SemaRef.targetDiag(Var->getLocation(), 17352 Var->getType().isConstQualified() 17353 ? diag::note_cuda_const_var_unpromoted 17354 : diag::note_cuda_host_var); 17355 } 17356 } else if (VarTarget == Sema::CVT_Device && 17357 (UserTarget == Sema::CFT_Host || 17358 UserTarget == Sema::CFT_HostDevice) && 17359 !Var->hasExternalStorage()) { 17360 // Record a CUDA/HIP device side variable if it is ODR-used 17361 // by host code. This is done conservatively, when the variable is 17362 // referenced in any of the following contexts: 17363 // - a non-function context 17364 // - a host function 17365 // - a host device function 17366 // This makes the ODR-use of the device side variable by host code to 17367 // be visible in the device compilation for the compiler to be able to 17368 // emit template variables instantiated by host code only and to 17369 // externalize the static device side variable ODR-used by host code. 17370 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 17371 } 17372 } 17373 17374 Var->markUsed(SemaRef.Context); 17375 } 17376 17377 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17378 SourceLocation Loc, 17379 unsigned CapturingScopeIndex) { 17380 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17381 } 17382 17383 static void 17384 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17385 ValueDecl *var, DeclContext *DC) { 17386 DeclContext *VarDC = var->getDeclContext(); 17387 17388 // If the parameter still belongs to the translation unit, then 17389 // we're actually just using one parameter in the declaration of 17390 // the next. 17391 if (isa<ParmVarDecl>(var) && 17392 isa<TranslationUnitDecl>(VarDC)) 17393 return; 17394 17395 // For C code, don't diagnose about capture if we're not actually in code 17396 // right now; it's impossible to write a non-constant expression outside of 17397 // function context, so we'll get other (more useful) diagnostics later. 17398 // 17399 // For C++, things get a bit more nasty... it would be nice to suppress this 17400 // diagnostic for certain cases like using a local variable in an array bound 17401 // for a member of a local class, but the correct predicate is not obvious. 17402 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17403 return; 17404 17405 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17406 unsigned ContextKind = 3; // unknown 17407 if (isa<CXXMethodDecl>(VarDC) && 17408 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17409 ContextKind = 2; 17410 } else if (isa<FunctionDecl>(VarDC)) { 17411 ContextKind = 0; 17412 } else if (isa<BlockDecl>(VarDC)) { 17413 ContextKind = 1; 17414 } 17415 17416 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17417 << var << ValueKind << ContextKind << VarDC; 17418 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17419 << var; 17420 17421 // FIXME: Add additional diagnostic info about class etc. which prevents 17422 // capture. 17423 } 17424 17425 17426 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17427 bool &SubCapturesAreNested, 17428 QualType &CaptureType, 17429 QualType &DeclRefType) { 17430 // Check whether we've already captured it. 17431 if (CSI->CaptureMap.count(Var)) { 17432 // If we found a capture, any subcaptures are nested. 17433 SubCapturesAreNested = true; 17434 17435 // Retrieve the capture type for this variable. 17436 CaptureType = CSI->getCapture(Var).getCaptureType(); 17437 17438 // Compute the type of an expression that refers to this variable. 17439 DeclRefType = CaptureType.getNonReferenceType(); 17440 17441 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17442 // are mutable in the sense that user can change their value - they are 17443 // private instances of the captured declarations. 17444 const Capture &Cap = CSI->getCapture(Var); 17445 if (Cap.isCopyCapture() && 17446 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17447 !(isa<CapturedRegionScopeInfo>(CSI) && 17448 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17449 DeclRefType.addConst(); 17450 return true; 17451 } 17452 return false; 17453 } 17454 17455 // Only block literals, captured statements, and lambda expressions can 17456 // capture; other scopes don't work. 17457 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17458 SourceLocation Loc, 17459 const bool Diagnose, Sema &S) { 17460 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17461 return getLambdaAwareParentOfDeclContext(DC); 17462 else if (Var->hasLocalStorage()) { 17463 if (Diagnose) 17464 diagnoseUncapturableValueReference(S, Loc, Var, DC); 17465 } 17466 return nullptr; 17467 } 17468 17469 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17470 // certain types of variables (unnamed, variably modified types etc.) 17471 // so check for eligibility. 17472 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17473 SourceLocation Loc, 17474 const bool Diagnose, Sema &S) { 17475 17476 bool IsBlock = isa<BlockScopeInfo>(CSI); 17477 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17478 17479 // Lambdas are not allowed to capture unnamed variables 17480 // (e.g. anonymous unions). 17481 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17482 // assuming that's the intent. 17483 if (IsLambda && !Var->getDeclName()) { 17484 if (Diagnose) { 17485 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17486 S.Diag(Var->getLocation(), diag::note_declared_at); 17487 } 17488 return false; 17489 } 17490 17491 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17492 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17493 if (Diagnose) { 17494 S.Diag(Loc, diag::err_ref_vm_type); 17495 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17496 } 17497 return false; 17498 } 17499 // Prohibit structs with flexible array members too. 17500 // We cannot capture what is in the tail end of the struct. 17501 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17502 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17503 if (Diagnose) { 17504 if (IsBlock) 17505 S.Diag(Loc, diag::err_ref_flexarray_type); 17506 else 17507 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17508 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17509 } 17510 return false; 17511 } 17512 } 17513 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17514 // Lambdas and captured statements are not allowed to capture __block 17515 // variables; they don't support the expected semantics. 17516 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17517 if (Diagnose) { 17518 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17519 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17520 } 17521 return false; 17522 } 17523 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17524 if (S.getLangOpts().OpenCL && IsBlock && 17525 Var->getType()->isBlockPointerType()) { 17526 if (Diagnose) 17527 S.Diag(Loc, diag::err_opencl_block_ref_block); 17528 return false; 17529 } 17530 17531 return true; 17532 } 17533 17534 // Returns true if the capture by block was successful. 17535 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17536 SourceLocation Loc, 17537 const bool BuildAndDiagnose, 17538 QualType &CaptureType, 17539 QualType &DeclRefType, 17540 const bool Nested, 17541 Sema &S, bool Invalid) { 17542 bool ByRef = false; 17543 17544 // Blocks are not allowed to capture arrays, excepting OpenCL. 17545 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17546 // (decayed to pointers). 17547 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17548 if (BuildAndDiagnose) { 17549 S.Diag(Loc, diag::err_ref_array_type); 17550 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17551 Invalid = true; 17552 } else { 17553 return false; 17554 } 17555 } 17556 17557 // Forbid the block-capture of autoreleasing variables. 17558 if (!Invalid && 17559 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17560 if (BuildAndDiagnose) { 17561 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17562 << /*block*/ 0; 17563 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17564 Invalid = true; 17565 } else { 17566 return false; 17567 } 17568 } 17569 17570 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17571 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17572 QualType PointeeTy = PT->getPointeeType(); 17573 17574 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17575 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17576 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17577 if (BuildAndDiagnose) { 17578 SourceLocation VarLoc = Var->getLocation(); 17579 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17580 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17581 } 17582 } 17583 } 17584 17585 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17586 if (HasBlocksAttr || CaptureType->isReferenceType() || 17587 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17588 // Block capture by reference does not change the capture or 17589 // declaration reference types. 17590 ByRef = true; 17591 } else { 17592 // Block capture by copy introduces 'const'. 17593 CaptureType = CaptureType.getNonReferenceType().withConst(); 17594 DeclRefType = CaptureType; 17595 } 17596 17597 // Actually capture the variable. 17598 if (BuildAndDiagnose) 17599 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17600 CaptureType, Invalid); 17601 17602 return !Invalid; 17603 } 17604 17605 17606 /// Capture the given variable in the captured region. 17607 static bool captureInCapturedRegion( 17608 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 17609 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 17610 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 17611 bool IsTopScope, Sema &S, bool Invalid) { 17612 // By default, capture variables by reference. 17613 bool ByRef = true; 17614 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17615 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17616 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17617 // Using an LValue reference type is consistent with Lambdas (see below). 17618 if (S.isOpenMPCapturedDecl(Var)) { 17619 bool HasConst = DeclRefType.isConstQualified(); 17620 DeclRefType = DeclRefType.getUnqualifiedType(); 17621 // Don't lose diagnostics about assignments to const. 17622 if (HasConst) 17623 DeclRefType.addConst(); 17624 } 17625 // Do not capture firstprivates in tasks. 17626 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17627 OMPC_unknown) 17628 return true; 17629 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17630 RSI->OpenMPCaptureLevel); 17631 } 17632 17633 if (ByRef) 17634 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17635 else 17636 CaptureType = DeclRefType; 17637 17638 // Actually capture the variable. 17639 if (BuildAndDiagnose) 17640 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17641 Loc, SourceLocation(), CaptureType, Invalid); 17642 17643 return !Invalid; 17644 } 17645 17646 /// Capture the given variable in the lambda. 17647 static bool captureInLambda(LambdaScopeInfo *LSI, 17648 VarDecl *Var, 17649 SourceLocation Loc, 17650 const bool BuildAndDiagnose, 17651 QualType &CaptureType, 17652 QualType &DeclRefType, 17653 const bool RefersToCapturedVariable, 17654 const Sema::TryCaptureKind Kind, 17655 SourceLocation EllipsisLoc, 17656 const bool IsTopScope, 17657 Sema &S, bool Invalid) { 17658 // Determine whether we are capturing by reference or by value. 17659 bool ByRef = false; 17660 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17661 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17662 } else { 17663 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17664 } 17665 17666 // Compute the type of the field that will capture this variable. 17667 if (ByRef) { 17668 // C++11 [expr.prim.lambda]p15: 17669 // An entity is captured by reference if it is implicitly or 17670 // explicitly captured but not captured by copy. It is 17671 // unspecified whether additional unnamed non-static data 17672 // members are declared in the closure type for entities 17673 // captured by reference. 17674 // 17675 // FIXME: It is not clear whether we want to build an lvalue reference 17676 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17677 // to do the former, while EDG does the latter. Core issue 1249 will 17678 // clarify, but for now we follow GCC because it's a more permissive and 17679 // easily defensible position. 17680 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17681 } else { 17682 // C++11 [expr.prim.lambda]p14: 17683 // For each entity captured by copy, an unnamed non-static 17684 // data member is declared in the closure type. The 17685 // declaration order of these members is unspecified. The type 17686 // of such a data member is the type of the corresponding 17687 // captured entity if the entity is not a reference to an 17688 // object, or the referenced type otherwise. [Note: If the 17689 // captured entity is a reference to a function, the 17690 // corresponding data member is also a reference to a 17691 // function. - end note ] 17692 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17693 if (!RefType->getPointeeType()->isFunctionType()) 17694 CaptureType = RefType->getPointeeType(); 17695 } 17696 17697 // Forbid the lambda copy-capture of autoreleasing variables. 17698 if (!Invalid && 17699 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17700 if (BuildAndDiagnose) { 17701 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17702 S.Diag(Var->getLocation(), diag::note_previous_decl) 17703 << Var->getDeclName(); 17704 Invalid = true; 17705 } else { 17706 return false; 17707 } 17708 } 17709 17710 // Make sure that by-copy captures are of a complete and non-abstract type. 17711 if (!Invalid && BuildAndDiagnose) { 17712 if (!CaptureType->isDependentType() && 17713 S.RequireCompleteSizedType( 17714 Loc, CaptureType, 17715 diag::err_capture_of_incomplete_or_sizeless_type, 17716 Var->getDeclName())) 17717 Invalid = true; 17718 else if (S.RequireNonAbstractType(Loc, CaptureType, 17719 diag::err_capture_of_abstract_type)) 17720 Invalid = true; 17721 } 17722 } 17723 17724 // Compute the type of a reference to this captured variable. 17725 if (ByRef) 17726 DeclRefType = CaptureType.getNonReferenceType(); 17727 else { 17728 // C++ [expr.prim.lambda]p5: 17729 // The closure type for a lambda-expression has a public inline 17730 // function call operator [...]. This function call operator is 17731 // declared const (9.3.1) if and only if the lambda-expression's 17732 // parameter-declaration-clause is not followed by mutable. 17733 DeclRefType = CaptureType.getNonReferenceType(); 17734 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17735 DeclRefType.addConst(); 17736 } 17737 17738 // Add the capture. 17739 if (BuildAndDiagnose) 17740 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17741 Loc, EllipsisLoc, CaptureType, Invalid); 17742 17743 return !Invalid; 17744 } 17745 17746 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 17747 // Offer a Copy fix even if the type is dependent. 17748 if (Var->getType()->isDependentType()) 17749 return true; 17750 QualType T = Var->getType().getNonReferenceType(); 17751 if (T.isTriviallyCopyableType(Context)) 17752 return true; 17753 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 17754 17755 if (!(RD = RD->getDefinition())) 17756 return false; 17757 if (RD->hasSimpleCopyConstructor()) 17758 return true; 17759 if (RD->hasUserDeclaredCopyConstructor()) 17760 for (CXXConstructorDecl *Ctor : RD->ctors()) 17761 if (Ctor->isCopyConstructor()) 17762 return !Ctor->isDeleted(); 17763 } 17764 return false; 17765 } 17766 17767 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 17768 /// default capture. Fixes may be omitted if they aren't allowed by the 17769 /// standard, for example we can't emit a default copy capture fix-it if we 17770 /// already explicitly copy capture capture another variable. 17771 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 17772 VarDecl *Var) { 17773 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 17774 // Don't offer Capture by copy of default capture by copy fixes if Var is 17775 // known not to be copy constructible. 17776 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 17777 17778 SmallString<32> FixBuffer; 17779 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 17780 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 17781 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 17782 if (ShouldOfferCopyFix) { 17783 // Offer fixes to insert an explicit capture for the variable. 17784 // [] -> [VarName] 17785 // [OtherCapture] -> [OtherCapture, VarName] 17786 FixBuffer.assign({Separator, Var->getName()}); 17787 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17788 << Var << /*value*/ 0 17789 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17790 } 17791 // As above but capture by reference. 17792 FixBuffer.assign({Separator, "&", Var->getName()}); 17793 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17794 << Var << /*reference*/ 1 17795 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17796 } 17797 17798 // Only try to offer default capture if there are no captures excluding this 17799 // and init captures. 17800 // [this]: OK. 17801 // [X = Y]: OK. 17802 // [&A, &B]: Don't offer. 17803 // [A, B]: Don't offer. 17804 if (llvm::any_of(LSI->Captures, [](Capture &C) { 17805 return !C.isThisCapture() && !C.isInitCapture(); 17806 })) 17807 return; 17808 17809 // The default capture specifiers, '=' or '&', must appear first in the 17810 // capture body. 17811 SourceLocation DefaultInsertLoc = 17812 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 17813 17814 if (ShouldOfferCopyFix) { 17815 bool CanDefaultCopyCapture = true; 17816 // [=, *this] OK since c++17 17817 // [=, this] OK since c++20 17818 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 17819 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 17820 ? LSI->getCXXThisCapture().isCopyCapture() 17821 : false; 17822 // We can't use default capture by copy if any captures already specified 17823 // capture by copy. 17824 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 17825 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 17826 })) { 17827 FixBuffer.assign({"=", Separator}); 17828 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17829 << /*value*/ 0 17830 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17831 } 17832 } 17833 17834 // We can't use default capture by reference if any captures already specified 17835 // capture by reference. 17836 if (llvm::none_of(LSI->Captures, [](Capture &C) { 17837 return !C.isInitCapture() && C.isReferenceCapture() && 17838 !C.isThisCapture(); 17839 })) { 17840 FixBuffer.assign({"&", Separator}); 17841 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17842 << /*reference*/ 1 17843 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17844 } 17845 } 17846 17847 bool Sema::tryCaptureVariable( 17848 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17849 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17850 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17851 // An init-capture is notionally from the context surrounding its 17852 // declaration, but its parent DC is the lambda class. 17853 DeclContext *VarDC = Var->getDeclContext(); 17854 if (Var->isInitCapture()) 17855 VarDC = VarDC->getParent(); 17856 17857 DeclContext *DC = CurContext; 17858 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17859 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17860 // We need to sync up the Declaration Context with the 17861 // FunctionScopeIndexToStopAt 17862 if (FunctionScopeIndexToStopAt) { 17863 unsigned FSIndex = FunctionScopes.size() - 1; 17864 while (FSIndex != MaxFunctionScopesIndex) { 17865 DC = getLambdaAwareParentOfDeclContext(DC); 17866 --FSIndex; 17867 } 17868 } 17869 17870 17871 // If the variable is declared in the current context, there is no need to 17872 // capture it. 17873 if (VarDC == DC) return true; 17874 17875 // Capture global variables if it is required to use private copy of this 17876 // variable. 17877 bool IsGlobal = !Var->hasLocalStorage(); 17878 if (IsGlobal && 17879 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17880 MaxFunctionScopesIndex))) 17881 return true; 17882 Var = Var->getCanonicalDecl(); 17883 17884 // Walk up the stack to determine whether we can capture the variable, 17885 // performing the "simple" checks that don't depend on type. We stop when 17886 // we've either hit the declared scope of the variable or find an existing 17887 // capture of that variable. We start from the innermost capturing-entity 17888 // (the DC) and ensure that all intervening capturing-entities 17889 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17890 // declcontext can either capture the variable or have already captured 17891 // the variable. 17892 CaptureType = Var->getType(); 17893 DeclRefType = CaptureType.getNonReferenceType(); 17894 bool Nested = false; 17895 bool Explicit = (Kind != TryCapture_Implicit); 17896 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17897 do { 17898 // Only block literals, captured statements, and lambda expressions can 17899 // capture; other scopes don't work. 17900 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17901 ExprLoc, 17902 BuildAndDiagnose, 17903 *this); 17904 // We need to check for the parent *first* because, if we *have* 17905 // private-captured a global variable, we need to recursively capture it in 17906 // intermediate blocks, lambdas, etc. 17907 if (!ParentDC) { 17908 if (IsGlobal) { 17909 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17910 break; 17911 } 17912 return true; 17913 } 17914 17915 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17916 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17917 17918 17919 // Check whether we've already captured it. 17920 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17921 DeclRefType)) { 17922 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17923 break; 17924 } 17925 // If we are instantiating a generic lambda call operator body, 17926 // we do not want to capture new variables. What was captured 17927 // during either a lambdas transformation or initial parsing 17928 // should be used. 17929 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17930 if (BuildAndDiagnose) { 17931 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17932 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17933 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17934 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17935 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17936 buildLambdaCaptureFixit(*this, LSI, Var); 17937 } else 17938 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17939 } 17940 return true; 17941 } 17942 17943 // Try to capture variable-length arrays types. 17944 if (Var->getType()->isVariablyModifiedType()) { 17945 // We're going to walk down into the type and look for VLA 17946 // expressions. 17947 QualType QTy = Var->getType(); 17948 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17949 QTy = PVD->getOriginalType(); 17950 captureVariablyModifiedType(Context, QTy, CSI); 17951 } 17952 17953 if (getLangOpts().OpenMP) { 17954 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17955 // OpenMP private variables should not be captured in outer scope, so 17956 // just break here. Similarly, global variables that are captured in a 17957 // target region should not be captured outside the scope of the region. 17958 if (RSI->CapRegionKind == CR_OpenMP) { 17959 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17960 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17961 // If the variable is private (i.e. not captured) and has variably 17962 // modified type, we still need to capture the type for correct 17963 // codegen in all regions, associated with the construct. Currently, 17964 // it is captured in the innermost captured region only. 17965 if (IsOpenMPPrivateDecl != OMPC_unknown && 17966 Var->getType()->isVariablyModifiedType()) { 17967 QualType QTy = Var->getType(); 17968 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17969 QTy = PVD->getOriginalType(); 17970 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17971 I < E; ++I) { 17972 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17973 FunctionScopes[FunctionScopesIndex - I]); 17974 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17975 "Wrong number of captured regions associated with the " 17976 "OpenMP construct."); 17977 captureVariablyModifiedType(Context, QTy, OuterRSI); 17978 } 17979 } 17980 bool IsTargetCap = 17981 IsOpenMPPrivateDecl != OMPC_private && 17982 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17983 RSI->OpenMPCaptureLevel); 17984 // Do not capture global if it is not privatized in outer regions. 17985 bool IsGlobalCap = 17986 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17987 RSI->OpenMPCaptureLevel); 17988 17989 // When we detect target captures we are looking from inside the 17990 // target region, therefore we need to propagate the capture from the 17991 // enclosing region. Therefore, the capture is not initially nested. 17992 if (IsTargetCap) 17993 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17994 17995 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17996 (IsGlobal && !IsGlobalCap)) { 17997 Nested = !IsTargetCap; 17998 bool HasConst = DeclRefType.isConstQualified(); 17999 DeclRefType = DeclRefType.getUnqualifiedType(); 18000 // Don't lose diagnostics about assignments to const. 18001 if (HasConst) 18002 DeclRefType.addConst(); 18003 CaptureType = Context.getLValueReferenceType(DeclRefType); 18004 break; 18005 } 18006 } 18007 } 18008 } 18009 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 18010 // No capture-default, and this is not an explicit capture 18011 // so cannot capture this variable. 18012 if (BuildAndDiagnose) { 18013 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18014 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18015 auto *LSI = cast<LambdaScopeInfo>(CSI); 18016 if (LSI->Lambda) { 18017 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18018 buildLambdaCaptureFixit(*this, LSI, Var); 18019 } 18020 // FIXME: If we error out because an outer lambda can not implicitly 18021 // capture a variable that an inner lambda explicitly captures, we 18022 // should have the inner lambda do the explicit capture - because 18023 // it makes for cleaner diagnostics later. This would purely be done 18024 // so that the diagnostic does not misleadingly claim that a variable 18025 // can not be captured by a lambda implicitly even though it is captured 18026 // explicitly. Suggestion: 18027 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 18028 // at the function head 18029 // - cache the StartingDeclContext - this must be a lambda 18030 // - captureInLambda in the innermost lambda the variable. 18031 } 18032 return true; 18033 } 18034 18035 FunctionScopesIndex--; 18036 DC = ParentDC; 18037 Explicit = false; 18038 } while (!VarDC->Equals(DC)); 18039 18040 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 18041 // computing the type of the capture at each step, checking type-specific 18042 // requirements, and adding captures if requested. 18043 // If the variable had already been captured previously, we start capturing 18044 // at the lambda nested within that one. 18045 bool Invalid = false; 18046 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 18047 ++I) { 18048 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 18049 18050 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18051 // certain types of variables (unnamed, variably modified types etc.) 18052 // so check for eligibility. 18053 if (!Invalid) 18054 Invalid = 18055 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 18056 18057 // After encountering an error, if we're actually supposed to capture, keep 18058 // capturing in nested contexts to suppress any follow-on diagnostics. 18059 if (Invalid && !BuildAndDiagnose) 18060 return true; 18061 18062 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 18063 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18064 DeclRefType, Nested, *this, Invalid); 18065 Nested = true; 18066 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18067 Invalid = !captureInCapturedRegion( 18068 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 18069 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 18070 Nested = true; 18071 } else { 18072 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18073 Invalid = 18074 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18075 DeclRefType, Nested, Kind, EllipsisLoc, 18076 /*IsTopScope*/ I == N - 1, *this, Invalid); 18077 Nested = true; 18078 } 18079 18080 if (Invalid && !BuildAndDiagnose) 18081 return true; 18082 } 18083 return Invalid; 18084 } 18085 18086 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 18087 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 18088 QualType CaptureType; 18089 QualType DeclRefType; 18090 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 18091 /*BuildAndDiagnose=*/true, CaptureType, 18092 DeclRefType, nullptr); 18093 } 18094 18095 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 18096 QualType CaptureType; 18097 QualType DeclRefType; 18098 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18099 /*BuildAndDiagnose=*/false, CaptureType, 18100 DeclRefType, nullptr); 18101 } 18102 18103 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 18104 QualType CaptureType; 18105 QualType DeclRefType; 18106 18107 // Determine whether we can capture this variable. 18108 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18109 /*BuildAndDiagnose=*/false, CaptureType, 18110 DeclRefType, nullptr)) 18111 return QualType(); 18112 18113 return DeclRefType; 18114 } 18115 18116 namespace { 18117 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 18118 // The produced TemplateArgumentListInfo* points to data stored within this 18119 // object, so should only be used in contexts where the pointer will not be 18120 // used after the CopiedTemplateArgs object is destroyed. 18121 class CopiedTemplateArgs { 18122 bool HasArgs; 18123 TemplateArgumentListInfo TemplateArgStorage; 18124 public: 18125 template<typename RefExpr> 18126 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 18127 if (HasArgs) 18128 E->copyTemplateArgumentsInto(TemplateArgStorage); 18129 } 18130 operator TemplateArgumentListInfo*() 18131 #ifdef __has_cpp_attribute 18132 #if __has_cpp_attribute(clang::lifetimebound) 18133 [[clang::lifetimebound]] 18134 #endif 18135 #endif 18136 { 18137 return HasArgs ? &TemplateArgStorage : nullptr; 18138 } 18139 }; 18140 } 18141 18142 /// Walk the set of potential results of an expression and mark them all as 18143 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 18144 /// 18145 /// \return A new expression if we found any potential results, ExprEmpty() if 18146 /// not, and ExprError() if we diagnosed an error. 18147 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 18148 NonOdrUseReason NOUR) { 18149 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 18150 // an object that satisfies the requirements for appearing in a 18151 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 18152 // is immediately applied." This function handles the lvalue-to-rvalue 18153 // conversion part. 18154 // 18155 // If we encounter a node that claims to be an odr-use but shouldn't be, we 18156 // transform it into the relevant kind of non-odr-use node and rebuild the 18157 // tree of nodes leading to it. 18158 // 18159 // This is a mini-TreeTransform that only transforms a restricted subset of 18160 // nodes (and only certain operands of them). 18161 18162 // Rebuild a subexpression. 18163 auto Rebuild = [&](Expr *Sub) { 18164 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 18165 }; 18166 18167 // Check whether a potential result satisfies the requirements of NOUR. 18168 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 18169 // Any entity other than a VarDecl is always odr-used whenever it's named 18170 // in a potentially-evaluated expression. 18171 auto *VD = dyn_cast<VarDecl>(D); 18172 if (!VD) 18173 return true; 18174 18175 // C++2a [basic.def.odr]p4: 18176 // A variable x whose name appears as a potentially-evalauted expression 18177 // e is odr-used by e unless 18178 // -- x is a reference that is usable in constant expressions, or 18179 // -- x is a variable of non-reference type that is usable in constant 18180 // expressions and has no mutable subobjects, and e is an element of 18181 // the set of potential results of an expression of 18182 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18183 // conversion is applied, or 18184 // -- x is a variable of non-reference type, and e is an element of the 18185 // set of potential results of a discarded-value expression to which 18186 // the lvalue-to-rvalue conversion is not applied 18187 // 18188 // We check the first bullet and the "potentially-evaluated" condition in 18189 // BuildDeclRefExpr. We check the type requirements in the second bullet 18190 // in CheckLValueToRValueConversionOperand below. 18191 switch (NOUR) { 18192 case NOUR_None: 18193 case NOUR_Unevaluated: 18194 llvm_unreachable("unexpected non-odr-use-reason"); 18195 18196 case NOUR_Constant: 18197 // Constant references were handled when they were built. 18198 if (VD->getType()->isReferenceType()) 18199 return true; 18200 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18201 if (RD->hasMutableFields()) 18202 return true; 18203 if (!VD->isUsableInConstantExpressions(S.Context)) 18204 return true; 18205 break; 18206 18207 case NOUR_Discarded: 18208 if (VD->getType()->isReferenceType()) 18209 return true; 18210 break; 18211 } 18212 return false; 18213 }; 18214 18215 // Mark that this expression does not constitute an odr-use. 18216 auto MarkNotOdrUsed = [&] { 18217 S.MaybeODRUseExprs.remove(E); 18218 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18219 LSI->markVariableExprAsNonODRUsed(E); 18220 }; 18221 18222 // C++2a [basic.def.odr]p2: 18223 // The set of potential results of an expression e is defined as follows: 18224 switch (E->getStmtClass()) { 18225 // -- If e is an id-expression, ... 18226 case Expr::DeclRefExprClass: { 18227 auto *DRE = cast<DeclRefExpr>(E); 18228 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18229 break; 18230 18231 // Rebuild as a non-odr-use DeclRefExpr. 18232 MarkNotOdrUsed(); 18233 return DeclRefExpr::Create( 18234 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18235 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18236 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18237 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18238 } 18239 18240 case Expr::FunctionParmPackExprClass: { 18241 auto *FPPE = cast<FunctionParmPackExpr>(E); 18242 // If any of the declarations in the pack is odr-used, then the expression 18243 // as a whole constitutes an odr-use. 18244 for (VarDecl *D : *FPPE) 18245 if (IsPotentialResultOdrUsed(D)) 18246 return ExprEmpty(); 18247 18248 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18249 // nothing cares about whether we marked this as an odr-use, but it might 18250 // be useful for non-compiler tools. 18251 MarkNotOdrUsed(); 18252 break; 18253 } 18254 18255 // -- If e is a subscripting operation with an array operand... 18256 case Expr::ArraySubscriptExprClass: { 18257 auto *ASE = cast<ArraySubscriptExpr>(E); 18258 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18259 if (!OldBase->getType()->isArrayType()) 18260 break; 18261 ExprResult Base = Rebuild(OldBase); 18262 if (!Base.isUsable()) 18263 return Base; 18264 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18265 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18266 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18267 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18268 ASE->getRBracketLoc()); 18269 } 18270 18271 case Expr::MemberExprClass: { 18272 auto *ME = cast<MemberExpr>(E); 18273 // -- If e is a class member access expression [...] naming a non-static 18274 // data member... 18275 if (isa<FieldDecl>(ME->getMemberDecl())) { 18276 ExprResult Base = Rebuild(ME->getBase()); 18277 if (!Base.isUsable()) 18278 return Base; 18279 return MemberExpr::Create( 18280 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18281 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18282 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18283 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18284 ME->getObjectKind(), ME->isNonOdrUse()); 18285 } 18286 18287 if (ME->getMemberDecl()->isCXXInstanceMember()) 18288 break; 18289 18290 // -- If e is a class member access expression naming a static data member, 18291 // ... 18292 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18293 break; 18294 18295 // Rebuild as a non-odr-use MemberExpr. 18296 MarkNotOdrUsed(); 18297 return MemberExpr::Create( 18298 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 18299 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 18300 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 18301 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 18302 } 18303 18304 case Expr::BinaryOperatorClass: { 18305 auto *BO = cast<BinaryOperator>(E); 18306 Expr *LHS = BO->getLHS(); 18307 Expr *RHS = BO->getRHS(); 18308 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18309 if (BO->getOpcode() == BO_PtrMemD) { 18310 ExprResult Sub = Rebuild(LHS); 18311 if (!Sub.isUsable()) 18312 return Sub; 18313 LHS = Sub.get(); 18314 // -- If e is a comma expression, ... 18315 } else if (BO->getOpcode() == BO_Comma) { 18316 ExprResult Sub = Rebuild(RHS); 18317 if (!Sub.isUsable()) 18318 return Sub; 18319 RHS = Sub.get(); 18320 } else { 18321 break; 18322 } 18323 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18324 LHS, RHS); 18325 } 18326 18327 // -- If e has the form (e1)... 18328 case Expr::ParenExprClass: { 18329 auto *PE = cast<ParenExpr>(E); 18330 ExprResult Sub = Rebuild(PE->getSubExpr()); 18331 if (!Sub.isUsable()) 18332 return Sub; 18333 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18334 } 18335 18336 // -- If e is a glvalue conditional expression, ... 18337 // We don't apply this to a binary conditional operator. FIXME: Should we? 18338 case Expr::ConditionalOperatorClass: { 18339 auto *CO = cast<ConditionalOperator>(E); 18340 ExprResult LHS = Rebuild(CO->getLHS()); 18341 if (LHS.isInvalid()) 18342 return ExprError(); 18343 ExprResult RHS = Rebuild(CO->getRHS()); 18344 if (RHS.isInvalid()) 18345 return ExprError(); 18346 if (!LHS.isUsable() && !RHS.isUsable()) 18347 return ExprEmpty(); 18348 if (!LHS.isUsable()) 18349 LHS = CO->getLHS(); 18350 if (!RHS.isUsable()) 18351 RHS = CO->getRHS(); 18352 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18353 CO->getCond(), LHS.get(), RHS.get()); 18354 } 18355 18356 // [Clang extension] 18357 // -- If e has the form __extension__ e1... 18358 case Expr::UnaryOperatorClass: { 18359 auto *UO = cast<UnaryOperator>(E); 18360 if (UO->getOpcode() != UO_Extension) 18361 break; 18362 ExprResult Sub = Rebuild(UO->getSubExpr()); 18363 if (!Sub.isUsable()) 18364 return Sub; 18365 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18366 Sub.get()); 18367 } 18368 18369 // [Clang extension] 18370 // -- If e has the form _Generic(...), the set of potential results is the 18371 // union of the sets of potential results of the associated expressions. 18372 case Expr::GenericSelectionExprClass: { 18373 auto *GSE = cast<GenericSelectionExpr>(E); 18374 18375 SmallVector<Expr *, 4> AssocExprs; 18376 bool AnyChanged = false; 18377 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18378 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18379 if (AssocExpr.isInvalid()) 18380 return ExprError(); 18381 if (AssocExpr.isUsable()) { 18382 AssocExprs.push_back(AssocExpr.get()); 18383 AnyChanged = true; 18384 } else { 18385 AssocExprs.push_back(OrigAssocExpr); 18386 } 18387 } 18388 18389 return AnyChanged ? S.CreateGenericSelectionExpr( 18390 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18391 GSE->getRParenLoc(), GSE->getControllingExpr(), 18392 GSE->getAssocTypeSourceInfos(), AssocExprs) 18393 : ExprEmpty(); 18394 } 18395 18396 // [Clang extension] 18397 // -- If e has the form __builtin_choose_expr(...), the set of potential 18398 // results is the union of the sets of potential results of the 18399 // second and third subexpressions. 18400 case Expr::ChooseExprClass: { 18401 auto *CE = cast<ChooseExpr>(E); 18402 18403 ExprResult LHS = Rebuild(CE->getLHS()); 18404 if (LHS.isInvalid()) 18405 return ExprError(); 18406 18407 ExprResult RHS = Rebuild(CE->getLHS()); 18408 if (RHS.isInvalid()) 18409 return ExprError(); 18410 18411 if (!LHS.get() && !RHS.get()) 18412 return ExprEmpty(); 18413 if (!LHS.isUsable()) 18414 LHS = CE->getLHS(); 18415 if (!RHS.isUsable()) 18416 RHS = CE->getRHS(); 18417 18418 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18419 RHS.get(), CE->getRParenLoc()); 18420 } 18421 18422 // Step through non-syntactic nodes. 18423 case Expr::ConstantExprClass: { 18424 auto *CE = cast<ConstantExpr>(E); 18425 ExprResult Sub = Rebuild(CE->getSubExpr()); 18426 if (!Sub.isUsable()) 18427 return Sub; 18428 return ConstantExpr::Create(S.Context, Sub.get()); 18429 } 18430 18431 // We could mostly rely on the recursive rebuilding to rebuild implicit 18432 // casts, but not at the top level, so rebuild them here. 18433 case Expr::ImplicitCastExprClass: { 18434 auto *ICE = cast<ImplicitCastExpr>(E); 18435 // Only step through the narrow set of cast kinds we expect to encounter. 18436 // Anything else suggests we've left the region in which potential results 18437 // can be found. 18438 switch (ICE->getCastKind()) { 18439 case CK_NoOp: 18440 case CK_DerivedToBase: 18441 case CK_UncheckedDerivedToBase: { 18442 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18443 if (!Sub.isUsable()) 18444 return Sub; 18445 CXXCastPath Path(ICE->path()); 18446 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18447 ICE->getValueKind(), &Path); 18448 } 18449 18450 default: 18451 break; 18452 } 18453 break; 18454 } 18455 18456 default: 18457 break; 18458 } 18459 18460 // Can't traverse through this node. Nothing to do. 18461 return ExprEmpty(); 18462 } 18463 18464 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18465 // Check whether the operand is or contains an object of non-trivial C union 18466 // type. 18467 if (E->getType().isVolatileQualified() && 18468 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18469 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18470 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18471 Sema::NTCUC_LValueToRValueVolatile, 18472 NTCUK_Destruct|NTCUK_Copy); 18473 18474 // C++2a [basic.def.odr]p4: 18475 // [...] an expression of non-volatile-qualified non-class type to which 18476 // the lvalue-to-rvalue conversion is applied [...] 18477 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18478 return E; 18479 18480 ExprResult Result = 18481 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18482 if (Result.isInvalid()) 18483 return ExprError(); 18484 return Result.get() ? Result : E; 18485 } 18486 18487 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18488 Res = CorrectDelayedTyposInExpr(Res); 18489 18490 if (!Res.isUsable()) 18491 return Res; 18492 18493 // If a constant-expression is a reference to a variable where we delay 18494 // deciding whether it is an odr-use, just assume we will apply the 18495 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18496 // (a non-type template argument), we have special handling anyway. 18497 return CheckLValueToRValueConversionOperand(Res.get()); 18498 } 18499 18500 void Sema::CleanupVarDeclMarking() { 18501 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18502 // call. 18503 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18504 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18505 18506 for (Expr *E : LocalMaybeODRUseExprs) { 18507 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18508 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18509 DRE->getLocation(), *this); 18510 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18511 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18512 *this); 18513 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18514 for (VarDecl *VD : *FP) 18515 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18516 } else { 18517 llvm_unreachable("Unexpected expression"); 18518 } 18519 } 18520 18521 assert(MaybeODRUseExprs.empty() && 18522 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18523 } 18524 18525 static void DoMarkVarDeclReferenced( 18526 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 18527 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18528 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18529 isa<FunctionParmPackExpr>(E)) && 18530 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18531 Var->setReferenced(); 18532 18533 if (Var->isInvalidDecl()) 18534 return; 18535 18536 auto *MSI = Var->getMemberSpecializationInfo(); 18537 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18538 : Var->getTemplateSpecializationKind(); 18539 18540 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18541 bool UsableInConstantExpr = 18542 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18543 18544 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 18545 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 18546 } 18547 18548 // C++20 [expr.const]p12: 18549 // A variable [...] is needed for constant evaluation if it is [...] a 18550 // variable whose name appears as a potentially constant evaluated 18551 // expression that is either a contexpr variable or is of non-volatile 18552 // const-qualified integral type or of reference type 18553 bool NeededForConstantEvaluation = 18554 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18555 18556 bool NeedDefinition = 18557 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18558 18559 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18560 "Can't instantiate a partial template specialization."); 18561 18562 // If this might be a member specialization of a static data member, check 18563 // the specialization is visible. We already did the checks for variable 18564 // template specializations when we created them. 18565 if (NeedDefinition && TSK != TSK_Undeclared && 18566 !isa<VarTemplateSpecializationDecl>(Var)) 18567 SemaRef.checkSpecializationVisibility(Loc, Var); 18568 18569 // Perform implicit instantiation of static data members, static data member 18570 // templates of class templates, and variable template specializations. Delay 18571 // instantiations of variable templates, except for those that could be used 18572 // in a constant expression. 18573 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18574 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18575 // instantiation declaration if a variable is usable in a constant 18576 // expression (among other cases). 18577 bool TryInstantiating = 18578 TSK == TSK_ImplicitInstantiation || 18579 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18580 18581 if (TryInstantiating) { 18582 SourceLocation PointOfInstantiation = 18583 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18584 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18585 if (FirstInstantiation) { 18586 PointOfInstantiation = Loc; 18587 if (MSI) 18588 MSI->setPointOfInstantiation(PointOfInstantiation); 18589 // FIXME: Notify listener. 18590 else 18591 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18592 } 18593 18594 if (UsableInConstantExpr) { 18595 // Do not defer instantiations of variables that could be used in a 18596 // constant expression. 18597 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18598 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18599 }); 18600 18601 // Re-set the member to trigger a recomputation of the dependence bits 18602 // for the expression. 18603 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18604 DRE->setDecl(DRE->getDecl()); 18605 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18606 ME->setMemberDecl(ME->getMemberDecl()); 18607 } else if (FirstInstantiation || 18608 isa<VarTemplateSpecializationDecl>(Var)) { 18609 // FIXME: For a specialization of a variable template, we don't 18610 // distinguish between "declaration and type implicitly instantiated" 18611 // and "implicit instantiation of definition requested", so we have 18612 // no direct way to avoid enqueueing the pending instantiation 18613 // multiple times. 18614 SemaRef.PendingInstantiations 18615 .push_back(std::make_pair(Var, PointOfInstantiation)); 18616 } 18617 } 18618 } 18619 18620 // C++2a [basic.def.odr]p4: 18621 // A variable x whose name appears as a potentially-evaluated expression e 18622 // is odr-used by e unless 18623 // -- x is a reference that is usable in constant expressions 18624 // -- x is a variable of non-reference type that is usable in constant 18625 // expressions and has no mutable subobjects [FIXME], and e is an 18626 // element of the set of potential results of an expression of 18627 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18628 // conversion is applied 18629 // -- x is a variable of non-reference type, and e is an element of the set 18630 // of potential results of a discarded-value expression to which the 18631 // lvalue-to-rvalue conversion is not applied [FIXME] 18632 // 18633 // We check the first part of the second bullet here, and 18634 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18635 // FIXME: To get the third bullet right, we need to delay this even for 18636 // variables that are not usable in constant expressions. 18637 18638 // If we already know this isn't an odr-use, there's nothing more to do. 18639 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18640 if (DRE->isNonOdrUse()) 18641 return; 18642 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18643 if (ME->isNonOdrUse()) 18644 return; 18645 18646 switch (OdrUse) { 18647 case OdrUseContext::None: 18648 assert((!E || isa<FunctionParmPackExpr>(E)) && 18649 "missing non-odr-use marking for unevaluated decl ref"); 18650 break; 18651 18652 case OdrUseContext::FormallyOdrUsed: 18653 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18654 // behavior. 18655 break; 18656 18657 case OdrUseContext::Used: 18658 // If we might later find that this expression isn't actually an odr-use, 18659 // delay the marking. 18660 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18661 SemaRef.MaybeODRUseExprs.insert(E); 18662 else 18663 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18664 break; 18665 18666 case OdrUseContext::Dependent: 18667 // If this is a dependent context, we don't need to mark variables as 18668 // odr-used, but we may still need to track them for lambda capture. 18669 // FIXME: Do we also need to do this inside dependent typeid expressions 18670 // (which are modeled as unevaluated at this point)? 18671 const bool RefersToEnclosingScope = 18672 (SemaRef.CurContext != Var->getDeclContext() && 18673 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18674 if (RefersToEnclosingScope) { 18675 LambdaScopeInfo *const LSI = 18676 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18677 if (LSI && (!LSI->CallOperator || 18678 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18679 // If a variable could potentially be odr-used, defer marking it so 18680 // until we finish analyzing the full expression for any 18681 // lvalue-to-rvalue 18682 // or discarded value conversions that would obviate odr-use. 18683 // Add it to the list of potential captures that will be analyzed 18684 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18685 // unless the variable is a reference that was initialized by a constant 18686 // expression (this will never need to be captured or odr-used). 18687 // 18688 // FIXME: We can simplify this a lot after implementing P0588R1. 18689 assert(E && "Capture variable should be used in an expression."); 18690 if (!Var->getType()->isReferenceType() || 18691 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18692 LSI->addPotentialCapture(E->IgnoreParens()); 18693 } 18694 } 18695 break; 18696 } 18697 } 18698 18699 /// Mark a variable referenced, and check whether it is odr-used 18700 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18701 /// used directly for normal expressions referring to VarDecl. 18702 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18703 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 18704 } 18705 18706 static void 18707 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 18708 bool MightBeOdrUse, 18709 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18710 if (SemaRef.isInOpenMPDeclareTargetContext()) 18711 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18712 18713 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18714 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 18715 return; 18716 } 18717 18718 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18719 18720 // If this is a call to a method via a cast, also mark the method in the 18721 // derived class used in case codegen can devirtualize the call. 18722 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18723 if (!ME) 18724 return; 18725 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18726 if (!MD) 18727 return; 18728 // Only attempt to devirtualize if this is truly a virtual call. 18729 bool IsVirtualCall = MD->isVirtual() && 18730 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18731 if (!IsVirtualCall) 18732 return; 18733 18734 // If it's possible to devirtualize the call, mark the called function 18735 // referenced. 18736 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18737 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18738 if (DM) 18739 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18740 } 18741 18742 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18743 /// 18744 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18745 /// handled with care if the DeclRefExpr is not newly-created. 18746 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18747 // TODO: update this with DR# once a defect report is filed. 18748 // C++11 defect. The address of a pure member should not be an ODR use, even 18749 // if it's a qualified reference. 18750 bool OdrUse = true; 18751 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18752 if (Method->isVirtual() && 18753 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18754 OdrUse = false; 18755 18756 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18757 if (!isUnevaluatedContext() && !isConstantEvaluated() && 18758 FD->isConsteval() && !RebuildingImmediateInvocation) 18759 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18760 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 18761 RefsMinusAssignments); 18762 } 18763 18764 /// Perform reference-marking and odr-use handling for a MemberExpr. 18765 void Sema::MarkMemberReferenced(MemberExpr *E) { 18766 // C++11 [basic.def.odr]p2: 18767 // A non-overloaded function whose name appears as a potentially-evaluated 18768 // expression or a member of a set of candidate functions, if selected by 18769 // overload resolution when referred to from a potentially-evaluated 18770 // expression, is odr-used, unless it is a pure virtual function and its 18771 // name is not explicitly qualified. 18772 bool MightBeOdrUse = true; 18773 if (E->performsVirtualDispatch(getLangOpts())) { 18774 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18775 if (Method->isPure()) 18776 MightBeOdrUse = false; 18777 } 18778 SourceLocation Loc = 18779 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18780 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 18781 RefsMinusAssignments); 18782 } 18783 18784 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18785 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18786 for (VarDecl *VD : *E) 18787 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 18788 RefsMinusAssignments); 18789 } 18790 18791 /// Perform marking for a reference to an arbitrary declaration. It 18792 /// marks the declaration referenced, and performs odr-use checking for 18793 /// functions and variables. This method should not be used when building a 18794 /// normal expression which refers to a variable. 18795 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18796 bool MightBeOdrUse) { 18797 if (MightBeOdrUse) { 18798 if (auto *VD = dyn_cast<VarDecl>(D)) { 18799 MarkVariableReferenced(Loc, VD); 18800 return; 18801 } 18802 } 18803 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18804 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18805 return; 18806 } 18807 D->setReferenced(); 18808 } 18809 18810 namespace { 18811 // Mark all of the declarations used by a type as referenced. 18812 // FIXME: Not fully implemented yet! We need to have a better understanding 18813 // of when we're entering a context we should not recurse into. 18814 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18815 // TreeTransforms rebuilding the type in a new context. Rather than 18816 // duplicating the TreeTransform logic, we should consider reusing it here. 18817 // Currently that causes problems when rebuilding LambdaExprs. 18818 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18819 Sema &S; 18820 SourceLocation Loc; 18821 18822 public: 18823 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18824 18825 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18826 18827 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18828 }; 18829 } 18830 18831 bool MarkReferencedDecls::TraverseTemplateArgument( 18832 const TemplateArgument &Arg) { 18833 { 18834 // A non-type template argument is a constant-evaluated context. 18835 EnterExpressionEvaluationContext Evaluated( 18836 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18837 if (Arg.getKind() == TemplateArgument::Declaration) { 18838 if (Decl *D = Arg.getAsDecl()) 18839 S.MarkAnyDeclReferenced(Loc, D, true); 18840 } else if (Arg.getKind() == TemplateArgument::Expression) { 18841 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18842 } 18843 } 18844 18845 return Inherited::TraverseTemplateArgument(Arg); 18846 } 18847 18848 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18849 MarkReferencedDecls Marker(*this, Loc); 18850 Marker.TraverseType(T); 18851 } 18852 18853 namespace { 18854 /// Helper class that marks all of the declarations referenced by 18855 /// potentially-evaluated subexpressions as "referenced". 18856 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18857 public: 18858 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18859 bool SkipLocalVariables; 18860 18861 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18862 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18863 18864 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18865 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18866 } 18867 18868 void VisitDeclRefExpr(DeclRefExpr *E) { 18869 // If we were asked not to visit local variables, don't. 18870 if (SkipLocalVariables) { 18871 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18872 if (VD->hasLocalStorage()) 18873 return; 18874 } 18875 18876 // FIXME: This can trigger the instantiation of the initializer of a 18877 // variable, which can cause the expression to become value-dependent 18878 // or error-dependent. Do we need to propagate the new dependence bits? 18879 S.MarkDeclRefReferenced(E); 18880 } 18881 18882 void VisitMemberExpr(MemberExpr *E) { 18883 S.MarkMemberReferenced(E); 18884 Visit(E->getBase()); 18885 } 18886 }; 18887 } // namespace 18888 18889 /// Mark any declarations that appear within this expression or any 18890 /// potentially-evaluated subexpressions as "referenced". 18891 /// 18892 /// \param SkipLocalVariables If true, don't mark local variables as 18893 /// 'referenced'. 18894 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18895 bool SkipLocalVariables) { 18896 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18897 } 18898 18899 /// Emit a diagnostic that describes an effect on the run-time behavior 18900 /// of the program being compiled. 18901 /// 18902 /// This routine emits the given diagnostic when the code currently being 18903 /// type-checked is "potentially evaluated", meaning that there is a 18904 /// possibility that the code will actually be executable. Code in sizeof() 18905 /// expressions, code used only during overload resolution, etc., are not 18906 /// potentially evaluated. This routine will suppress such diagnostics or, 18907 /// in the absolutely nutty case of potentially potentially evaluated 18908 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18909 /// later. 18910 /// 18911 /// This routine should be used for all diagnostics that describe the run-time 18912 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18913 /// Failure to do so will likely result in spurious diagnostics or failures 18914 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18915 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18916 const PartialDiagnostic &PD) { 18917 switch (ExprEvalContexts.back().Context) { 18918 case ExpressionEvaluationContext::Unevaluated: 18919 case ExpressionEvaluationContext::UnevaluatedList: 18920 case ExpressionEvaluationContext::UnevaluatedAbstract: 18921 case ExpressionEvaluationContext::DiscardedStatement: 18922 // The argument will never be evaluated, so don't complain. 18923 break; 18924 18925 case ExpressionEvaluationContext::ConstantEvaluated: 18926 // Relevant diagnostics should be produced by constant evaluation. 18927 break; 18928 18929 case ExpressionEvaluationContext::PotentiallyEvaluated: 18930 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18931 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18932 FunctionScopes.back()->PossiblyUnreachableDiags. 18933 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18934 return true; 18935 } 18936 18937 // The initializer of a constexpr variable or of the first declaration of a 18938 // static data member is not syntactically a constant evaluated constant, 18939 // but nonetheless is always required to be a constant expression, so we 18940 // can skip diagnosing. 18941 // FIXME: Using the mangling context here is a hack. 18942 if (auto *VD = dyn_cast_or_null<VarDecl>( 18943 ExprEvalContexts.back().ManglingContextDecl)) { 18944 if (VD->isConstexpr() || 18945 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18946 break; 18947 // FIXME: For any other kind of variable, we should build a CFG for its 18948 // initializer and check whether the context in question is reachable. 18949 } 18950 18951 Diag(Loc, PD); 18952 return true; 18953 } 18954 18955 return false; 18956 } 18957 18958 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18959 const PartialDiagnostic &PD) { 18960 return DiagRuntimeBehavior( 18961 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18962 } 18963 18964 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18965 CallExpr *CE, FunctionDecl *FD) { 18966 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18967 return false; 18968 18969 // If we're inside a decltype's expression, don't check for a valid return 18970 // type or construct temporaries until we know whether this is the last call. 18971 if (ExprEvalContexts.back().ExprContext == 18972 ExpressionEvaluationContextRecord::EK_Decltype) { 18973 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18974 return false; 18975 } 18976 18977 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18978 FunctionDecl *FD; 18979 CallExpr *CE; 18980 18981 public: 18982 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18983 : FD(FD), CE(CE) { } 18984 18985 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18986 if (!FD) { 18987 S.Diag(Loc, diag::err_call_incomplete_return) 18988 << T << CE->getSourceRange(); 18989 return; 18990 } 18991 18992 S.Diag(Loc, diag::err_call_function_incomplete_return) 18993 << CE->getSourceRange() << FD << T; 18994 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18995 << FD->getDeclName(); 18996 } 18997 } Diagnoser(FD, CE); 18998 18999 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 19000 return true; 19001 19002 return false; 19003 } 19004 19005 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 19006 // will prevent this condition from triggering, which is what we want. 19007 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 19008 SourceLocation Loc; 19009 19010 unsigned diagnostic = diag::warn_condition_is_assignment; 19011 bool IsOrAssign = false; 19012 19013 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 19014 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 19015 return; 19016 19017 IsOrAssign = Op->getOpcode() == BO_OrAssign; 19018 19019 // Greylist some idioms by putting them into a warning subcategory. 19020 if (ObjCMessageExpr *ME 19021 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 19022 Selector Sel = ME->getSelector(); 19023 19024 // self = [<foo> init...] 19025 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 19026 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19027 19028 // <foo> = [<bar> nextObject] 19029 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 19030 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19031 } 19032 19033 Loc = Op->getOperatorLoc(); 19034 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 19035 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 19036 return; 19037 19038 IsOrAssign = Op->getOperator() == OO_PipeEqual; 19039 Loc = Op->getOperatorLoc(); 19040 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 19041 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 19042 else { 19043 // Not an assignment. 19044 return; 19045 } 19046 19047 Diag(Loc, diagnostic) << E->getSourceRange(); 19048 19049 SourceLocation Open = E->getBeginLoc(); 19050 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 19051 Diag(Loc, diag::note_condition_assign_silence) 19052 << FixItHint::CreateInsertion(Open, "(") 19053 << FixItHint::CreateInsertion(Close, ")"); 19054 19055 if (IsOrAssign) 19056 Diag(Loc, diag::note_condition_or_assign_to_comparison) 19057 << FixItHint::CreateReplacement(Loc, "!="); 19058 else 19059 Diag(Loc, diag::note_condition_assign_to_comparison) 19060 << FixItHint::CreateReplacement(Loc, "=="); 19061 } 19062 19063 /// Redundant parentheses over an equality comparison can indicate 19064 /// that the user intended an assignment used as condition. 19065 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 19066 // Don't warn if the parens came from a macro. 19067 SourceLocation parenLoc = ParenE->getBeginLoc(); 19068 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 19069 return; 19070 // Don't warn for dependent expressions. 19071 if (ParenE->isTypeDependent()) 19072 return; 19073 19074 Expr *E = ParenE->IgnoreParens(); 19075 19076 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 19077 if (opE->getOpcode() == BO_EQ && 19078 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 19079 == Expr::MLV_Valid) { 19080 SourceLocation Loc = opE->getOperatorLoc(); 19081 19082 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 19083 SourceRange ParenERange = ParenE->getSourceRange(); 19084 Diag(Loc, diag::note_equality_comparison_silence) 19085 << FixItHint::CreateRemoval(ParenERange.getBegin()) 19086 << FixItHint::CreateRemoval(ParenERange.getEnd()); 19087 Diag(Loc, diag::note_equality_comparison_to_assign) 19088 << FixItHint::CreateReplacement(Loc, "="); 19089 } 19090 } 19091 19092 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 19093 bool IsConstexpr) { 19094 DiagnoseAssignmentAsCondition(E); 19095 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 19096 DiagnoseEqualityWithExtraParens(parenE); 19097 19098 ExprResult result = CheckPlaceholderExpr(E); 19099 if (result.isInvalid()) return ExprError(); 19100 E = result.get(); 19101 19102 if (!E->isTypeDependent()) { 19103 if (getLangOpts().CPlusPlus) 19104 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 19105 19106 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 19107 if (ERes.isInvalid()) 19108 return ExprError(); 19109 E = ERes.get(); 19110 19111 QualType T = E->getType(); 19112 if (!T->isScalarType()) { // C99 6.8.4.1p1 19113 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 19114 << T << E->getSourceRange(); 19115 return ExprError(); 19116 } 19117 CheckBoolLikeConversion(E, Loc); 19118 } 19119 19120 return E; 19121 } 19122 19123 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 19124 Expr *SubExpr, ConditionKind CK) { 19125 // Empty conditions are valid in for-statements. 19126 if (!SubExpr) 19127 return ConditionResult(); 19128 19129 ExprResult Cond; 19130 switch (CK) { 19131 case ConditionKind::Boolean: 19132 Cond = CheckBooleanCondition(Loc, SubExpr); 19133 break; 19134 19135 case ConditionKind::ConstexprIf: 19136 Cond = CheckBooleanCondition(Loc, SubExpr, true); 19137 break; 19138 19139 case ConditionKind::Switch: 19140 Cond = CheckSwitchCondition(Loc, SubExpr); 19141 break; 19142 } 19143 if (Cond.isInvalid()) { 19144 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 19145 {SubExpr}); 19146 if (!Cond.get()) 19147 return ConditionError(); 19148 } 19149 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 19150 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 19151 if (!FullExpr.get()) 19152 return ConditionError(); 19153 19154 return ConditionResult(*this, nullptr, FullExpr, 19155 CK == ConditionKind::ConstexprIf); 19156 } 19157 19158 namespace { 19159 /// A visitor for rebuilding a call to an __unknown_any expression 19160 /// to have an appropriate type. 19161 struct RebuildUnknownAnyFunction 19162 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 19163 19164 Sema &S; 19165 19166 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 19167 19168 ExprResult VisitStmt(Stmt *S) { 19169 llvm_unreachable("unexpected statement!"); 19170 } 19171 19172 ExprResult VisitExpr(Expr *E) { 19173 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 19174 << E->getSourceRange(); 19175 return ExprError(); 19176 } 19177 19178 /// Rebuild an expression which simply semantically wraps another 19179 /// expression which it shares the type and value kind of. 19180 template <class T> ExprResult rebuildSugarExpr(T *E) { 19181 ExprResult SubResult = Visit(E->getSubExpr()); 19182 if (SubResult.isInvalid()) return ExprError(); 19183 19184 Expr *SubExpr = SubResult.get(); 19185 E->setSubExpr(SubExpr); 19186 E->setType(SubExpr->getType()); 19187 E->setValueKind(SubExpr->getValueKind()); 19188 assert(E->getObjectKind() == OK_Ordinary); 19189 return E; 19190 } 19191 19192 ExprResult VisitParenExpr(ParenExpr *E) { 19193 return rebuildSugarExpr(E); 19194 } 19195 19196 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19197 return rebuildSugarExpr(E); 19198 } 19199 19200 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19201 ExprResult SubResult = Visit(E->getSubExpr()); 19202 if (SubResult.isInvalid()) return ExprError(); 19203 19204 Expr *SubExpr = SubResult.get(); 19205 E->setSubExpr(SubExpr); 19206 E->setType(S.Context.getPointerType(SubExpr->getType())); 19207 assert(E->isPRValue()); 19208 assert(E->getObjectKind() == OK_Ordinary); 19209 return E; 19210 } 19211 19212 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19213 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19214 19215 E->setType(VD->getType()); 19216 19217 assert(E->isPRValue()); 19218 if (S.getLangOpts().CPlusPlus && 19219 !(isa<CXXMethodDecl>(VD) && 19220 cast<CXXMethodDecl>(VD)->isInstance())) 19221 E->setValueKind(VK_LValue); 19222 19223 return E; 19224 } 19225 19226 ExprResult VisitMemberExpr(MemberExpr *E) { 19227 return resolveDecl(E, E->getMemberDecl()); 19228 } 19229 19230 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19231 return resolveDecl(E, E->getDecl()); 19232 } 19233 }; 19234 } 19235 19236 /// Given a function expression of unknown-any type, try to rebuild it 19237 /// to have a function type. 19238 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19239 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19240 if (Result.isInvalid()) return ExprError(); 19241 return S.DefaultFunctionArrayConversion(Result.get()); 19242 } 19243 19244 namespace { 19245 /// A visitor for rebuilding an expression of type __unknown_anytype 19246 /// into one which resolves the type directly on the referring 19247 /// expression. Strict preservation of the original source 19248 /// structure is not a goal. 19249 struct RebuildUnknownAnyExpr 19250 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19251 19252 Sema &S; 19253 19254 /// The current destination type. 19255 QualType DestType; 19256 19257 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19258 : S(S), DestType(CastType) {} 19259 19260 ExprResult VisitStmt(Stmt *S) { 19261 llvm_unreachable("unexpected statement!"); 19262 } 19263 19264 ExprResult VisitExpr(Expr *E) { 19265 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19266 << E->getSourceRange(); 19267 return ExprError(); 19268 } 19269 19270 ExprResult VisitCallExpr(CallExpr *E); 19271 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 19272 19273 /// Rebuild an expression which simply semantically wraps another 19274 /// expression which it shares the type and value kind of. 19275 template <class T> ExprResult rebuildSugarExpr(T *E) { 19276 ExprResult SubResult = Visit(E->getSubExpr()); 19277 if (SubResult.isInvalid()) return ExprError(); 19278 Expr *SubExpr = SubResult.get(); 19279 E->setSubExpr(SubExpr); 19280 E->setType(SubExpr->getType()); 19281 E->setValueKind(SubExpr->getValueKind()); 19282 assert(E->getObjectKind() == OK_Ordinary); 19283 return E; 19284 } 19285 19286 ExprResult VisitParenExpr(ParenExpr *E) { 19287 return rebuildSugarExpr(E); 19288 } 19289 19290 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19291 return rebuildSugarExpr(E); 19292 } 19293 19294 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19295 const PointerType *Ptr = DestType->getAs<PointerType>(); 19296 if (!Ptr) { 19297 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19298 << E->getSourceRange(); 19299 return ExprError(); 19300 } 19301 19302 if (isa<CallExpr>(E->getSubExpr())) { 19303 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19304 << E->getSourceRange(); 19305 return ExprError(); 19306 } 19307 19308 assert(E->isPRValue()); 19309 assert(E->getObjectKind() == OK_Ordinary); 19310 E->setType(DestType); 19311 19312 // Build the sub-expression as if it were an object of the pointee type. 19313 DestType = Ptr->getPointeeType(); 19314 ExprResult SubResult = Visit(E->getSubExpr()); 19315 if (SubResult.isInvalid()) return ExprError(); 19316 E->setSubExpr(SubResult.get()); 19317 return E; 19318 } 19319 19320 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19321 19322 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19323 19324 ExprResult VisitMemberExpr(MemberExpr *E) { 19325 return resolveDecl(E, E->getMemberDecl()); 19326 } 19327 19328 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19329 return resolveDecl(E, E->getDecl()); 19330 } 19331 }; 19332 } 19333 19334 /// Rebuilds a call expression which yielded __unknown_anytype. 19335 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19336 Expr *CalleeExpr = E->getCallee(); 19337 19338 enum FnKind { 19339 FK_MemberFunction, 19340 FK_FunctionPointer, 19341 FK_BlockPointer 19342 }; 19343 19344 FnKind Kind; 19345 QualType CalleeType = CalleeExpr->getType(); 19346 if (CalleeType == S.Context.BoundMemberTy) { 19347 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19348 Kind = FK_MemberFunction; 19349 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19350 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19351 CalleeType = Ptr->getPointeeType(); 19352 Kind = FK_FunctionPointer; 19353 } else { 19354 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19355 Kind = FK_BlockPointer; 19356 } 19357 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19358 19359 // Verify that this is a legal result type of a function. 19360 if (DestType->isArrayType() || DestType->isFunctionType()) { 19361 unsigned diagID = diag::err_func_returning_array_function; 19362 if (Kind == FK_BlockPointer) 19363 diagID = diag::err_block_returning_array_function; 19364 19365 S.Diag(E->getExprLoc(), diagID) 19366 << DestType->isFunctionType() << DestType; 19367 return ExprError(); 19368 } 19369 19370 // Otherwise, go ahead and set DestType as the call's result. 19371 E->setType(DestType.getNonLValueExprType(S.Context)); 19372 E->setValueKind(Expr::getValueKindForType(DestType)); 19373 assert(E->getObjectKind() == OK_Ordinary); 19374 19375 // Rebuild the function type, replacing the result type with DestType. 19376 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19377 if (Proto) { 19378 // __unknown_anytype(...) is a special case used by the debugger when 19379 // it has no idea what a function's signature is. 19380 // 19381 // We want to build this call essentially under the K&R 19382 // unprototyped rules, but making a FunctionNoProtoType in C++ 19383 // would foul up all sorts of assumptions. However, we cannot 19384 // simply pass all arguments as variadic arguments, nor can we 19385 // portably just call the function under a non-variadic type; see 19386 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19387 // However, it turns out that in practice it is generally safe to 19388 // call a function declared as "A foo(B,C,D);" under the prototype 19389 // "A foo(B,C,D,...);". The only known exception is with the 19390 // Windows ABI, where any variadic function is implicitly cdecl 19391 // regardless of its normal CC. Therefore we change the parameter 19392 // types to match the types of the arguments. 19393 // 19394 // This is a hack, but it is far superior to moving the 19395 // corresponding target-specific code from IR-gen to Sema/AST. 19396 19397 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19398 SmallVector<QualType, 8> ArgTypes; 19399 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19400 ArgTypes.reserve(E->getNumArgs()); 19401 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19402 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); 19403 } 19404 ParamTypes = ArgTypes; 19405 } 19406 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19407 Proto->getExtProtoInfo()); 19408 } else { 19409 DestType = S.Context.getFunctionNoProtoType(DestType, 19410 FnType->getExtInfo()); 19411 } 19412 19413 // Rebuild the appropriate pointer-to-function type. 19414 switch (Kind) { 19415 case FK_MemberFunction: 19416 // Nothing to do. 19417 break; 19418 19419 case FK_FunctionPointer: 19420 DestType = S.Context.getPointerType(DestType); 19421 break; 19422 19423 case FK_BlockPointer: 19424 DestType = S.Context.getBlockPointerType(DestType); 19425 break; 19426 } 19427 19428 // Finally, we can recurse. 19429 ExprResult CalleeResult = Visit(CalleeExpr); 19430 if (!CalleeResult.isUsable()) return ExprError(); 19431 E->setCallee(CalleeResult.get()); 19432 19433 // Bind a temporary if necessary. 19434 return S.MaybeBindToTemporary(E); 19435 } 19436 19437 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19438 // Verify that this is a legal result type of a call. 19439 if (DestType->isArrayType() || DestType->isFunctionType()) { 19440 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19441 << DestType->isFunctionType() << DestType; 19442 return ExprError(); 19443 } 19444 19445 // Rewrite the method result type if available. 19446 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19447 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19448 Method->setReturnType(DestType); 19449 } 19450 19451 // Change the type of the message. 19452 E->setType(DestType.getNonReferenceType()); 19453 E->setValueKind(Expr::getValueKindForType(DestType)); 19454 19455 return S.MaybeBindToTemporary(E); 19456 } 19457 19458 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19459 // The only case we should ever see here is a function-to-pointer decay. 19460 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19461 assert(E->isPRValue()); 19462 assert(E->getObjectKind() == OK_Ordinary); 19463 19464 E->setType(DestType); 19465 19466 // Rebuild the sub-expression as the pointee (function) type. 19467 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19468 19469 ExprResult Result = Visit(E->getSubExpr()); 19470 if (!Result.isUsable()) return ExprError(); 19471 19472 E->setSubExpr(Result.get()); 19473 return E; 19474 } else if (E->getCastKind() == CK_LValueToRValue) { 19475 assert(E->isPRValue()); 19476 assert(E->getObjectKind() == OK_Ordinary); 19477 19478 assert(isa<BlockPointerType>(E->getType())); 19479 19480 E->setType(DestType); 19481 19482 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19483 DestType = S.Context.getLValueReferenceType(DestType); 19484 19485 ExprResult Result = Visit(E->getSubExpr()); 19486 if (!Result.isUsable()) return ExprError(); 19487 19488 E->setSubExpr(Result.get()); 19489 return E; 19490 } else { 19491 llvm_unreachable("Unhandled cast type!"); 19492 } 19493 } 19494 19495 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19496 ExprValueKind ValueKind = VK_LValue; 19497 QualType Type = DestType; 19498 19499 // We know how to make this work for certain kinds of decls: 19500 19501 // - functions 19502 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19503 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19504 DestType = Ptr->getPointeeType(); 19505 ExprResult Result = resolveDecl(E, VD); 19506 if (Result.isInvalid()) return ExprError(); 19507 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 19508 VK_PRValue); 19509 } 19510 19511 if (!Type->isFunctionType()) { 19512 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19513 << VD << E->getSourceRange(); 19514 return ExprError(); 19515 } 19516 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19517 // We must match the FunctionDecl's type to the hack introduced in 19518 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19519 // type. See the lengthy commentary in that routine. 19520 QualType FDT = FD->getType(); 19521 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19522 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19523 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19524 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19525 SourceLocation Loc = FD->getLocation(); 19526 FunctionDecl *NewFD = FunctionDecl::Create( 19527 S.Context, FD->getDeclContext(), Loc, Loc, 19528 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19529 SC_None, S.getCurFPFeatures().isFPConstrained(), 19530 false /*isInlineSpecified*/, FD->hasPrototype(), 19531 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19532 19533 if (FD->getQualifier()) 19534 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19535 19536 SmallVector<ParmVarDecl*, 16> Params; 19537 for (const auto &AI : FT->param_types()) { 19538 ParmVarDecl *Param = 19539 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19540 Param->setScopeInfo(0, Params.size()); 19541 Params.push_back(Param); 19542 } 19543 NewFD->setParams(Params); 19544 DRE->setDecl(NewFD); 19545 VD = DRE->getDecl(); 19546 } 19547 } 19548 19549 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19550 if (MD->isInstance()) { 19551 ValueKind = VK_PRValue; 19552 Type = S.Context.BoundMemberTy; 19553 } 19554 19555 // Function references aren't l-values in C. 19556 if (!S.getLangOpts().CPlusPlus) 19557 ValueKind = VK_PRValue; 19558 19559 // - variables 19560 } else if (isa<VarDecl>(VD)) { 19561 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19562 Type = RefTy->getPointeeType(); 19563 } else if (Type->isFunctionType()) { 19564 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19565 << VD << E->getSourceRange(); 19566 return ExprError(); 19567 } 19568 19569 // - nothing else 19570 } else { 19571 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19572 << VD << E->getSourceRange(); 19573 return ExprError(); 19574 } 19575 19576 // Modifying the declaration like this is friendly to IR-gen but 19577 // also really dangerous. 19578 VD->setType(DestType); 19579 E->setType(Type); 19580 E->setValueKind(ValueKind); 19581 return E; 19582 } 19583 19584 /// Check a cast of an unknown-any type. We intentionally only 19585 /// trigger this for C-style casts. 19586 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19587 Expr *CastExpr, CastKind &CastKind, 19588 ExprValueKind &VK, CXXCastPath &Path) { 19589 // The type we're casting to must be either void or complete. 19590 if (!CastType->isVoidType() && 19591 RequireCompleteType(TypeRange.getBegin(), CastType, 19592 diag::err_typecheck_cast_to_incomplete)) 19593 return ExprError(); 19594 19595 // Rewrite the casted expression from scratch. 19596 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19597 if (!result.isUsable()) return ExprError(); 19598 19599 CastExpr = result.get(); 19600 VK = CastExpr->getValueKind(); 19601 CastKind = CK_NoOp; 19602 19603 return CastExpr; 19604 } 19605 19606 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19607 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19608 } 19609 19610 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19611 Expr *arg, QualType ¶mType) { 19612 // If the syntactic form of the argument is not an explicit cast of 19613 // any sort, just do default argument promotion. 19614 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19615 if (!castArg) { 19616 ExprResult result = DefaultArgumentPromotion(arg); 19617 if (result.isInvalid()) return ExprError(); 19618 paramType = result.get()->getType(); 19619 return result; 19620 } 19621 19622 // Otherwise, use the type that was written in the explicit cast. 19623 assert(!arg->hasPlaceholderType()); 19624 paramType = castArg->getTypeAsWritten(); 19625 19626 // Copy-initialize a parameter of that type. 19627 InitializedEntity entity = 19628 InitializedEntity::InitializeParameter(Context, paramType, 19629 /*consumed*/ false); 19630 return PerformCopyInitialization(entity, callLoc, arg); 19631 } 19632 19633 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19634 Expr *orig = E; 19635 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19636 while (true) { 19637 E = E->IgnoreParenImpCasts(); 19638 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19639 E = call->getCallee(); 19640 diagID = diag::err_uncasted_call_of_unknown_any; 19641 } else { 19642 break; 19643 } 19644 } 19645 19646 SourceLocation loc; 19647 NamedDecl *d; 19648 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19649 loc = ref->getLocation(); 19650 d = ref->getDecl(); 19651 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19652 loc = mem->getMemberLoc(); 19653 d = mem->getMemberDecl(); 19654 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19655 diagID = diag::err_uncasted_call_of_unknown_any; 19656 loc = msg->getSelectorStartLoc(); 19657 d = msg->getMethodDecl(); 19658 if (!d) { 19659 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19660 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19661 << orig->getSourceRange(); 19662 return ExprError(); 19663 } 19664 } else { 19665 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19666 << E->getSourceRange(); 19667 return ExprError(); 19668 } 19669 19670 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19671 19672 // Never recoverable. 19673 return ExprError(); 19674 } 19675 19676 /// Check for operands with placeholder types and complain if found. 19677 /// Returns ExprError() if there was an error and no recovery was possible. 19678 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19679 if (!Context.isDependenceAllowed()) { 19680 // C cannot handle TypoExpr nodes on either side of a binop because it 19681 // doesn't handle dependent types properly, so make sure any TypoExprs have 19682 // been dealt with before checking the operands. 19683 ExprResult Result = CorrectDelayedTyposInExpr(E); 19684 if (!Result.isUsable()) return ExprError(); 19685 E = Result.get(); 19686 } 19687 19688 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19689 if (!placeholderType) return E; 19690 19691 switch (placeholderType->getKind()) { 19692 19693 // Overloaded expressions. 19694 case BuiltinType::Overload: { 19695 // Try to resolve a single function template specialization. 19696 // This is obligatory. 19697 ExprResult Result = E; 19698 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19699 return Result; 19700 19701 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19702 // leaves Result unchanged on failure. 19703 Result = E; 19704 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19705 return Result; 19706 19707 // If that failed, try to recover with a call. 19708 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19709 /*complain*/ true); 19710 return Result; 19711 } 19712 19713 // Bound member functions. 19714 case BuiltinType::BoundMember: { 19715 ExprResult result = E; 19716 const Expr *BME = E->IgnoreParens(); 19717 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19718 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19719 if (isa<CXXPseudoDestructorExpr>(BME)) { 19720 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19721 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19722 if (ME->getMemberNameInfo().getName().getNameKind() == 19723 DeclarationName::CXXDestructorName) 19724 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19725 } 19726 tryToRecoverWithCall(result, PD, 19727 /*complain*/ true); 19728 return result; 19729 } 19730 19731 // ARC unbridged casts. 19732 case BuiltinType::ARCUnbridgedCast: { 19733 Expr *realCast = stripARCUnbridgedCast(E); 19734 diagnoseARCUnbridgedCast(realCast); 19735 return realCast; 19736 } 19737 19738 // Expressions of unknown type. 19739 case BuiltinType::UnknownAny: 19740 return diagnoseUnknownAnyExpr(*this, E); 19741 19742 // Pseudo-objects. 19743 case BuiltinType::PseudoObject: 19744 return checkPseudoObjectRValue(E); 19745 19746 case BuiltinType::BuiltinFn: { 19747 // Accept __noop without parens by implicitly converting it to a call expr. 19748 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19749 if (DRE) { 19750 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19751 if (FD->getBuiltinID() == Builtin::BI__noop) { 19752 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19753 CK_BuiltinFnToFnPtr) 19754 .get(); 19755 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19756 VK_PRValue, SourceLocation(), 19757 FPOptionsOverride()); 19758 } 19759 } 19760 19761 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19762 return ExprError(); 19763 } 19764 19765 case BuiltinType::IncompleteMatrixIdx: 19766 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19767 ->getRowIdx() 19768 ->getBeginLoc(), 19769 diag::err_matrix_incomplete_index); 19770 return ExprError(); 19771 19772 // Expressions of unknown type. 19773 case BuiltinType::OMPArraySection: 19774 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19775 return ExprError(); 19776 19777 // Expressions of unknown type. 19778 case BuiltinType::OMPArrayShaping: 19779 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19780 19781 case BuiltinType::OMPIterator: 19782 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19783 19784 // Everything else should be impossible. 19785 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19786 case BuiltinType::Id: 19787 #include "clang/Basic/OpenCLImageTypes.def" 19788 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19789 case BuiltinType::Id: 19790 #include "clang/Basic/OpenCLExtensionTypes.def" 19791 #define SVE_TYPE(Name, Id, SingletonId) \ 19792 case BuiltinType::Id: 19793 #include "clang/Basic/AArch64SVEACLETypes.def" 19794 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19795 case BuiltinType::Id: 19796 #include "clang/Basic/PPCTypes.def" 19797 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19798 #include "clang/Basic/RISCVVTypes.def" 19799 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19800 #define PLACEHOLDER_TYPE(Id, SingletonId) 19801 #include "clang/AST/BuiltinTypes.def" 19802 break; 19803 } 19804 19805 llvm_unreachable("invalid placeholder type!"); 19806 } 19807 19808 bool Sema::CheckCaseExpression(Expr *E) { 19809 if (E->isTypeDependent()) 19810 return true; 19811 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19812 return E->getType()->isIntegralOrEnumerationType(); 19813 return false; 19814 } 19815 19816 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19817 ExprResult 19818 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19819 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19820 "Unknown Objective-C Boolean value!"); 19821 QualType BoolT = Context.ObjCBuiltinBoolTy; 19822 if (!Context.getBOOLDecl()) { 19823 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19824 Sema::LookupOrdinaryName); 19825 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19826 NamedDecl *ND = Result.getFoundDecl(); 19827 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19828 Context.setBOOLDecl(TD); 19829 } 19830 } 19831 if (Context.getBOOLDecl()) 19832 BoolT = Context.getBOOLType(); 19833 return new (Context) 19834 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19835 } 19836 19837 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19838 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19839 SourceLocation RParen) { 19840 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { 19841 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19842 return Spec.getPlatform() == Platform; 19843 }); 19844 // Transcribe the "ios" availability check to "maccatalyst" when compiling 19845 // for "maccatalyst" if "maccatalyst" is not specified. 19846 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { 19847 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19848 return Spec.getPlatform() == "ios"; 19849 }); 19850 } 19851 if (Spec == AvailSpecs.end()) 19852 return None; 19853 return Spec->getVersion(); 19854 }; 19855 19856 VersionTuple Version; 19857 if (auto MaybeVersion = 19858 FindSpecVersion(Context.getTargetInfo().getPlatformName())) 19859 Version = *MaybeVersion; 19860 19861 // The use of `@available` in the enclosing context should be analyzed to 19862 // warn when it's used inappropriately (i.e. not if(@available)). 19863 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 19864 Context->HasPotentialAvailabilityViolations = true; 19865 19866 return new (Context) 19867 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19868 } 19869 19870 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19871 ArrayRef<Expr *> SubExprs, QualType T) { 19872 if (!Context.getLangOpts().RecoveryAST) 19873 return ExprError(); 19874 19875 if (isSFINAEContext()) 19876 return ExprError(); 19877 19878 if (T.isNull() || T->isUndeducedType() || 19879 !Context.getLangOpts().RecoveryASTType) 19880 // We don't know the concrete type, fallback to dependent type. 19881 T = Context.DependentTy; 19882 19883 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19884 } 19885