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/DiagnosticSema.h" 32 #include "clang/Basic/PartialDiagnostic.h" 33 #include "clang/Basic/SourceManager.h" 34 #include "clang/Basic/TargetInfo.h" 35 #include "clang/Lex/LiteralSupport.h" 36 #include "clang/Lex/Preprocessor.h" 37 #include "clang/Sema/AnalysisBasedWarnings.h" 38 #include "clang/Sema/DeclSpec.h" 39 #include "clang/Sema/DelayedDiagnostic.h" 40 #include "clang/Sema/Designator.h" 41 #include "clang/Sema/Initialization.h" 42 #include "clang/Sema/Lookup.h" 43 #include "clang/Sema/Overload.h" 44 #include "clang/Sema/ParsedTemplate.h" 45 #include "clang/Sema/Scope.h" 46 #include "clang/Sema/ScopeInfo.h" 47 #include "clang/Sema/SemaFixItUtils.h" 48 #include "clang/Sema/SemaInternal.h" 49 #include "clang/Sema/Template.h" 50 #include "llvm/ADT/STLExtras.h" 51 #include "llvm/ADT/StringExtras.h" 52 #include "llvm/Support/ConvertUTF.h" 53 #include "llvm/Support/SaveAndRestore.h" 54 55 using namespace clang; 56 using namespace sema; 57 using llvm::RoundingMode; 58 59 /// Determine whether the use of this declaration is valid, without 60 /// emitting diagnostics. 61 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 62 // See if this is an auto-typed variable whose initializer we are parsing. 63 if (ParsingInitForAutoVars.count(D)) 64 return false; 65 66 // See if this is a deleted function. 67 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 68 if (FD->isDeleted()) 69 return false; 70 71 // If the function has a deduced return type, and we can't deduce it, 72 // then we can't use it either. 73 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 74 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 75 return false; 76 77 // See if this is an aligned allocation/deallocation function that is 78 // unavailable. 79 if (TreatUnavailableAsInvalid && 80 isUnavailableAlignedAllocationFunction(*FD)) 81 return false; 82 } 83 84 // See if this function is unavailable. 85 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 86 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 87 return false; 88 89 if (isa<UnresolvedUsingIfExistsDecl>(D)) 90 return false; 91 92 return true; 93 } 94 95 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 96 // Warn if this is used but marked unused. 97 if (const auto *A = D->getAttr<UnusedAttr>()) { 98 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 99 // should diagnose them. 100 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 101 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 102 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 103 if (DC && !DC->hasAttr<UnusedAttr>()) 104 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 105 } 106 } 107 } 108 109 /// Emit a note explaining that this function is deleted. 110 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 111 assert(Decl && Decl->isDeleted()); 112 113 if (Decl->isDefaulted()) { 114 // If the method was explicitly defaulted, point at that declaration. 115 if (!Decl->isImplicit()) 116 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 117 118 // Try to diagnose why this special member function was implicitly 119 // deleted. This might fail, if that reason no longer applies. 120 DiagnoseDeletedDefaultedFunction(Decl); 121 return; 122 } 123 124 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 125 if (Ctor && Ctor->isInheritingConstructor()) 126 return NoteDeletedInheritingConstructor(Ctor); 127 128 Diag(Decl->getLocation(), diag::note_availability_specified_here) 129 << Decl << 1; 130 } 131 132 /// Determine whether a FunctionDecl was ever declared with an 133 /// explicit storage class. 134 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 135 for (auto I : D->redecls()) { 136 if (I->getStorageClass() != SC_None) 137 return true; 138 } 139 return false; 140 } 141 142 /// Check whether we're in an extern inline function and referring to a 143 /// variable or function with internal linkage (C11 6.7.4p3). 144 /// 145 /// This is only a warning because we used to silently accept this code, but 146 /// in many cases it will not behave correctly. This is not enabled in C++ mode 147 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 148 /// and so while there may still be user mistakes, most of the time we can't 149 /// prove that there are errors. 150 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 151 const NamedDecl *D, 152 SourceLocation Loc) { 153 // This is disabled under C++; there are too many ways for this to fire in 154 // contexts where the warning is a false positive, or where it is technically 155 // correct but benign. 156 if (S.getLangOpts().CPlusPlus) 157 return; 158 159 // Check if this is an inlined function or method. 160 FunctionDecl *Current = S.getCurFunctionDecl(); 161 if (!Current) 162 return; 163 if (!Current->isInlined()) 164 return; 165 if (!Current->isExternallyVisible()) 166 return; 167 168 // Check if the decl has internal linkage. 169 if (D->getFormalLinkage() != InternalLinkage) 170 return; 171 172 // Downgrade from ExtWarn to Extension if 173 // (1) the supposedly external inline function is in the main file, 174 // and probably won't be included anywhere else. 175 // (2) the thing we're referencing is a pure function. 176 // (3) the thing we're referencing is another inline function. 177 // This last can give us false negatives, but it's better than warning on 178 // wrappers for simple C library functions. 179 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 180 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 181 if (!DowngradeWarning && UsedFn) 182 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 183 184 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 185 : diag::ext_internal_in_extern_inline) 186 << /*IsVar=*/!UsedFn << D; 187 188 S.MaybeSuggestAddingStaticToDecl(Current); 189 190 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 191 << D; 192 } 193 194 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 195 const FunctionDecl *First = Cur->getFirstDecl(); 196 197 // Suggest "static" on the function, if possible. 198 if (!hasAnyExplicitStorageClass(First)) { 199 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 200 Diag(DeclBegin, diag::note_convert_inline_to_static) 201 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 202 } 203 } 204 205 /// Determine whether the use of this declaration is valid, and 206 /// emit any corresponding diagnostics. 207 /// 208 /// This routine diagnoses various problems with referencing 209 /// declarations that can occur when using a declaration. For example, 210 /// it might warn if a deprecated or unavailable declaration is being 211 /// used, or produce an error (and return true) if a C++0x deleted 212 /// function is being used. 213 /// 214 /// \returns true if there was an error (this declaration cannot be 215 /// referenced), false otherwise. 216 /// 217 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 218 const ObjCInterfaceDecl *UnknownObjCClass, 219 bool ObjCPropertyAccess, 220 bool AvoidPartialAvailabilityChecks, 221 ObjCInterfaceDecl *ClassReceiver) { 222 SourceLocation Loc = Locs.front(); 223 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 224 // If there were any diagnostics suppressed by template argument deduction, 225 // emit them now. 226 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 227 if (Pos != SuppressedDiagnostics.end()) { 228 for (const PartialDiagnosticAt &Suppressed : Pos->second) 229 Diag(Suppressed.first, Suppressed.second); 230 231 // Clear out the list of suppressed diagnostics, so that we don't emit 232 // them again for this specialization. However, we don't obsolete this 233 // entry from the table, because we want to avoid ever emitting these 234 // diagnostics again. 235 Pos->second.clear(); 236 } 237 238 // C++ [basic.start.main]p3: 239 // The function 'main' shall not be used within a program. 240 if (cast<FunctionDecl>(D)->isMain()) 241 Diag(Loc, diag::ext_main_used); 242 243 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 244 } 245 246 // See if this is an auto-typed variable whose initializer we are parsing. 247 if (ParsingInitForAutoVars.count(D)) { 248 if (isa<BindingDecl>(D)) { 249 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 250 << D->getDeclName(); 251 } else { 252 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 253 << D->getDeclName() << cast<VarDecl>(D)->getType(); 254 } 255 return true; 256 } 257 258 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 259 // See if this is a deleted function. 260 if (FD->isDeleted()) { 261 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 262 if (Ctor && Ctor->isInheritingConstructor()) 263 Diag(Loc, diag::err_deleted_inherited_ctor_use) 264 << Ctor->getParent() 265 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 266 else 267 Diag(Loc, diag::err_deleted_function_use); 268 NoteDeletedFunction(FD); 269 return true; 270 } 271 272 // [expr.prim.id]p4 273 // A program that refers explicitly or implicitly to a function with a 274 // trailing requires-clause whose constraint-expression is not satisfied, 275 // other than to declare it, is ill-formed. [...] 276 // 277 // See if this is a function with constraints that need to be satisfied. 278 // Check this before deducing the return type, as it might instantiate the 279 // definition. 280 if (FD->getTrailingRequiresClause()) { 281 ConstraintSatisfaction Satisfaction; 282 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 283 // A diagnostic will have already been generated (non-constant 284 // constraint expression, for example) 285 return true; 286 if (!Satisfaction.IsSatisfied) { 287 Diag(Loc, 288 diag::err_reference_to_function_with_unsatisfied_constraints) 289 << D; 290 DiagnoseUnsatisfiedConstraint(Satisfaction); 291 return true; 292 } 293 } 294 295 // If the function has a deduced return type, and we can't deduce it, 296 // then we can't use it either. 297 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 298 DeduceReturnType(FD, Loc)) 299 return true; 300 301 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 302 return true; 303 304 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 305 return true; 306 } 307 308 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 309 // Lambdas are only default-constructible or assignable in C++2a onwards. 310 if (MD->getParent()->isLambda() && 311 ((isa<CXXConstructorDecl>(MD) && 312 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 313 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 314 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 315 << !isa<CXXConstructorDecl>(MD); 316 } 317 } 318 319 auto getReferencedObjCProp = [](const NamedDecl *D) -> 320 const ObjCPropertyDecl * { 321 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 322 return MD->findPropertyDecl(); 323 return nullptr; 324 }; 325 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 326 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 327 return true; 328 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 329 return true; 330 } 331 332 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 333 // Only the variables omp_in and omp_out are allowed in the combiner. 334 // Only the variables omp_priv and omp_orig are allowed in the 335 // initializer-clause. 336 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 337 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 338 isa<VarDecl>(D)) { 339 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 340 << getCurFunction()->HasOMPDeclareReductionCombiner; 341 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 342 return true; 343 } 344 345 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 346 // List-items in map clauses on this construct may only refer to the declared 347 // variable var and entities that could be referenced by a procedure defined 348 // at the same location 349 if (LangOpts.OpenMP && isa<VarDecl>(D) && 350 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 351 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 352 << getOpenMPDeclareMapperVarName(); 353 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 354 return true; 355 } 356 357 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) { 358 Diag(Loc, diag::err_use_of_empty_using_if_exists); 359 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); 360 return true; 361 } 362 363 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 364 AvoidPartialAvailabilityChecks, ClassReceiver); 365 366 DiagnoseUnusedOfDecl(*this, D, Loc); 367 368 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 369 370 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 371 if (auto *VD = dyn_cast<ValueDecl>(D)) 372 checkDeviceDecl(VD, Loc); 373 374 if (!Context.getTargetInfo().isTLSSupported()) 375 if (const auto *VD = dyn_cast<VarDecl>(D)) 376 if (VD->getTLSKind() != VarDecl::TLS_None) 377 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 378 } 379 380 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 381 !isUnevaluatedContext()) { 382 // C++ [expr.prim.req.nested] p3 383 // A local parameter shall only appear as an unevaluated operand 384 // (Clause 8) within the constraint-expression. 385 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 386 << D; 387 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 388 return true; 389 } 390 391 return false; 392 } 393 394 /// DiagnoseSentinelCalls - This routine checks whether a call or 395 /// message-send is to a declaration with the sentinel attribute, and 396 /// if so, it checks that the requirements of the sentinel are 397 /// satisfied. 398 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 399 ArrayRef<Expr *> Args) { 400 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 401 if (!attr) 402 return; 403 404 // The number of formal parameters of the declaration. 405 unsigned numFormalParams; 406 407 // The kind of declaration. This is also an index into a %select in 408 // the diagnostic. 409 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 410 411 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 412 numFormalParams = MD->param_size(); 413 calleeType = CT_Method; 414 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 415 numFormalParams = FD->param_size(); 416 calleeType = CT_Function; 417 } else if (isa<VarDecl>(D)) { 418 QualType type = cast<ValueDecl>(D)->getType(); 419 const FunctionType *fn = nullptr; 420 if (const PointerType *ptr = type->getAs<PointerType>()) { 421 fn = ptr->getPointeeType()->getAs<FunctionType>(); 422 if (!fn) return; 423 calleeType = CT_Function; 424 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 425 fn = ptr->getPointeeType()->castAs<FunctionType>(); 426 calleeType = CT_Block; 427 } else { 428 return; 429 } 430 431 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 432 numFormalParams = proto->getNumParams(); 433 } else { 434 numFormalParams = 0; 435 } 436 } else { 437 return; 438 } 439 440 // "nullPos" is the number of formal parameters at the end which 441 // effectively count as part of the variadic arguments. This is 442 // useful if you would prefer to not have *any* formal parameters, 443 // but the language forces you to have at least one. 444 unsigned nullPos = attr->getNullPos(); 445 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 446 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 447 448 // The number of arguments which should follow the sentinel. 449 unsigned numArgsAfterSentinel = attr->getSentinel(); 450 451 // If there aren't enough arguments for all the formal parameters, 452 // the sentinel, and the args after the sentinel, complain. 453 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 454 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 455 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 456 return; 457 } 458 459 // Otherwise, find the sentinel expression. 460 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 461 if (!sentinelExpr) return; 462 if (sentinelExpr->isValueDependent()) return; 463 if (Context.isSentinelNullExpr(sentinelExpr)) return; 464 465 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 466 // or 'NULL' if those are actually defined in the context. Only use 467 // 'nil' for ObjC methods, where it's much more likely that the 468 // variadic arguments form a list of object pointers. 469 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 470 std::string NullValue; 471 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 472 NullValue = "nil"; 473 else if (getLangOpts().CPlusPlus11) 474 NullValue = "nullptr"; 475 else if (PP.isMacroDefined("NULL")) 476 NullValue = "NULL"; 477 else 478 NullValue = "(void*) 0"; 479 480 if (MissingNilLoc.isInvalid()) 481 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 482 else 483 Diag(MissingNilLoc, diag::warn_missing_sentinel) 484 << int(calleeType) 485 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 486 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 487 } 488 489 SourceRange Sema::getExprRange(Expr *E) const { 490 return E ? E->getSourceRange() : SourceRange(); 491 } 492 493 //===----------------------------------------------------------------------===// 494 // Standard Promotions and Conversions 495 //===----------------------------------------------------------------------===// 496 497 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 498 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 499 // Handle any placeholder expressions which made it here. 500 if (E->getType()->isPlaceholderType()) { 501 ExprResult result = CheckPlaceholderExpr(E); 502 if (result.isInvalid()) return ExprError(); 503 E = result.get(); 504 } 505 506 QualType Ty = E->getType(); 507 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 508 509 if (Ty->isFunctionType()) { 510 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 511 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 512 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 513 return ExprError(); 514 515 E = ImpCastExprToType(E, Context.getPointerType(Ty), 516 CK_FunctionToPointerDecay).get(); 517 } else if (Ty->isArrayType()) { 518 // In C90 mode, arrays only promote to pointers if the array expression is 519 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 520 // type 'array of type' is converted to an expression that has type 'pointer 521 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 522 // that has type 'array of type' ...". The relevant change is "an lvalue" 523 // (C90) to "an expression" (C99). 524 // 525 // C++ 4.2p1: 526 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 527 // T" can be converted to an rvalue of type "pointer to T". 528 // 529 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { 530 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 531 CK_ArrayToPointerDecay); 532 if (Res.isInvalid()) 533 return ExprError(); 534 E = Res.get(); 535 } 536 } 537 return E; 538 } 539 540 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 541 // Check to see if we are dereferencing a null pointer. If so, 542 // and if not volatile-qualified, this is undefined behavior that the 543 // optimizer will delete, so warn about it. People sometimes try to use this 544 // to get a deterministic trap and are surprised by clang's behavior. This 545 // only handles the pattern "*null", which is a very syntactic check. 546 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 547 if (UO && UO->getOpcode() == UO_Deref && 548 UO->getSubExpr()->getType()->isPointerType()) { 549 const LangAS AS = 550 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 551 if ((!isTargetAddressSpace(AS) || 552 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 553 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 554 S.Context, Expr::NPC_ValueDependentIsNotNull) && 555 !UO->getType().isVolatileQualified()) { 556 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 557 S.PDiag(diag::warn_indirection_through_null) 558 << UO->getSubExpr()->getSourceRange()); 559 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 560 S.PDiag(diag::note_indirection_through_null)); 561 } 562 } 563 } 564 565 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 566 SourceLocation AssignLoc, 567 const Expr* RHS) { 568 const ObjCIvarDecl *IV = OIRE->getDecl(); 569 if (!IV) 570 return; 571 572 DeclarationName MemberName = IV->getDeclName(); 573 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 574 if (!Member || !Member->isStr("isa")) 575 return; 576 577 const Expr *Base = OIRE->getBase(); 578 QualType BaseType = Base->getType(); 579 if (OIRE->isArrow()) 580 BaseType = BaseType->getPointeeType(); 581 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 582 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 583 ObjCInterfaceDecl *ClassDeclared = nullptr; 584 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 585 if (!ClassDeclared->getSuperClass() 586 && (*ClassDeclared->ivar_begin()) == IV) { 587 if (RHS) { 588 NamedDecl *ObjectSetClass = 589 S.LookupSingleName(S.TUScope, 590 &S.Context.Idents.get("object_setClass"), 591 SourceLocation(), S.LookupOrdinaryName); 592 if (ObjectSetClass) { 593 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 594 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 595 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 596 "object_setClass(") 597 << FixItHint::CreateReplacement( 598 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 599 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 600 } 601 else 602 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 603 } else { 604 NamedDecl *ObjectGetClass = 605 S.LookupSingleName(S.TUScope, 606 &S.Context.Idents.get("object_getClass"), 607 SourceLocation(), S.LookupOrdinaryName); 608 if (ObjectGetClass) 609 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 610 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 611 "object_getClass(") 612 << FixItHint::CreateReplacement( 613 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 614 else 615 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 616 } 617 S.Diag(IV->getLocation(), diag::note_ivar_decl); 618 } 619 } 620 } 621 622 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 623 // Handle any placeholder expressions which made it here. 624 if (E->getType()->isPlaceholderType()) { 625 ExprResult result = CheckPlaceholderExpr(E); 626 if (result.isInvalid()) return ExprError(); 627 E = result.get(); 628 } 629 630 // C++ [conv.lval]p1: 631 // A glvalue of a non-function, non-array type T can be 632 // converted to a prvalue. 633 if (!E->isGLValue()) return E; 634 635 QualType T = E->getType(); 636 assert(!T.isNull() && "r-value conversion on typeless expression?"); 637 638 // lvalue-to-rvalue conversion cannot be applied to function or array types. 639 if (T->isFunctionType() || T->isArrayType()) 640 return E; 641 642 // We don't want to throw lvalue-to-rvalue casts on top of 643 // expressions of certain types in C++. 644 if (getLangOpts().CPlusPlus && 645 (E->getType() == Context.OverloadTy || 646 T->isDependentType() || 647 T->isRecordType())) 648 return E; 649 650 // The C standard is actually really unclear on this point, and 651 // DR106 tells us what the result should be but not why. It's 652 // generally best to say that void types just doesn't undergo 653 // lvalue-to-rvalue at all. Note that expressions of unqualified 654 // 'void' type are never l-values, but qualified void can be. 655 if (T->isVoidType()) 656 return E; 657 658 // OpenCL usually rejects direct accesses to values of 'half' type. 659 if (getLangOpts().OpenCL && 660 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 661 T->isHalfType()) { 662 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 663 << 0 << T; 664 return ExprError(); 665 } 666 667 CheckForNullPointerDereference(*this, E); 668 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 669 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 670 &Context.Idents.get("object_getClass"), 671 SourceLocation(), LookupOrdinaryName); 672 if (ObjectGetClass) 673 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 674 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 675 << FixItHint::CreateReplacement( 676 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 677 else 678 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 679 } 680 else if (const ObjCIvarRefExpr *OIRE = 681 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 682 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 683 684 // C++ [conv.lval]p1: 685 // [...] If T is a non-class type, the type of the prvalue is the 686 // cv-unqualified version of T. Otherwise, the type of the 687 // rvalue is T. 688 // 689 // C99 6.3.2.1p2: 690 // If the lvalue has qualified type, the value has the unqualified 691 // version of the type of the lvalue; otherwise, the value has the 692 // type of the lvalue. 693 if (T.hasQualifiers()) 694 T = T.getUnqualifiedType(); 695 696 // Under the MS ABI, lock down the inheritance model now. 697 if (T->isMemberPointerType() && 698 Context.getTargetInfo().getCXXABI().isMicrosoft()) 699 (void)isCompleteType(E->getExprLoc(), T); 700 701 ExprResult Res = CheckLValueToRValueConversionOperand(E); 702 if (Res.isInvalid()) 703 return Res; 704 E = Res.get(); 705 706 // Loading a __weak object implicitly retains the value, so we need a cleanup to 707 // balance that. 708 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 709 Cleanup.setExprNeedsCleanups(true); 710 711 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 712 Cleanup.setExprNeedsCleanups(true); 713 714 // C++ [conv.lval]p3: 715 // If T is cv std::nullptr_t, the result is a null pointer constant. 716 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 717 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, 718 CurFPFeatureOverrides()); 719 720 // C11 6.3.2.1p2: 721 // ... if the lvalue has atomic type, the value has the non-atomic version 722 // of the type of the lvalue ... 723 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 724 T = Atomic->getValueType().getUnqualifiedType(); 725 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 726 nullptr, VK_PRValue, FPOptionsOverride()); 727 } 728 729 return Res; 730 } 731 732 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 733 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 734 if (Res.isInvalid()) 735 return ExprError(); 736 Res = DefaultLvalueConversion(Res.get()); 737 if (Res.isInvalid()) 738 return ExprError(); 739 return Res; 740 } 741 742 /// CallExprUnaryConversions - a special case of an unary conversion 743 /// performed on a function designator of a call expression. 744 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 745 QualType Ty = E->getType(); 746 ExprResult Res = E; 747 // Only do implicit cast for a function type, but not for a pointer 748 // to function type. 749 if (Ty->isFunctionType()) { 750 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 751 CK_FunctionToPointerDecay); 752 if (Res.isInvalid()) 753 return ExprError(); 754 } 755 Res = DefaultLvalueConversion(Res.get()); 756 if (Res.isInvalid()) 757 return ExprError(); 758 return Res.get(); 759 } 760 761 /// UsualUnaryConversions - Performs various conversions that are common to most 762 /// operators (C99 6.3). The conversions of array and function types are 763 /// sometimes suppressed. For example, the array->pointer conversion doesn't 764 /// apply if the array is an argument to the sizeof or address (&) operators. 765 /// In these instances, this routine should *not* be called. 766 ExprResult Sema::UsualUnaryConversions(Expr *E) { 767 // First, convert to an r-value. 768 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 769 if (Res.isInvalid()) 770 return ExprError(); 771 E = Res.get(); 772 773 QualType Ty = E->getType(); 774 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 775 776 // Half FP have to be promoted to float unless it is natively supported 777 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 778 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 779 780 // Try to perform integral promotions if the object has a theoretically 781 // promotable type. 782 if (Ty->isIntegralOrUnscopedEnumerationType()) { 783 // C99 6.3.1.1p2: 784 // 785 // The following may be used in an expression wherever an int or 786 // unsigned int may be used: 787 // - an object or expression with an integer type whose integer 788 // conversion rank is less than or equal to the rank of int 789 // and unsigned int. 790 // - A bit-field of type _Bool, int, signed int, or unsigned int. 791 // 792 // If an int can represent all values of the original type, the 793 // value is converted to an int; otherwise, it is converted to an 794 // unsigned int. These are called the integer promotions. All 795 // other types are unchanged by the integer promotions. 796 797 QualType PTy = Context.isPromotableBitField(E); 798 if (!PTy.isNull()) { 799 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 800 return E; 801 } 802 if (Ty->isPromotableIntegerType()) { 803 QualType PT = Context.getPromotedIntegerType(Ty); 804 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 805 return E; 806 } 807 } 808 return E; 809 } 810 811 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 812 /// do not have a prototype. Arguments that have type float or __fp16 813 /// are promoted to double. All other argument types are converted by 814 /// UsualUnaryConversions(). 815 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 816 QualType Ty = E->getType(); 817 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 818 819 ExprResult Res = UsualUnaryConversions(E); 820 if (Res.isInvalid()) 821 return ExprError(); 822 E = Res.get(); 823 824 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 825 // promote to double. 826 // Note that default argument promotion applies only to float (and 827 // half/fp16); it does not apply to _Float16. 828 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 829 if (BTy && (BTy->getKind() == BuiltinType::Half || 830 BTy->getKind() == BuiltinType::Float)) { 831 if (getLangOpts().OpenCL && 832 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 833 if (BTy->getKind() == BuiltinType::Half) { 834 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 835 } 836 } else { 837 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 838 } 839 } 840 if (BTy && 841 getLangOpts().getExtendIntArgs() == 842 LangOptions::ExtendArgsKind::ExtendTo64 && 843 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && 844 Context.getTypeSizeInChars(BTy) < 845 Context.getTypeSizeInChars(Context.LongLongTy)) { 846 E = (Ty->isUnsignedIntegerType()) 847 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) 848 .get() 849 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); 850 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && 851 "Unexpected typesize for LongLongTy"); 852 } 853 854 // C++ performs lvalue-to-rvalue conversion as a default argument 855 // promotion, even on class types, but note: 856 // C++11 [conv.lval]p2: 857 // When an lvalue-to-rvalue conversion occurs in an unevaluated 858 // operand or a subexpression thereof the value contained in the 859 // referenced object is not accessed. Otherwise, if the glvalue 860 // has a class type, the conversion copy-initializes a temporary 861 // of type T from the glvalue and the result of the conversion 862 // is a prvalue for the temporary. 863 // FIXME: add some way to gate this entire thing for correctness in 864 // potentially potentially evaluated contexts. 865 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 866 ExprResult Temp = PerformCopyInitialization( 867 InitializedEntity::InitializeTemporary(E->getType()), 868 E->getExprLoc(), E); 869 if (Temp.isInvalid()) 870 return ExprError(); 871 E = Temp.get(); 872 } 873 874 return E; 875 } 876 877 /// Determine the degree of POD-ness for an expression. 878 /// Incomplete types are considered POD, since this check can be performed 879 /// when we're in an unevaluated context. 880 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 881 if (Ty->isIncompleteType()) { 882 // C++11 [expr.call]p7: 883 // After these conversions, if the argument does not have arithmetic, 884 // enumeration, pointer, pointer to member, or class type, the program 885 // is ill-formed. 886 // 887 // Since we've already performed array-to-pointer and function-to-pointer 888 // decay, the only such type in C++ is cv void. This also handles 889 // initializer lists as variadic arguments. 890 if (Ty->isVoidType()) 891 return VAK_Invalid; 892 893 if (Ty->isObjCObjectType()) 894 return VAK_Invalid; 895 return VAK_Valid; 896 } 897 898 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 899 return VAK_Invalid; 900 901 if (Ty.isCXX98PODType(Context)) 902 return VAK_Valid; 903 904 // C++11 [expr.call]p7: 905 // Passing a potentially-evaluated argument of class type (Clause 9) 906 // having a non-trivial copy constructor, a non-trivial move constructor, 907 // or a non-trivial destructor, with no corresponding parameter, 908 // is conditionally-supported with implementation-defined semantics. 909 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 910 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 911 if (!Record->hasNonTrivialCopyConstructor() && 912 !Record->hasNonTrivialMoveConstructor() && 913 !Record->hasNonTrivialDestructor()) 914 return VAK_ValidInCXX11; 915 916 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 917 return VAK_Valid; 918 919 if (Ty->isObjCObjectType()) 920 return VAK_Invalid; 921 922 if (getLangOpts().MSVCCompat) 923 return VAK_MSVCUndefined; 924 925 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 926 // permitted to reject them. We should consider doing so. 927 return VAK_Undefined; 928 } 929 930 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 931 // Don't allow one to pass an Objective-C interface to a vararg. 932 const QualType &Ty = E->getType(); 933 VarArgKind VAK = isValidVarArgType(Ty); 934 935 // Complain about passing non-POD types through varargs. 936 switch (VAK) { 937 case VAK_ValidInCXX11: 938 DiagRuntimeBehavior( 939 E->getBeginLoc(), nullptr, 940 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 941 LLVM_FALLTHROUGH; 942 case VAK_Valid: 943 if (Ty->isRecordType()) { 944 // This is unlikely to be what the user intended. If the class has a 945 // 'c_str' member function, the user probably meant to call that. 946 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 947 PDiag(diag::warn_pass_class_arg_to_vararg) 948 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 949 } 950 break; 951 952 case VAK_Undefined: 953 case VAK_MSVCUndefined: 954 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 955 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 956 << getLangOpts().CPlusPlus11 << Ty << CT); 957 break; 958 959 case VAK_Invalid: 960 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 961 Diag(E->getBeginLoc(), 962 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 963 << Ty << CT; 964 else if (Ty->isObjCObjectType()) 965 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 966 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 967 << Ty << CT); 968 else 969 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 970 << isa<InitListExpr>(E) << Ty << CT; 971 break; 972 } 973 } 974 975 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 976 /// will create a trap if the resulting type is not a POD type. 977 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 978 FunctionDecl *FDecl) { 979 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 980 // Strip the unbridged-cast placeholder expression off, if applicable. 981 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 982 (CT == VariadicMethod || 983 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 984 E = stripARCUnbridgedCast(E); 985 986 // Otherwise, do normal placeholder checking. 987 } else { 988 ExprResult ExprRes = CheckPlaceholderExpr(E); 989 if (ExprRes.isInvalid()) 990 return ExprError(); 991 E = ExprRes.get(); 992 } 993 } 994 995 ExprResult ExprRes = DefaultArgumentPromotion(E); 996 if (ExprRes.isInvalid()) 997 return ExprError(); 998 999 // Copy blocks to the heap. 1000 if (ExprRes.get()->getType()->isBlockPointerType()) 1001 maybeExtendBlockObject(ExprRes); 1002 1003 E = ExprRes.get(); 1004 1005 // Diagnostics regarding non-POD argument types are 1006 // emitted along with format string checking in Sema::CheckFunctionCall(). 1007 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 1008 // Turn this into a trap. 1009 CXXScopeSpec SS; 1010 SourceLocation TemplateKWLoc; 1011 UnqualifiedId Name; 1012 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1013 E->getBeginLoc()); 1014 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1015 /*HasTrailingLParen=*/true, 1016 /*IsAddressOfOperand=*/false); 1017 if (TrapFn.isInvalid()) 1018 return ExprError(); 1019 1020 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1021 None, E->getEndLoc()); 1022 if (Call.isInvalid()) 1023 return ExprError(); 1024 1025 ExprResult Comma = 1026 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1027 if (Comma.isInvalid()) 1028 return ExprError(); 1029 return Comma.get(); 1030 } 1031 1032 if (!getLangOpts().CPlusPlus && 1033 RequireCompleteType(E->getExprLoc(), E->getType(), 1034 diag::err_call_incomplete_argument)) 1035 return ExprError(); 1036 1037 return E; 1038 } 1039 1040 /// Converts an integer to complex float type. Helper function of 1041 /// UsualArithmeticConversions() 1042 /// 1043 /// \return false if the integer expression is an integer type and is 1044 /// successfully converted to the complex type. 1045 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1046 ExprResult &ComplexExpr, 1047 QualType IntTy, 1048 QualType ComplexTy, 1049 bool SkipCast) { 1050 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1051 if (SkipCast) return false; 1052 if (IntTy->isIntegerType()) { 1053 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1054 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1055 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1056 CK_FloatingRealToComplex); 1057 } else { 1058 assert(IntTy->isComplexIntegerType()); 1059 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1060 CK_IntegralComplexToFloatingComplex); 1061 } 1062 return false; 1063 } 1064 1065 /// Handle arithmetic conversion with complex types. Helper function of 1066 /// UsualArithmeticConversions() 1067 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1068 ExprResult &RHS, QualType LHSType, 1069 QualType RHSType, 1070 bool IsCompAssign) { 1071 // if we have an integer operand, the result is the complex type. 1072 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1073 /*skipCast*/false)) 1074 return LHSType; 1075 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1076 /*skipCast*/IsCompAssign)) 1077 return RHSType; 1078 1079 // This handles complex/complex, complex/float, or float/complex. 1080 // When both operands are complex, the shorter operand is converted to the 1081 // type of the longer, and that is the type of the result. This corresponds 1082 // to what is done when combining two real floating-point operands. 1083 // The fun begins when size promotion occur across type domains. 1084 // From H&S 6.3.4: When one operand is complex and the other is a real 1085 // floating-point type, the less precise type is converted, within it's 1086 // real or complex domain, to the precision of the other type. For example, 1087 // when combining a "long double" with a "double _Complex", the 1088 // "double _Complex" is promoted to "long double _Complex". 1089 1090 // Compute the rank of the two types, regardless of whether they are complex. 1091 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1092 1093 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1094 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1095 QualType LHSElementType = 1096 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1097 QualType RHSElementType = 1098 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1099 1100 QualType ResultType = S.Context.getComplexType(LHSElementType); 1101 if (Order < 0) { 1102 // Promote the precision of the LHS if not an assignment. 1103 ResultType = S.Context.getComplexType(RHSElementType); 1104 if (!IsCompAssign) { 1105 if (LHSComplexType) 1106 LHS = 1107 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1108 else 1109 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1110 } 1111 } else if (Order > 0) { 1112 // Promote the precision of the RHS. 1113 if (RHSComplexType) 1114 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1115 else 1116 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1117 } 1118 return ResultType; 1119 } 1120 1121 /// Handle arithmetic conversion from integer to float. Helper function 1122 /// of UsualArithmeticConversions() 1123 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1124 ExprResult &IntExpr, 1125 QualType FloatTy, QualType IntTy, 1126 bool ConvertFloat, bool ConvertInt) { 1127 if (IntTy->isIntegerType()) { 1128 if (ConvertInt) 1129 // Convert intExpr to the lhs floating point type. 1130 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1131 CK_IntegralToFloating); 1132 return FloatTy; 1133 } 1134 1135 // Convert both sides to the appropriate complex float. 1136 assert(IntTy->isComplexIntegerType()); 1137 QualType result = S.Context.getComplexType(FloatTy); 1138 1139 // _Complex int -> _Complex float 1140 if (ConvertInt) 1141 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1142 CK_IntegralComplexToFloatingComplex); 1143 1144 // float -> _Complex float 1145 if (ConvertFloat) 1146 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1147 CK_FloatingRealToComplex); 1148 1149 return result; 1150 } 1151 1152 /// Handle arithmethic conversion with floating point types. Helper 1153 /// function of UsualArithmeticConversions() 1154 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1155 ExprResult &RHS, QualType LHSType, 1156 QualType RHSType, bool IsCompAssign) { 1157 bool LHSFloat = LHSType->isRealFloatingType(); 1158 bool RHSFloat = RHSType->isRealFloatingType(); 1159 1160 // N1169 4.1.4: If one of the operands has a floating type and the other 1161 // operand has a fixed-point type, the fixed-point operand 1162 // is converted to the floating type [...] 1163 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1164 if (LHSFloat) 1165 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1166 else if (!IsCompAssign) 1167 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1168 return LHSFloat ? LHSType : RHSType; 1169 } 1170 1171 // If we have two real floating types, convert the smaller operand 1172 // to the bigger result. 1173 if (LHSFloat && RHSFloat) { 1174 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1175 if (order > 0) { 1176 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1177 return LHSType; 1178 } 1179 1180 assert(order < 0 && "illegal float comparison"); 1181 if (!IsCompAssign) 1182 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1183 return RHSType; 1184 } 1185 1186 if (LHSFloat) { 1187 // Half FP has to be promoted to float unless it is natively supported 1188 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1189 LHSType = S.Context.FloatTy; 1190 1191 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1192 /*ConvertFloat=*/!IsCompAssign, 1193 /*ConvertInt=*/ true); 1194 } 1195 assert(RHSFloat); 1196 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1197 /*ConvertFloat=*/ true, 1198 /*ConvertInt=*/!IsCompAssign); 1199 } 1200 1201 /// Diagnose attempts to convert between __float128, __ibm128 and 1202 /// long double if there is no support for such conversion. 1203 /// Helper function of UsualArithmeticConversions(). 1204 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1205 QualType RHSType) { 1206 // No issue if either is not a floating point type. 1207 if (!LHSType->isFloatingType() || !RHSType->isFloatingType()) 1208 return false; 1209 1210 // No issue if both have the same 128-bit float semantics. 1211 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1212 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1213 1214 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType; 1215 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType; 1216 1217 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem); 1218 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem); 1219 1220 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() || 1221 &RHSSem != &llvm::APFloat::IEEEquad()) && 1222 (&LHSSem != &llvm::APFloat::IEEEquad() || 1223 &RHSSem != &llvm::APFloat::PPCDoubleDouble())) 1224 return false; 1225 1226 return true; 1227 } 1228 1229 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1230 1231 namespace { 1232 /// These helper callbacks are placed in an anonymous namespace to 1233 /// permit their use as function template parameters. 1234 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1235 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1236 } 1237 1238 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1239 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1240 CK_IntegralComplexCast); 1241 } 1242 } 1243 1244 /// Handle integer arithmetic conversions. Helper function of 1245 /// UsualArithmeticConversions() 1246 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1247 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1248 ExprResult &RHS, QualType LHSType, 1249 QualType RHSType, bool IsCompAssign) { 1250 // The rules for this case are in C99 6.3.1.8 1251 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1252 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1253 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1254 if (LHSSigned == RHSSigned) { 1255 // Same signedness; use the higher-ranked type 1256 if (order >= 0) { 1257 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1258 return LHSType; 1259 } else if (!IsCompAssign) 1260 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1261 return RHSType; 1262 } else if (order != (LHSSigned ? 1 : -1)) { 1263 // The unsigned type has greater than or equal rank to the 1264 // signed type, so use the unsigned type 1265 if (RHSSigned) { 1266 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1267 return LHSType; 1268 } else if (!IsCompAssign) 1269 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1270 return RHSType; 1271 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1272 // The two types are different widths; if we are here, that 1273 // means the signed type is larger than the unsigned type, so 1274 // use the signed type. 1275 if (LHSSigned) { 1276 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1277 return LHSType; 1278 } else if (!IsCompAssign) 1279 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1280 return RHSType; 1281 } else { 1282 // The signed type is higher-ranked than the unsigned type, 1283 // but isn't actually any bigger (like unsigned int and long 1284 // on most 32-bit systems). Use the unsigned type corresponding 1285 // to the signed type. 1286 QualType result = 1287 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1288 RHS = (*doRHSCast)(S, RHS.get(), result); 1289 if (!IsCompAssign) 1290 LHS = (*doLHSCast)(S, LHS.get(), result); 1291 return result; 1292 } 1293 } 1294 1295 /// Handle conversions with GCC complex int extension. Helper function 1296 /// of UsualArithmeticConversions() 1297 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1298 ExprResult &RHS, QualType LHSType, 1299 QualType RHSType, 1300 bool IsCompAssign) { 1301 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1302 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1303 1304 if (LHSComplexInt && RHSComplexInt) { 1305 QualType LHSEltType = LHSComplexInt->getElementType(); 1306 QualType RHSEltType = RHSComplexInt->getElementType(); 1307 QualType ScalarType = 1308 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1309 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1310 1311 return S.Context.getComplexType(ScalarType); 1312 } 1313 1314 if (LHSComplexInt) { 1315 QualType LHSEltType = LHSComplexInt->getElementType(); 1316 QualType ScalarType = 1317 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1318 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1319 QualType ComplexType = S.Context.getComplexType(ScalarType); 1320 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1321 CK_IntegralRealToComplex); 1322 1323 return ComplexType; 1324 } 1325 1326 assert(RHSComplexInt); 1327 1328 QualType RHSEltType = RHSComplexInt->getElementType(); 1329 QualType ScalarType = 1330 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1331 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1332 QualType ComplexType = S.Context.getComplexType(ScalarType); 1333 1334 if (!IsCompAssign) 1335 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1336 CK_IntegralRealToComplex); 1337 return ComplexType; 1338 } 1339 1340 /// Return the rank of a given fixed point or integer type. The value itself 1341 /// doesn't matter, but the values must be increasing with proper increasing 1342 /// rank as described in N1169 4.1.1. 1343 static unsigned GetFixedPointRank(QualType Ty) { 1344 const auto *BTy = Ty->getAs<BuiltinType>(); 1345 assert(BTy && "Expected a builtin type."); 1346 1347 switch (BTy->getKind()) { 1348 case BuiltinType::ShortFract: 1349 case BuiltinType::UShortFract: 1350 case BuiltinType::SatShortFract: 1351 case BuiltinType::SatUShortFract: 1352 return 1; 1353 case BuiltinType::Fract: 1354 case BuiltinType::UFract: 1355 case BuiltinType::SatFract: 1356 case BuiltinType::SatUFract: 1357 return 2; 1358 case BuiltinType::LongFract: 1359 case BuiltinType::ULongFract: 1360 case BuiltinType::SatLongFract: 1361 case BuiltinType::SatULongFract: 1362 return 3; 1363 case BuiltinType::ShortAccum: 1364 case BuiltinType::UShortAccum: 1365 case BuiltinType::SatShortAccum: 1366 case BuiltinType::SatUShortAccum: 1367 return 4; 1368 case BuiltinType::Accum: 1369 case BuiltinType::UAccum: 1370 case BuiltinType::SatAccum: 1371 case BuiltinType::SatUAccum: 1372 return 5; 1373 case BuiltinType::LongAccum: 1374 case BuiltinType::ULongAccum: 1375 case BuiltinType::SatLongAccum: 1376 case BuiltinType::SatULongAccum: 1377 return 6; 1378 default: 1379 if (BTy->isInteger()) 1380 return 0; 1381 llvm_unreachable("Unexpected fixed point or integer type"); 1382 } 1383 } 1384 1385 /// handleFixedPointConversion - Fixed point operations between fixed 1386 /// point types and integers or other fixed point types do not fall under 1387 /// usual arithmetic conversion since these conversions could result in loss 1388 /// of precsision (N1169 4.1.4). These operations should be calculated with 1389 /// the full precision of their result type (N1169 4.1.6.2.1). 1390 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1391 QualType RHSTy) { 1392 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1393 "Expected at least one of the operands to be a fixed point type"); 1394 assert((LHSTy->isFixedPointOrIntegerType() || 1395 RHSTy->isFixedPointOrIntegerType()) && 1396 "Special fixed point arithmetic operation conversions are only " 1397 "applied to ints or other fixed point types"); 1398 1399 // If one operand has signed fixed-point type and the other operand has 1400 // unsigned fixed-point type, then the unsigned fixed-point operand is 1401 // converted to its corresponding signed fixed-point type and the resulting 1402 // type is the type of the converted operand. 1403 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1404 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1405 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1406 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1407 1408 // The result type is the type with the highest rank, whereby a fixed-point 1409 // conversion rank is always greater than an integer conversion rank; if the 1410 // type of either of the operands is a saturating fixedpoint type, the result 1411 // type shall be the saturating fixed-point type corresponding to the type 1412 // with the highest rank; the resulting value is converted (taking into 1413 // account rounding and overflow) to the precision of the resulting type. 1414 // Same ranks between signed and unsigned types are resolved earlier, so both 1415 // types are either signed or both unsigned at this point. 1416 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1417 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1418 1419 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1420 1421 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1422 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1423 1424 return ResultTy; 1425 } 1426 1427 /// Check that the usual arithmetic conversions can be performed on this pair of 1428 /// expressions that might be of enumeration type. 1429 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1430 SourceLocation Loc, 1431 Sema::ArithConvKind ACK) { 1432 // C++2a [expr.arith.conv]p1: 1433 // If one operand is of enumeration type and the other operand is of a 1434 // different enumeration type or a floating-point type, this behavior is 1435 // deprecated ([depr.arith.conv.enum]). 1436 // 1437 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1438 // Eventually we will presumably reject these cases (in C++23 onwards?). 1439 QualType L = LHS->getType(), R = RHS->getType(); 1440 bool LEnum = L->isUnscopedEnumerationType(), 1441 REnum = R->isUnscopedEnumerationType(); 1442 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1443 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1444 (REnum && L->isFloatingType())) { 1445 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1446 ? diag::warn_arith_conv_enum_float_cxx20 1447 : diag::warn_arith_conv_enum_float) 1448 << LHS->getSourceRange() << RHS->getSourceRange() 1449 << (int)ACK << LEnum << L << R; 1450 } else if (!IsCompAssign && LEnum && REnum && 1451 !S.Context.hasSameUnqualifiedType(L, R)) { 1452 unsigned DiagID; 1453 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1454 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1455 // If either enumeration type is unnamed, it's less likely that the 1456 // user cares about this, but this situation is still deprecated in 1457 // C++2a. Use a different warning group. 1458 DiagID = S.getLangOpts().CPlusPlus20 1459 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1460 : diag::warn_arith_conv_mixed_anon_enum_types; 1461 } else if (ACK == Sema::ACK_Conditional) { 1462 // Conditional expressions are separated out because they have 1463 // historically had a different warning flag. 1464 DiagID = S.getLangOpts().CPlusPlus20 1465 ? diag::warn_conditional_mixed_enum_types_cxx20 1466 : diag::warn_conditional_mixed_enum_types; 1467 } else if (ACK == Sema::ACK_Comparison) { 1468 // Comparison expressions are separated out because they have 1469 // historically had a different warning flag. 1470 DiagID = S.getLangOpts().CPlusPlus20 1471 ? diag::warn_comparison_mixed_enum_types_cxx20 1472 : diag::warn_comparison_mixed_enum_types; 1473 } else { 1474 DiagID = S.getLangOpts().CPlusPlus20 1475 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1476 : diag::warn_arith_conv_mixed_enum_types; 1477 } 1478 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1479 << (int)ACK << L << R; 1480 } 1481 } 1482 1483 /// UsualArithmeticConversions - Performs various conversions that are common to 1484 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1485 /// routine returns the first non-arithmetic type found. The client is 1486 /// responsible for emitting appropriate error diagnostics. 1487 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1488 SourceLocation Loc, 1489 ArithConvKind ACK) { 1490 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1491 1492 if (ACK != ACK_CompAssign) { 1493 LHS = UsualUnaryConversions(LHS.get()); 1494 if (LHS.isInvalid()) 1495 return QualType(); 1496 } 1497 1498 RHS = UsualUnaryConversions(RHS.get()); 1499 if (RHS.isInvalid()) 1500 return QualType(); 1501 1502 // For conversion purposes, we ignore any qualifiers. 1503 // For example, "const float" and "float" are equivalent. 1504 QualType LHSType = 1505 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1506 QualType RHSType = 1507 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1508 1509 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1510 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1511 LHSType = AtomicLHS->getValueType(); 1512 1513 // If both types are identical, no conversion is needed. 1514 if (LHSType == RHSType) 1515 return LHSType; 1516 1517 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1518 // The caller can deal with this (e.g. pointer + int). 1519 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1520 return QualType(); 1521 1522 // Apply unary and bitfield promotions to the LHS's type. 1523 QualType LHSUnpromotedType = LHSType; 1524 if (LHSType->isPromotableIntegerType()) 1525 LHSType = Context.getPromotedIntegerType(LHSType); 1526 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1527 if (!LHSBitfieldPromoteTy.isNull()) 1528 LHSType = LHSBitfieldPromoteTy; 1529 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1530 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1531 1532 // If both types are identical, no conversion is needed. 1533 if (LHSType == RHSType) 1534 return LHSType; 1535 1536 // At this point, we have two different arithmetic types. 1537 1538 // Diagnose attempts to convert between __ibm128, __float128 and long double 1539 // where such conversions currently can't be handled. 1540 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1541 return QualType(); 1542 1543 // Handle complex types first (C99 6.3.1.8p1). 1544 if (LHSType->isComplexType() || RHSType->isComplexType()) 1545 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1546 ACK == ACK_CompAssign); 1547 1548 // Now handle "real" floating types (i.e. float, double, long double). 1549 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1550 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1551 ACK == ACK_CompAssign); 1552 1553 // Handle GCC complex int extension. 1554 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1555 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1556 ACK == ACK_CompAssign); 1557 1558 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1559 return handleFixedPointConversion(*this, LHSType, RHSType); 1560 1561 // Finally, we have two differing integer types. 1562 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1563 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1564 } 1565 1566 //===----------------------------------------------------------------------===// 1567 // Semantic Analysis for various Expression Types 1568 //===----------------------------------------------------------------------===// 1569 1570 1571 ExprResult 1572 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1573 SourceLocation DefaultLoc, 1574 SourceLocation RParenLoc, 1575 Expr *ControllingExpr, 1576 ArrayRef<ParsedType> ArgTypes, 1577 ArrayRef<Expr *> ArgExprs) { 1578 unsigned NumAssocs = ArgTypes.size(); 1579 assert(NumAssocs == ArgExprs.size()); 1580 1581 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1582 for (unsigned i = 0; i < NumAssocs; ++i) { 1583 if (ArgTypes[i]) 1584 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1585 else 1586 Types[i] = nullptr; 1587 } 1588 1589 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1590 ControllingExpr, 1591 llvm::makeArrayRef(Types, NumAssocs), 1592 ArgExprs); 1593 delete [] Types; 1594 return ER; 1595 } 1596 1597 ExprResult 1598 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1599 SourceLocation DefaultLoc, 1600 SourceLocation RParenLoc, 1601 Expr *ControllingExpr, 1602 ArrayRef<TypeSourceInfo *> Types, 1603 ArrayRef<Expr *> Exprs) { 1604 unsigned NumAssocs = Types.size(); 1605 assert(NumAssocs == Exprs.size()); 1606 1607 // Decay and strip qualifiers for the controlling expression type, and handle 1608 // placeholder type replacement. See committee discussion from WG14 DR423. 1609 { 1610 EnterExpressionEvaluationContext Unevaluated( 1611 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1612 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1613 if (R.isInvalid()) 1614 return ExprError(); 1615 ControllingExpr = R.get(); 1616 } 1617 1618 // The controlling expression is an unevaluated operand, so side effects are 1619 // likely unintended. 1620 if (!inTemplateInstantiation() && 1621 ControllingExpr->HasSideEffects(Context, false)) 1622 Diag(ControllingExpr->getExprLoc(), 1623 diag::warn_side_effects_unevaluated_context); 1624 1625 bool TypeErrorFound = false, 1626 IsResultDependent = ControllingExpr->isTypeDependent(), 1627 ContainsUnexpandedParameterPack 1628 = ControllingExpr->containsUnexpandedParameterPack(); 1629 1630 for (unsigned i = 0; i < NumAssocs; ++i) { 1631 if (Exprs[i]->containsUnexpandedParameterPack()) 1632 ContainsUnexpandedParameterPack = true; 1633 1634 if (Types[i]) { 1635 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1636 ContainsUnexpandedParameterPack = true; 1637 1638 if (Types[i]->getType()->isDependentType()) { 1639 IsResultDependent = true; 1640 } else { 1641 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1642 // complete object type other than a variably modified type." 1643 unsigned D = 0; 1644 if (Types[i]->getType()->isIncompleteType()) 1645 D = diag::err_assoc_type_incomplete; 1646 else if (!Types[i]->getType()->isObjectType()) 1647 D = diag::err_assoc_type_nonobject; 1648 else if (Types[i]->getType()->isVariablyModifiedType()) 1649 D = diag::err_assoc_type_variably_modified; 1650 1651 if (D != 0) { 1652 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1653 << Types[i]->getTypeLoc().getSourceRange() 1654 << Types[i]->getType(); 1655 TypeErrorFound = true; 1656 } 1657 1658 // C11 6.5.1.1p2 "No two generic associations in the same generic 1659 // selection shall specify compatible types." 1660 for (unsigned j = i+1; j < NumAssocs; ++j) 1661 if (Types[j] && !Types[j]->getType()->isDependentType() && 1662 Context.typesAreCompatible(Types[i]->getType(), 1663 Types[j]->getType())) { 1664 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1665 diag::err_assoc_compatible_types) 1666 << Types[j]->getTypeLoc().getSourceRange() 1667 << Types[j]->getType() 1668 << Types[i]->getType(); 1669 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1670 diag::note_compat_assoc) 1671 << Types[i]->getTypeLoc().getSourceRange() 1672 << Types[i]->getType(); 1673 TypeErrorFound = true; 1674 } 1675 } 1676 } 1677 } 1678 if (TypeErrorFound) 1679 return ExprError(); 1680 1681 // If we determined that the generic selection is result-dependent, don't 1682 // try to compute the result expression. 1683 if (IsResultDependent) 1684 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1685 Exprs, DefaultLoc, RParenLoc, 1686 ContainsUnexpandedParameterPack); 1687 1688 SmallVector<unsigned, 1> CompatIndices; 1689 unsigned DefaultIndex = -1U; 1690 for (unsigned i = 0; i < NumAssocs; ++i) { 1691 if (!Types[i]) 1692 DefaultIndex = i; 1693 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1694 Types[i]->getType())) 1695 CompatIndices.push_back(i); 1696 } 1697 1698 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1699 // type compatible with at most one of the types named in its generic 1700 // association list." 1701 if (CompatIndices.size() > 1) { 1702 // We strip parens here because the controlling expression is typically 1703 // parenthesized in macro definitions. 1704 ControllingExpr = ControllingExpr->IgnoreParens(); 1705 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1706 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1707 << (unsigned)CompatIndices.size(); 1708 for (unsigned I : CompatIndices) { 1709 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1710 diag::note_compat_assoc) 1711 << Types[I]->getTypeLoc().getSourceRange() 1712 << Types[I]->getType(); 1713 } 1714 return ExprError(); 1715 } 1716 1717 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1718 // its controlling expression shall have type compatible with exactly one of 1719 // the types named in its generic association list." 1720 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1721 // We strip parens here because the controlling expression is typically 1722 // parenthesized in macro definitions. 1723 ControllingExpr = ControllingExpr->IgnoreParens(); 1724 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1725 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1726 return ExprError(); 1727 } 1728 1729 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1730 // type name that is compatible with the type of the controlling expression, 1731 // then the result expression of the generic selection is the expression 1732 // in that generic association. Otherwise, the result expression of the 1733 // generic selection is the expression in the default generic association." 1734 unsigned ResultIndex = 1735 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1736 1737 return GenericSelectionExpr::Create( 1738 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1739 ContainsUnexpandedParameterPack, ResultIndex); 1740 } 1741 1742 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1743 /// location of the token and the offset of the ud-suffix within it. 1744 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1745 unsigned Offset) { 1746 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1747 S.getLangOpts()); 1748 } 1749 1750 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1751 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1752 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1753 IdentifierInfo *UDSuffix, 1754 SourceLocation UDSuffixLoc, 1755 ArrayRef<Expr*> Args, 1756 SourceLocation LitEndLoc) { 1757 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1758 1759 QualType ArgTy[2]; 1760 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1761 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1762 if (ArgTy[ArgIdx]->isArrayType()) 1763 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1764 } 1765 1766 DeclarationName OpName = 1767 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1768 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1769 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1770 1771 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1772 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1773 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1774 /*AllowStringTemplatePack*/ false, 1775 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1776 return ExprError(); 1777 1778 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1779 } 1780 1781 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1782 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1783 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1784 /// multiple tokens. However, the common case is that StringToks points to one 1785 /// string. 1786 /// 1787 ExprResult 1788 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1789 assert(!StringToks.empty() && "Must have at least one string!"); 1790 1791 StringLiteralParser Literal(StringToks, PP); 1792 if (Literal.hadError) 1793 return ExprError(); 1794 1795 SmallVector<SourceLocation, 4> StringTokLocs; 1796 for (const Token &Tok : StringToks) 1797 StringTokLocs.push_back(Tok.getLocation()); 1798 1799 QualType CharTy = Context.CharTy; 1800 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1801 if (Literal.isWide()) { 1802 CharTy = Context.getWideCharType(); 1803 Kind = StringLiteral::Wide; 1804 } else if (Literal.isUTF8()) { 1805 if (getLangOpts().Char8) 1806 CharTy = Context.Char8Ty; 1807 Kind = StringLiteral::UTF8; 1808 } else if (Literal.isUTF16()) { 1809 CharTy = Context.Char16Ty; 1810 Kind = StringLiteral::UTF16; 1811 } else if (Literal.isUTF32()) { 1812 CharTy = Context.Char32Ty; 1813 Kind = StringLiteral::UTF32; 1814 } else if (Literal.isPascal()) { 1815 CharTy = Context.UnsignedCharTy; 1816 } 1817 1818 // Warn on initializing an array of char from a u8 string literal; this 1819 // becomes ill-formed in C++2a. 1820 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1821 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1822 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1823 1824 // Create removals for all 'u8' prefixes in the string literal(s). This 1825 // ensures C++2a compatibility (but may change the program behavior when 1826 // built by non-Clang compilers for which the execution character set is 1827 // not always UTF-8). 1828 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1829 SourceLocation RemovalDiagLoc; 1830 for (const Token &Tok : StringToks) { 1831 if (Tok.getKind() == tok::utf8_string_literal) { 1832 if (RemovalDiagLoc.isInvalid()) 1833 RemovalDiagLoc = Tok.getLocation(); 1834 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1835 Tok.getLocation(), 1836 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1837 getSourceManager(), getLangOpts()))); 1838 } 1839 } 1840 Diag(RemovalDiagLoc, RemovalDiag); 1841 } 1842 1843 QualType StrTy = 1844 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1845 1846 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1847 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1848 Kind, Literal.Pascal, StrTy, 1849 &StringTokLocs[0], 1850 StringTokLocs.size()); 1851 if (Literal.getUDSuffix().empty()) 1852 return Lit; 1853 1854 // We're building a user-defined literal. 1855 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1856 SourceLocation UDSuffixLoc = 1857 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1858 Literal.getUDSuffixOffset()); 1859 1860 // Make sure we're allowed user-defined literals here. 1861 if (!UDLScope) 1862 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1863 1864 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1865 // operator "" X (str, len) 1866 QualType SizeType = Context.getSizeType(); 1867 1868 DeclarationName OpName = 1869 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1870 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1871 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1872 1873 QualType ArgTy[] = { 1874 Context.getArrayDecayedType(StrTy), SizeType 1875 }; 1876 1877 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1878 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1879 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1880 /*AllowStringTemplatePack*/ true, 1881 /*DiagnoseMissing*/ true, Lit)) { 1882 1883 case LOLR_Cooked: { 1884 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1885 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1886 StringTokLocs[0]); 1887 Expr *Args[] = { Lit, LenArg }; 1888 1889 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1890 } 1891 1892 case LOLR_Template: { 1893 TemplateArgumentListInfo ExplicitArgs; 1894 TemplateArgument Arg(Lit); 1895 TemplateArgumentLocInfo ArgInfo(Lit); 1896 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1897 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1898 &ExplicitArgs); 1899 } 1900 1901 case LOLR_StringTemplatePack: { 1902 TemplateArgumentListInfo ExplicitArgs; 1903 1904 unsigned CharBits = Context.getIntWidth(CharTy); 1905 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1906 llvm::APSInt Value(CharBits, CharIsUnsigned); 1907 1908 TemplateArgument TypeArg(CharTy); 1909 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1910 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1911 1912 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1913 Value = Lit->getCodeUnit(I); 1914 TemplateArgument Arg(Context, Value, CharTy); 1915 TemplateArgumentLocInfo ArgInfo; 1916 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1917 } 1918 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1919 &ExplicitArgs); 1920 } 1921 case LOLR_Raw: 1922 case LOLR_ErrorNoDiagnostic: 1923 llvm_unreachable("unexpected literal operator lookup result"); 1924 case LOLR_Error: 1925 return ExprError(); 1926 } 1927 llvm_unreachable("unexpected literal operator lookup result"); 1928 } 1929 1930 DeclRefExpr * 1931 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1932 SourceLocation Loc, 1933 const CXXScopeSpec *SS) { 1934 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1935 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1936 } 1937 1938 DeclRefExpr * 1939 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1940 const DeclarationNameInfo &NameInfo, 1941 const CXXScopeSpec *SS, NamedDecl *FoundD, 1942 SourceLocation TemplateKWLoc, 1943 const TemplateArgumentListInfo *TemplateArgs) { 1944 NestedNameSpecifierLoc NNS = 1945 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1946 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1947 TemplateArgs); 1948 } 1949 1950 // CUDA/HIP: Check whether a captured reference variable is referencing a 1951 // host variable in a device or host device lambda. 1952 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1953 VarDecl *VD) { 1954 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1955 return false; 1956 assert(VD->getType()->isReferenceType()); 1957 1958 // Check whether the reference variable is referencing a host variable. 1959 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1960 if (!DRE) 1961 return false; 1962 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 1963 if (!Referee || !Referee->hasGlobalStorage() || 1964 Referee->hasAttr<CUDADeviceAttr>()) 1965 return false; 1966 1967 // Check whether the current function is a device or host device lambda. 1968 // Check whether the reference variable is a capture by getDeclContext() 1969 // since refersToEnclosingVariableOrCapture() is not ready at this point. 1970 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 1971 if (MD && MD->getParent()->isLambda() && 1972 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 1973 VD->getDeclContext() != MD) 1974 return true; 1975 1976 return false; 1977 } 1978 1979 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1980 // A declaration named in an unevaluated operand never constitutes an odr-use. 1981 if (isUnevaluatedContext()) 1982 return NOUR_Unevaluated; 1983 1984 // C++2a [basic.def.odr]p4: 1985 // A variable x whose name appears as a potentially-evaluated expression e 1986 // is odr-used by e unless [...] x is a reference that is usable in 1987 // constant expressions. 1988 // CUDA/HIP: 1989 // If a reference variable referencing a host variable is captured in a 1990 // device or host device lambda, the value of the referee must be copied 1991 // to the capture and the reference variable must be treated as odr-use 1992 // since the value of the referee is not known at compile time and must 1993 // be loaded from the captured. 1994 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1995 if (VD->getType()->isReferenceType() && 1996 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1997 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 1998 VD->isUsableInConstantExpressions(Context)) 1999 return NOUR_Constant; 2000 } 2001 2002 // All remaining non-variable cases constitute an odr-use. For variables, we 2003 // need to wait and see how the expression is used. 2004 return NOUR_None; 2005 } 2006 2007 /// BuildDeclRefExpr - Build an expression that references a 2008 /// declaration that does not require a closure capture. 2009 DeclRefExpr * 2010 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2011 const DeclarationNameInfo &NameInfo, 2012 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2013 SourceLocation TemplateKWLoc, 2014 const TemplateArgumentListInfo *TemplateArgs) { 2015 bool RefersToCapturedVariable = 2016 isa<VarDecl>(D) && 2017 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2018 2019 DeclRefExpr *E = DeclRefExpr::Create( 2020 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2021 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2022 MarkDeclRefReferenced(E); 2023 2024 // C++ [except.spec]p17: 2025 // An exception-specification is considered to be needed when: 2026 // - in an expression, the function is the unique lookup result or 2027 // the selected member of a set of overloaded functions. 2028 // 2029 // We delay doing this until after we've built the function reference and 2030 // marked it as used so that: 2031 // a) if the function is defaulted, we get errors from defining it before / 2032 // instead of errors from computing its exception specification, and 2033 // b) if the function is a defaulted comparison, we can use the body we 2034 // build when defining it as input to the exception specification 2035 // computation rather than computing a new body. 2036 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2037 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2038 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2039 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2040 } 2041 } 2042 2043 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2044 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2045 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2046 getCurFunction()->recordUseOfWeak(E); 2047 2048 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2049 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2050 FD = IFD->getAnonField(); 2051 if (FD) { 2052 UnusedPrivateFields.remove(FD); 2053 // Just in case we're building an illegal pointer-to-member. 2054 if (FD->isBitField()) 2055 E->setObjectKind(OK_BitField); 2056 } 2057 2058 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2059 // designates a bit-field. 2060 if (auto *BD = dyn_cast<BindingDecl>(D)) 2061 if (auto *BE = BD->getBinding()) 2062 E->setObjectKind(BE->getObjectKind()); 2063 2064 return E; 2065 } 2066 2067 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2068 /// possibly a list of template arguments. 2069 /// 2070 /// If this produces template arguments, it is permitted to call 2071 /// DecomposeTemplateName. 2072 /// 2073 /// This actually loses a lot of source location information for 2074 /// non-standard name kinds; we should consider preserving that in 2075 /// some way. 2076 void 2077 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2078 TemplateArgumentListInfo &Buffer, 2079 DeclarationNameInfo &NameInfo, 2080 const TemplateArgumentListInfo *&TemplateArgs) { 2081 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2082 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2083 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2084 2085 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2086 Id.TemplateId->NumArgs); 2087 translateTemplateArguments(TemplateArgsPtr, Buffer); 2088 2089 TemplateName TName = Id.TemplateId->Template.get(); 2090 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2091 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2092 TemplateArgs = &Buffer; 2093 } else { 2094 NameInfo = GetNameFromUnqualifiedId(Id); 2095 TemplateArgs = nullptr; 2096 } 2097 } 2098 2099 static void emitEmptyLookupTypoDiagnostic( 2100 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2101 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2102 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2103 DeclContext *Ctx = 2104 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2105 if (!TC) { 2106 // Emit a special diagnostic for failed member lookups. 2107 // FIXME: computing the declaration context might fail here (?) 2108 if (Ctx) 2109 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2110 << SS.getRange(); 2111 else 2112 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2113 return; 2114 } 2115 2116 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2117 bool DroppedSpecifier = 2118 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2119 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2120 ? diag::note_implicit_param_decl 2121 : diag::note_previous_decl; 2122 if (!Ctx) 2123 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2124 SemaRef.PDiag(NoteID)); 2125 else 2126 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2127 << Typo << Ctx << DroppedSpecifier 2128 << SS.getRange(), 2129 SemaRef.PDiag(NoteID)); 2130 } 2131 2132 /// Diagnose a lookup that found results in an enclosing class during error 2133 /// recovery. This usually indicates that the results were found in a dependent 2134 /// base class that could not be searched as part of a template definition. 2135 /// Always issues a diagnostic (though this may be only a warning in MS 2136 /// compatibility mode). 2137 /// 2138 /// Return \c true if the error is unrecoverable, or \c false if the caller 2139 /// should attempt to recover using these lookup results. 2140 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2141 // During a default argument instantiation the CurContext points 2142 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2143 // function parameter list, hence add an explicit check. 2144 bool isDefaultArgument = 2145 !CodeSynthesisContexts.empty() && 2146 CodeSynthesisContexts.back().Kind == 2147 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2148 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2149 bool isInstance = CurMethod && CurMethod->isInstance() && 2150 R.getNamingClass() == CurMethod->getParent() && 2151 !isDefaultArgument; 2152 2153 // There are two ways we can find a class-scope declaration during template 2154 // instantiation that we did not find in the template definition: if it is a 2155 // member of a dependent base class, or if it is declared after the point of 2156 // use in the same class. Distinguish these by comparing the class in which 2157 // the member was found to the naming class of the lookup. 2158 unsigned DiagID = diag::err_found_in_dependent_base; 2159 unsigned NoteID = diag::note_member_declared_at; 2160 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2161 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2162 : diag::err_found_later_in_class; 2163 } else if (getLangOpts().MSVCCompat) { 2164 DiagID = diag::ext_found_in_dependent_base; 2165 NoteID = diag::note_dependent_member_use; 2166 } 2167 2168 if (isInstance) { 2169 // Give a code modification hint to insert 'this->'. 2170 Diag(R.getNameLoc(), DiagID) 2171 << R.getLookupName() 2172 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2173 CheckCXXThisCapture(R.getNameLoc()); 2174 } else { 2175 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2176 // they're not shadowed). 2177 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2178 } 2179 2180 for (NamedDecl *D : R) 2181 Diag(D->getLocation(), NoteID); 2182 2183 // Return true if we are inside a default argument instantiation 2184 // and the found name refers to an instance member function, otherwise 2185 // the caller will try to create an implicit member call and this is wrong 2186 // for default arguments. 2187 // 2188 // FIXME: Is this special case necessary? We could allow the caller to 2189 // diagnose this. 2190 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2191 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2192 return true; 2193 } 2194 2195 // Tell the callee to try to recover. 2196 return false; 2197 } 2198 2199 /// Diagnose an empty lookup. 2200 /// 2201 /// \return false if new lookup candidates were found 2202 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2203 CorrectionCandidateCallback &CCC, 2204 TemplateArgumentListInfo *ExplicitTemplateArgs, 2205 ArrayRef<Expr *> Args, TypoExpr **Out) { 2206 DeclarationName Name = R.getLookupName(); 2207 2208 unsigned diagnostic = diag::err_undeclared_var_use; 2209 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2210 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2211 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2212 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2213 diagnostic = diag::err_undeclared_use; 2214 diagnostic_suggest = diag::err_undeclared_use_suggest; 2215 } 2216 2217 // If the original lookup was an unqualified lookup, fake an 2218 // unqualified lookup. This is useful when (for example) the 2219 // original lookup would not have found something because it was a 2220 // dependent name. 2221 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2222 while (DC) { 2223 if (isa<CXXRecordDecl>(DC)) { 2224 LookupQualifiedName(R, DC); 2225 2226 if (!R.empty()) { 2227 // Don't give errors about ambiguities in this lookup. 2228 R.suppressDiagnostics(); 2229 2230 // If there's a best viable function among the results, only mention 2231 // that one in the notes. 2232 OverloadCandidateSet Candidates(R.getNameLoc(), 2233 OverloadCandidateSet::CSK_Normal); 2234 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2235 OverloadCandidateSet::iterator Best; 2236 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2237 OR_Success) { 2238 R.clear(); 2239 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2240 R.resolveKind(); 2241 } 2242 2243 return DiagnoseDependentMemberLookup(R); 2244 } 2245 2246 R.clear(); 2247 } 2248 2249 DC = DC->getLookupParent(); 2250 } 2251 2252 // We didn't find anything, so try to correct for a typo. 2253 TypoCorrection Corrected; 2254 if (S && Out) { 2255 SourceLocation TypoLoc = R.getNameLoc(); 2256 assert(!ExplicitTemplateArgs && 2257 "Diagnosing an empty lookup with explicit template args!"); 2258 *Out = CorrectTypoDelayed( 2259 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2260 [=](const TypoCorrection &TC) { 2261 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2262 diagnostic, diagnostic_suggest); 2263 }, 2264 nullptr, CTK_ErrorRecovery); 2265 if (*Out) 2266 return true; 2267 } else if (S && 2268 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2269 S, &SS, CCC, CTK_ErrorRecovery))) { 2270 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2271 bool DroppedSpecifier = 2272 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2273 R.setLookupName(Corrected.getCorrection()); 2274 2275 bool AcceptableWithRecovery = false; 2276 bool AcceptableWithoutRecovery = false; 2277 NamedDecl *ND = Corrected.getFoundDecl(); 2278 if (ND) { 2279 if (Corrected.isOverloaded()) { 2280 OverloadCandidateSet OCS(R.getNameLoc(), 2281 OverloadCandidateSet::CSK_Normal); 2282 OverloadCandidateSet::iterator Best; 2283 for (NamedDecl *CD : Corrected) { 2284 if (FunctionTemplateDecl *FTD = 2285 dyn_cast<FunctionTemplateDecl>(CD)) 2286 AddTemplateOverloadCandidate( 2287 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2288 Args, OCS); 2289 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2290 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2291 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2292 Args, OCS); 2293 } 2294 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2295 case OR_Success: 2296 ND = Best->FoundDecl; 2297 Corrected.setCorrectionDecl(ND); 2298 break; 2299 default: 2300 // FIXME: Arbitrarily pick the first declaration for the note. 2301 Corrected.setCorrectionDecl(ND); 2302 break; 2303 } 2304 } 2305 R.addDecl(ND); 2306 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2307 CXXRecordDecl *Record = nullptr; 2308 if (Corrected.getCorrectionSpecifier()) { 2309 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2310 Record = Ty->getAsCXXRecordDecl(); 2311 } 2312 if (!Record) 2313 Record = cast<CXXRecordDecl>( 2314 ND->getDeclContext()->getRedeclContext()); 2315 R.setNamingClass(Record); 2316 } 2317 2318 auto *UnderlyingND = ND->getUnderlyingDecl(); 2319 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2320 isa<FunctionTemplateDecl>(UnderlyingND); 2321 // FIXME: If we ended up with a typo for a type name or 2322 // Objective-C class name, we're in trouble because the parser 2323 // is in the wrong place to recover. Suggest the typo 2324 // correction, but don't make it a fix-it since we're not going 2325 // to recover well anyway. 2326 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2327 getAsTypeTemplateDecl(UnderlyingND) || 2328 isa<ObjCInterfaceDecl>(UnderlyingND); 2329 } else { 2330 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2331 // because we aren't able to recover. 2332 AcceptableWithoutRecovery = true; 2333 } 2334 2335 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2336 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2337 ? diag::note_implicit_param_decl 2338 : diag::note_previous_decl; 2339 if (SS.isEmpty()) 2340 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2341 PDiag(NoteID), AcceptableWithRecovery); 2342 else 2343 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2344 << Name << computeDeclContext(SS, false) 2345 << DroppedSpecifier << SS.getRange(), 2346 PDiag(NoteID), AcceptableWithRecovery); 2347 2348 // Tell the callee whether to try to recover. 2349 return !AcceptableWithRecovery; 2350 } 2351 } 2352 R.clear(); 2353 2354 // Emit a special diagnostic for failed member lookups. 2355 // FIXME: computing the declaration context might fail here (?) 2356 if (!SS.isEmpty()) { 2357 Diag(R.getNameLoc(), diag::err_no_member) 2358 << Name << computeDeclContext(SS, false) 2359 << SS.getRange(); 2360 return true; 2361 } 2362 2363 // Give up, we can't recover. 2364 Diag(R.getNameLoc(), diagnostic) << Name; 2365 return true; 2366 } 2367 2368 /// In Microsoft mode, if we are inside a template class whose parent class has 2369 /// dependent base classes, and we can't resolve an unqualified identifier, then 2370 /// assume the identifier is a member of a dependent base class. We can only 2371 /// recover successfully in static methods, instance methods, and other contexts 2372 /// where 'this' is available. This doesn't precisely match MSVC's 2373 /// instantiation model, but it's close enough. 2374 static Expr * 2375 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2376 DeclarationNameInfo &NameInfo, 2377 SourceLocation TemplateKWLoc, 2378 const TemplateArgumentListInfo *TemplateArgs) { 2379 // Only try to recover from lookup into dependent bases in static methods or 2380 // contexts where 'this' is available. 2381 QualType ThisType = S.getCurrentThisType(); 2382 const CXXRecordDecl *RD = nullptr; 2383 if (!ThisType.isNull()) 2384 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2385 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2386 RD = MD->getParent(); 2387 if (!RD || !RD->hasAnyDependentBases()) 2388 return nullptr; 2389 2390 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2391 // is available, suggest inserting 'this->' as a fixit. 2392 SourceLocation Loc = NameInfo.getLoc(); 2393 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2394 DB << NameInfo.getName() << RD; 2395 2396 if (!ThisType.isNull()) { 2397 DB << FixItHint::CreateInsertion(Loc, "this->"); 2398 return CXXDependentScopeMemberExpr::Create( 2399 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2400 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2401 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2402 } 2403 2404 // Synthesize a fake NNS that points to the derived class. This will 2405 // perform name lookup during template instantiation. 2406 CXXScopeSpec SS; 2407 auto *NNS = 2408 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2409 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2410 return DependentScopeDeclRefExpr::Create( 2411 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2412 TemplateArgs); 2413 } 2414 2415 ExprResult 2416 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2417 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2418 bool HasTrailingLParen, bool IsAddressOfOperand, 2419 CorrectionCandidateCallback *CCC, 2420 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2421 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2422 "cannot be direct & operand and have a trailing lparen"); 2423 if (SS.isInvalid()) 2424 return ExprError(); 2425 2426 TemplateArgumentListInfo TemplateArgsBuffer; 2427 2428 // Decompose the UnqualifiedId into the following data. 2429 DeclarationNameInfo NameInfo; 2430 const TemplateArgumentListInfo *TemplateArgs; 2431 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2432 2433 DeclarationName Name = NameInfo.getName(); 2434 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2435 SourceLocation NameLoc = NameInfo.getLoc(); 2436 2437 if (II && II->isEditorPlaceholder()) { 2438 // FIXME: When typed placeholders are supported we can create a typed 2439 // placeholder expression node. 2440 return ExprError(); 2441 } 2442 2443 // C++ [temp.dep.expr]p3: 2444 // An id-expression is type-dependent if it contains: 2445 // -- an identifier that was declared with a dependent type, 2446 // (note: handled after lookup) 2447 // -- a template-id that is dependent, 2448 // (note: handled in BuildTemplateIdExpr) 2449 // -- a conversion-function-id that specifies a dependent type, 2450 // -- a nested-name-specifier that contains a class-name that 2451 // names a dependent type. 2452 // Determine whether this is a member of an unknown specialization; 2453 // we need to handle these differently. 2454 bool DependentID = false; 2455 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2456 Name.getCXXNameType()->isDependentType()) { 2457 DependentID = true; 2458 } else if (SS.isSet()) { 2459 if (DeclContext *DC = computeDeclContext(SS, false)) { 2460 if (RequireCompleteDeclContext(SS, DC)) 2461 return ExprError(); 2462 } else { 2463 DependentID = true; 2464 } 2465 } 2466 2467 if (DependentID) 2468 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2469 IsAddressOfOperand, TemplateArgs); 2470 2471 // Perform the required lookup. 2472 LookupResult R(*this, NameInfo, 2473 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2474 ? LookupObjCImplicitSelfParam 2475 : LookupOrdinaryName); 2476 if (TemplateKWLoc.isValid() || TemplateArgs) { 2477 // Lookup the template name again to correctly establish the context in 2478 // which it was found. This is really unfortunate as we already did the 2479 // lookup to determine that it was a template name in the first place. If 2480 // this becomes a performance hit, we can work harder to preserve those 2481 // results until we get here but it's likely not worth it. 2482 bool MemberOfUnknownSpecialization; 2483 AssumedTemplateKind AssumedTemplate; 2484 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2485 MemberOfUnknownSpecialization, TemplateKWLoc, 2486 &AssumedTemplate)) 2487 return ExprError(); 2488 2489 if (MemberOfUnknownSpecialization || 2490 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2491 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2492 IsAddressOfOperand, TemplateArgs); 2493 } else { 2494 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2495 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2496 2497 // If the result might be in a dependent base class, this is a dependent 2498 // id-expression. 2499 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2500 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2501 IsAddressOfOperand, TemplateArgs); 2502 2503 // If this reference is in an Objective-C method, then we need to do 2504 // some special Objective-C lookup, too. 2505 if (IvarLookupFollowUp) { 2506 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2507 if (E.isInvalid()) 2508 return ExprError(); 2509 2510 if (Expr *Ex = E.getAs<Expr>()) 2511 return Ex; 2512 } 2513 } 2514 2515 if (R.isAmbiguous()) 2516 return ExprError(); 2517 2518 // This could be an implicitly declared function reference (legal in C90, 2519 // extension in C99, forbidden in C++). 2520 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2521 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2522 if (D) R.addDecl(D); 2523 } 2524 2525 // Determine whether this name might be a candidate for 2526 // argument-dependent lookup. 2527 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2528 2529 if (R.empty() && !ADL) { 2530 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2531 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2532 TemplateKWLoc, TemplateArgs)) 2533 return E; 2534 } 2535 2536 // Don't diagnose an empty lookup for inline assembly. 2537 if (IsInlineAsmIdentifier) 2538 return ExprError(); 2539 2540 // If this name wasn't predeclared and if this is not a function 2541 // call, diagnose the problem. 2542 TypoExpr *TE = nullptr; 2543 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2544 : nullptr); 2545 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2546 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2547 "Typo correction callback misconfigured"); 2548 if (CCC) { 2549 // Make sure the callback knows what the typo being diagnosed is. 2550 CCC->setTypoName(II); 2551 if (SS.isValid()) 2552 CCC->setTypoNNS(SS.getScopeRep()); 2553 } 2554 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2555 // a template name, but we happen to have always already looked up the name 2556 // before we get here if it must be a template name. 2557 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2558 None, &TE)) { 2559 if (TE && KeywordReplacement) { 2560 auto &State = getTypoExprState(TE); 2561 auto BestTC = State.Consumer->getNextCorrection(); 2562 if (BestTC.isKeyword()) { 2563 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2564 if (State.DiagHandler) 2565 State.DiagHandler(BestTC); 2566 KeywordReplacement->startToken(); 2567 KeywordReplacement->setKind(II->getTokenID()); 2568 KeywordReplacement->setIdentifierInfo(II); 2569 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2570 // Clean up the state associated with the TypoExpr, since it has 2571 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2572 clearDelayedTypo(TE); 2573 // Signal that a correction to a keyword was performed by returning a 2574 // valid-but-null ExprResult. 2575 return (Expr*)nullptr; 2576 } 2577 State.Consumer->resetCorrectionStream(); 2578 } 2579 return TE ? TE : ExprError(); 2580 } 2581 2582 assert(!R.empty() && 2583 "DiagnoseEmptyLookup returned false but added no results"); 2584 2585 // If we found an Objective-C instance variable, let 2586 // LookupInObjCMethod build the appropriate expression to 2587 // reference the ivar. 2588 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2589 R.clear(); 2590 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2591 // In a hopelessly buggy code, Objective-C instance variable 2592 // lookup fails and no expression will be built to reference it. 2593 if (!E.isInvalid() && !E.get()) 2594 return ExprError(); 2595 return E; 2596 } 2597 } 2598 2599 // This is guaranteed from this point on. 2600 assert(!R.empty() || ADL); 2601 2602 // Check whether this might be a C++ implicit instance member access. 2603 // C++ [class.mfct.non-static]p3: 2604 // When an id-expression that is not part of a class member access 2605 // syntax and not used to form a pointer to member is used in the 2606 // body of a non-static member function of class X, if name lookup 2607 // resolves the name in the id-expression to a non-static non-type 2608 // member of some class C, the id-expression is transformed into a 2609 // class member access expression using (*this) as the 2610 // postfix-expression to the left of the . operator. 2611 // 2612 // But we don't actually need to do this for '&' operands if R 2613 // resolved to a function or overloaded function set, because the 2614 // expression is ill-formed if it actually works out to be a 2615 // non-static member function: 2616 // 2617 // C++ [expr.ref]p4: 2618 // Otherwise, if E1.E2 refers to a non-static member function. . . 2619 // [t]he expression can be used only as the left-hand operand of a 2620 // member function call. 2621 // 2622 // There are other safeguards against such uses, but it's important 2623 // to get this right here so that we don't end up making a 2624 // spuriously dependent expression if we're inside a dependent 2625 // instance method. 2626 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2627 bool MightBeImplicitMember; 2628 if (!IsAddressOfOperand) 2629 MightBeImplicitMember = true; 2630 else if (!SS.isEmpty()) 2631 MightBeImplicitMember = false; 2632 else if (R.isOverloadedResult()) 2633 MightBeImplicitMember = false; 2634 else if (R.isUnresolvableResult()) 2635 MightBeImplicitMember = true; 2636 else 2637 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2638 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2639 isa<MSPropertyDecl>(R.getFoundDecl()); 2640 2641 if (MightBeImplicitMember) 2642 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2643 R, TemplateArgs, S); 2644 } 2645 2646 if (TemplateArgs || TemplateKWLoc.isValid()) { 2647 2648 // In C++1y, if this is a variable template id, then check it 2649 // in BuildTemplateIdExpr(). 2650 // The single lookup result must be a variable template declaration. 2651 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2652 Id.TemplateId->Kind == TNK_Var_template) { 2653 assert(R.getAsSingle<VarTemplateDecl>() && 2654 "There should only be one declaration found."); 2655 } 2656 2657 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2658 } 2659 2660 return BuildDeclarationNameExpr(SS, R, ADL); 2661 } 2662 2663 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2664 /// declaration name, generally during template instantiation. 2665 /// There's a large number of things which don't need to be done along 2666 /// this path. 2667 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2668 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2669 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2670 DeclContext *DC = computeDeclContext(SS, false); 2671 if (!DC) 2672 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2673 NameInfo, /*TemplateArgs=*/nullptr); 2674 2675 if (RequireCompleteDeclContext(SS, DC)) 2676 return ExprError(); 2677 2678 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2679 LookupQualifiedName(R, DC); 2680 2681 if (R.isAmbiguous()) 2682 return ExprError(); 2683 2684 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2685 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2686 NameInfo, /*TemplateArgs=*/nullptr); 2687 2688 if (R.empty()) { 2689 // Don't diagnose problems with invalid record decl, the secondary no_member 2690 // diagnostic during template instantiation is likely bogus, e.g. if a class 2691 // is invalid because it's derived from an invalid base class, then missing 2692 // members were likely supposed to be inherited. 2693 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2694 if (CD->isInvalidDecl()) 2695 return ExprError(); 2696 Diag(NameInfo.getLoc(), diag::err_no_member) 2697 << NameInfo.getName() << DC << SS.getRange(); 2698 return ExprError(); 2699 } 2700 2701 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2702 // Diagnose a missing typename if this resolved unambiguously to a type in 2703 // a dependent context. If we can recover with a type, downgrade this to 2704 // a warning in Microsoft compatibility mode. 2705 unsigned DiagID = diag::err_typename_missing; 2706 if (RecoveryTSI && getLangOpts().MSVCCompat) 2707 DiagID = diag::ext_typename_missing; 2708 SourceLocation Loc = SS.getBeginLoc(); 2709 auto D = Diag(Loc, DiagID); 2710 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2711 << SourceRange(Loc, NameInfo.getEndLoc()); 2712 2713 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2714 // context. 2715 if (!RecoveryTSI) 2716 return ExprError(); 2717 2718 // Only issue the fixit if we're prepared to recover. 2719 D << FixItHint::CreateInsertion(Loc, "typename "); 2720 2721 // Recover by pretending this was an elaborated type. 2722 QualType Ty = Context.getTypeDeclType(TD); 2723 TypeLocBuilder TLB; 2724 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2725 2726 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2727 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2728 QTL.setElaboratedKeywordLoc(SourceLocation()); 2729 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2730 2731 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2732 2733 return ExprEmpty(); 2734 } 2735 2736 // Defend against this resolving to an implicit member access. We usually 2737 // won't get here if this might be a legitimate a class member (we end up in 2738 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2739 // a pointer-to-member or in an unevaluated context in C++11. 2740 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2741 return BuildPossibleImplicitMemberExpr(SS, 2742 /*TemplateKWLoc=*/SourceLocation(), 2743 R, /*TemplateArgs=*/nullptr, S); 2744 2745 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2746 } 2747 2748 /// The parser has read a name in, and Sema has detected that we're currently 2749 /// inside an ObjC method. Perform some additional checks and determine if we 2750 /// should form a reference to an ivar. 2751 /// 2752 /// Ideally, most of this would be done by lookup, but there's 2753 /// actually quite a lot of extra work involved. 2754 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2755 IdentifierInfo *II) { 2756 SourceLocation Loc = Lookup.getNameLoc(); 2757 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2758 2759 // Check for error condition which is already reported. 2760 if (!CurMethod) 2761 return DeclResult(true); 2762 2763 // There are two cases to handle here. 1) scoped lookup could have failed, 2764 // in which case we should look for an ivar. 2) scoped lookup could have 2765 // found a decl, but that decl is outside the current instance method (i.e. 2766 // a global variable). In these two cases, we do a lookup for an ivar with 2767 // this name, if the lookup sucedes, we replace it our current decl. 2768 2769 // If we're in a class method, we don't normally want to look for 2770 // ivars. But if we don't find anything else, and there's an 2771 // ivar, that's an error. 2772 bool IsClassMethod = CurMethod->isClassMethod(); 2773 2774 bool LookForIvars; 2775 if (Lookup.empty()) 2776 LookForIvars = true; 2777 else if (IsClassMethod) 2778 LookForIvars = false; 2779 else 2780 LookForIvars = (Lookup.isSingleResult() && 2781 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2782 ObjCInterfaceDecl *IFace = nullptr; 2783 if (LookForIvars) { 2784 IFace = CurMethod->getClassInterface(); 2785 ObjCInterfaceDecl *ClassDeclared; 2786 ObjCIvarDecl *IV = nullptr; 2787 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2788 // Diagnose using an ivar in a class method. 2789 if (IsClassMethod) { 2790 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2791 return DeclResult(true); 2792 } 2793 2794 // Diagnose the use of an ivar outside of the declaring class. 2795 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2796 !declaresSameEntity(ClassDeclared, IFace) && 2797 !getLangOpts().DebuggerSupport) 2798 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2799 2800 // Success. 2801 return IV; 2802 } 2803 } else if (CurMethod->isInstanceMethod()) { 2804 // We should warn if a local variable hides an ivar. 2805 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2806 ObjCInterfaceDecl *ClassDeclared; 2807 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2808 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2809 declaresSameEntity(IFace, ClassDeclared)) 2810 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2811 } 2812 } 2813 } else if (Lookup.isSingleResult() && 2814 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2815 // If accessing a stand-alone ivar in a class method, this is an error. 2816 if (const ObjCIvarDecl *IV = 2817 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2818 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2819 return DeclResult(true); 2820 } 2821 } 2822 2823 // Didn't encounter an error, didn't find an ivar. 2824 return DeclResult(false); 2825 } 2826 2827 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2828 ObjCIvarDecl *IV) { 2829 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2830 assert(CurMethod && CurMethod->isInstanceMethod() && 2831 "should not reference ivar from this context"); 2832 2833 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2834 assert(IFace && "should not reference ivar from this context"); 2835 2836 // If we're referencing an invalid decl, just return this as a silent 2837 // error node. The error diagnostic was already emitted on the decl. 2838 if (IV->isInvalidDecl()) 2839 return ExprError(); 2840 2841 // Check if referencing a field with __attribute__((deprecated)). 2842 if (DiagnoseUseOfDecl(IV, Loc)) 2843 return ExprError(); 2844 2845 // FIXME: This should use a new expr for a direct reference, don't 2846 // turn this into Self->ivar, just return a BareIVarExpr or something. 2847 IdentifierInfo &II = Context.Idents.get("self"); 2848 UnqualifiedId SelfName; 2849 SelfName.setImplicitSelfParam(&II); 2850 CXXScopeSpec SelfScopeSpec; 2851 SourceLocation TemplateKWLoc; 2852 ExprResult SelfExpr = 2853 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2854 /*HasTrailingLParen=*/false, 2855 /*IsAddressOfOperand=*/false); 2856 if (SelfExpr.isInvalid()) 2857 return ExprError(); 2858 2859 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2860 if (SelfExpr.isInvalid()) 2861 return ExprError(); 2862 2863 MarkAnyDeclReferenced(Loc, IV, true); 2864 2865 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2866 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2867 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2868 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2869 2870 ObjCIvarRefExpr *Result = new (Context) 2871 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2872 IV->getLocation(), SelfExpr.get(), true, true); 2873 2874 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2875 if (!isUnevaluatedContext() && 2876 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2877 getCurFunction()->recordUseOfWeak(Result); 2878 } 2879 if (getLangOpts().ObjCAutoRefCount) 2880 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2881 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2882 2883 return Result; 2884 } 2885 2886 /// The parser has read a name in, and Sema has detected that we're currently 2887 /// inside an ObjC method. Perform some additional checks and determine if we 2888 /// should form a reference to an ivar. If so, build an expression referencing 2889 /// that ivar. 2890 ExprResult 2891 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2892 IdentifierInfo *II, bool AllowBuiltinCreation) { 2893 // FIXME: Integrate this lookup step into LookupParsedName. 2894 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2895 if (Ivar.isInvalid()) 2896 return ExprError(); 2897 if (Ivar.isUsable()) 2898 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2899 cast<ObjCIvarDecl>(Ivar.get())); 2900 2901 if (Lookup.empty() && II && AllowBuiltinCreation) 2902 LookupBuiltin(Lookup); 2903 2904 // Sentinel value saying that we didn't do anything special. 2905 return ExprResult(false); 2906 } 2907 2908 /// Cast a base object to a member's actual type. 2909 /// 2910 /// There are two relevant checks: 2911 /// 2912 /// C++ [class.access.base]p7: 2913 /// 2914 /// If a class member access operator [...] is used to access a non-static 2915 /// data member or non-static member function, the reference is ill-formed if 2916 /// the left operand [...] cannot be implicitly converted to a pointer to the 2917 /// naming class of the right operand. 2918 /// 2919 /// C++ [expr.ref]p7: 2920 /// 2921 /// If E2 is a non-static data member or a non-static member function, the 2922 /// program is ill-formed if the class of which E2 is directly a member is an 2923 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2924 /// 2925 /// Note that the latter check does not consider access; the access of the 2926 /// "real" base class is checked as appropriate when checking the access of the 2927 /// member name. 2928 ExprResult 2929 Sema::PerformObjectMemberConversion(Expr *From, 2930 NestedNameSpecifier *Qualifier, 2931 NamedDecl *FoundDecl, 2932 NamedDecl *Member) { 2933 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2934 if (!RD) 2935 return From; 2936 2937 QualType DestRecordType; 2938 QualType DestType; 2939 QualType FromRecordType; 2940 QualType FromType = From->getType(); 2941 bool PointerConversions = false; 2942 if (isa<FieldDecl>(Member)) { 2943 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2944 auto FromPtrType = FromType->getAs<PointerType>(); 2945 DestRecordType = Context.getAddrSpaceQualType( 2946 DestRecordType, FromPtrType 2947 ? FromType->getPointeeType().getAddressSpace() 2948 : FromType.getAddressSpace()); 2949 2950 if (FromPtrType) { 2951 DestType = Context.getPointerType(DestRecordType); 2952 FromRecordType = FromPtrType->getPointeeType(); 2953 PointerConversions = true; 2954 } else { 2955 DestType = DestRecordType; 2956 FromRecordType = FromType; 2957 } 2958 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2959 if (Method->isStatic()) 2960 return From; 2961 2962 DestType = Method->getThisType(); 2963 DestRecordType = DestType->getPointeeType(); 2964 2965 if (FromType->getAs<PointerType>()) { 2966 FromRecordType = FromType->getPointeeType(); 2967 PointerConversions = true; 2968 } else { 2969 FromRecordType = FromType; 2970 DestType = DestRecordType; 2971 } 2972 2973 LangAS FromAS = FromRecordType.getAddressSpace(); 2974 LangAS DestAS = DestRecordType.getAddressSpace(); 2975 if (FromAS != DestAS) { 2976 QualType FromRecordTypeWithoutAS = 2977 Context.removeAddrSpaceQualType(FromRecordType); 2978 QualType FromTypeWithDestAS = 2979 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2980 if (PointerConversions) 2981 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2982 From = ImpCastExprToType(From, FromTypeWithDestAS, 2983 CK_AddressSpaceConversion, From->getValueKind()) 2984 .get(); 2985 } 2986 } else { 2987 // No conversion necessary. 2988 return From; 2989 } 2990 2991 if (DestType->isDependentType() || FromType->isDependentType()) 2992 return From; 2993 2994 // If the unqualified types are the same, no conversion is necessary. 2995 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2996 return From; 2997 2998 SourceRange FromRange = From->getSourceRange(); 2999 SourceLocation FromLoc = FromRange.getBegin(); 3000 3001 ExprValueKind VK = From->getValueKind(); 3002 3003 // C++ [class.member.lookup]p8: 3004 // [...] Ambiguities can often be resolved by qualifying a name with its 3005 // class name. 3006 // 3007 // If the member was a qualified name and the qualified referred to a 3008 // specific base subobject type, we'll cast to that intermediate type 3009 // first and then to the object in which the member is declared. That allows 3010 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3011 // 3012 // class Base { public: int x; }; 3013 // class Derived1 : public Base { }; 3014 // class Derived2 : public Base { }; 3015 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3016 // 3017 // void VeryDerived::f() { 3018 // x = 17; // error: ambiguous base subobjects 3019 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3020 // } 3021 if (Qualifier && Qualifier->getAsType()) { 3022 QualType QType = QualType(Qualifier->getAsType(), 0); 3023 assert(QType->isRecordType() && "lookup done with non-record type"); 3024 3025 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3026 3027 // In C++98, the qualifier type doesn't actually have to be a base 3028 // type of the object type, in which case we just ignore it. 3029 // Otherwise build the appropriate casts. 3030 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3031 CXXCastPath BasePath; 3032 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3033 FromLoc, FromRange, &BasePath)) 3034 return ExprError(); 3035 3036 if (PointerConversions) 3037 QType = Context.getPointerType(QType); 3038 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3039 VK, &BasePath).get(); 3040 3041 FromType = QType; 3042 FromRecordType = QRecordType; 3043 3044 // If the qualifier type was the same as the destination type, 3045 // we're done. 3046 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3047 return From; 3048 } 3049 } 3050 3051 CXXCastPath BasePath; 3052 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3053 FromLoc, FromRange, &BasePath, 3054 /*IgnoreAccess=*/true)) 3055 return ExprError(); 3056 3057 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3058 VK, &BasePath); 3059 } 3060 3061 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3062 const LookupResult &R, 3063 bool HasTrailingLParen) { 3064 // Only when used directly as the postfix-expression of a call. 3065 if (!HasTrailingLParen) 3066 return false; 3067 3068 // Never if a scope specifier was provided. 3069 if (SS.isSet()) 3070 return false; 3071 3072 // Only in C++ or ObjC++. 3073 if (!getLangOpts().CPlusPlus) 3074 return false; 3075 3076 // Turn off ADL when we find certain kinds of declarations during 3077 // normal lookup: 3078 for (NamedDecl *D : R) { 3079 // C++0x [basic.lookup.argdep]p3: 3080 // -- a declaration of a class member 3081 // Since using decls preserve this property, we check this on the 3082 // original decl. 3083 if (D->isCXXClassMember()) 3084 return false; 3085 3086 // C++0x [basic.lookup.argdep]p3: 3087 // -- a block-scope function declaration that is not a 3088 // using-declaration 3089 // NOTE: we also trigger this for function templates (in fact, we 3090 // don't check the decl type at all, since all other decl types 3091 // turn off ADL anyway). 3092 if (isa<UsingShadowDecl>(D)) 3093 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3094 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3095 return false; 3096 3097 // C++0x [basic.lookup.argdep]p3: 3098 // -- a declaration that is neither a function or a function 3099 // template 3100 // And also for builtin functions. 3101 if (isa<FunctionDecl>(D)) { 3102 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3103 3104 // But also builtin functions. 3105 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3106 return false; 3107 } else if (!isa<FunctionTemplateDecl>(D)) 3108 return false; 3109 } 3110 3111 return true; 3112 } 3113 3114 3115 /// Diagnoses obvious problems with the use of the given declaration 3116 /// as an expression. This is only actually called for lookups that 3117 /// were not overloaded, and it doesn't promise that the declaration 3118 /// will in fact be used. 3119 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3120 if (D->isInvalidDecl()) 3121 return true; 3122 3123 if (isa<TypedefNameDecl>(D)) { 3124 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3125 return true; 3126 } 3127 3128 if (isa<ObjCInterfaceDecl>(D)) { 3129 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3130 return true; 3131 } 3132 3133 if (isa<NamespaceDecl>(D)) { 3134 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3135 return true; 3136 } 3137 3138 return false; 3139 } 3140 3141 // Certain multiversion types should be treated as overloaded even when there is 3142 // only one result. 3143 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3144 assert(R.isSingleResult() && "Expected only a single result"); 3145 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3146 return FD && 3147 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3148 } 3149 3150 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3151 LookupResult &R, bool NeedsADL, 3152 bool AcceptInvalidDecl) { 3153 // If this is a single, fully-resolved result and we don't need ADL, 3154 // just build an ordinary singleton decl ref. 3155 if (!NeedsADL && R.isSingleResult() && 3156 !R.getAsSingle<FunctionTemplateDecl>() && 3157 !ShouldLookupResultBeMultiVersionOverload(R)) 3158 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3159 R.getRepresentativeDecl(), nullptr, 3160 AcceptInvalidDecl); 3161 3162 // We only need to check the declaration if there's exactly one 3163 // result, because in the overloaded case the results can only be 3164 // functions and function templates. 3165 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3166 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3167 return ExprError(); 3168 3169 // Otherwise, just build an unresolved lookup expression. Suppress 3170 // any lookup-related diagnostics; we'll hash these out later, when 3171 // we've picked a target. 3172 R.suppressDiagnostics(); 3173 3174 UnresolvedLookupExpr *ULE 3175 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3176 SS.getWithLocInContext(Context), 3177 R.getLookupNameInfo(), 3178 NeedsADL, R.isOverloadedResult(), 3179 R.begin(), R.end()); 3180 3181 return ULE; 3182 } 3183 3184 static void 3185 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3186 ValueDecl *var, DeclContext *DC); 3187 3188 /// Complete semantic analysis for a reference to the given declaration. 3189 ExprResult Sema::BuildDeclarationNameExpr( 3190 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3191 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3192 bool AcceptInvalidDecl) { 3193 assert(D && "Cannot refer to a NULL declaration"); 3194 assert(!isa<FunctionTemplateDecl>(D) && 3195 "Cannot refer unambiguously to a function template"); 3196 3197 SourceLocation Loc = NameInfo.getLoc(); 3198 if (CheckDeclInExpr(*this, Loc, D)) 3199 return ExprError(); 3200 3201 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3202 // Specifically diagnose references to class templates that are missing 3203 // a template argument list. 3204 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3205 return ExprError(); 3206 } 3207 3208 // Make sure that we're referring to a value. 3209 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { 3210 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange(); 3211 Diag(D->getLocation(), diag::note_declared_at); 3212 return ExprError(); 3213 } 3214 3215 // Check whether this declaration can be used. Note that we suppress 3216 // this check when we're going to perform argument-dependent lookup 3217 // on this function name, because this might not be the function 3218 // that overload resolution actually selects. 3219 if (DiagnoseUseOfDecl(D, Loc)) 3220 return ExprError(); 3221 3222 auto *VD = cast<ValueDecl>(D); 3223 3224 // Only create DeclRefExpr's for valid Decl's. 3225 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3226 return ExprError(); 3227 3228 // Handle members of anonymous structs and unions. If we got here, 3229 // and the reference is to a class member indirect field, then this 3230 // must be the subject of a pointer-to-member expression. 3231 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3232 if (!indirectField->isCXXClassMember()) 3233 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3234 indirectField); 3235 3236 QualType type = VD->getType(); 3237 if (type.isNull()) 3238 return ExprError(); 3239 ExprValueKind valueKind = VK_PRValue; 3240 3241 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3242 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3243 // is expanded by some outer '...' in the context of the use. 3244 type = type.getNonPackExpansionType(); 3245 3246 switch (D->getKind()) { 3247 // Ignore all the non-ValueDecl kinds. 3248 #define ABSTRACT_DECL(kind) 3249 #define VALUE(type, base) 3250 #define DECL(type, base) case Decl::type: 3251 #include "clang/AST/DeclNodes.inc" 3252 llvm_unreachable("invalid value decl kind"); 3253 3254 // These shouldn't make it here. 3255 case Decl::ObjCAtDefsField: 3256 llvm_unreachable("forming non-member reference to ivar?"); 3257 3258 // Enum constants are always r-values and never references. 3259 // Unresolved using declarations are dependent. 3260 case Decl::EnumConstant: 3261 case Decl::UnresolvedUsingValue: 3262 case Decl::OMPDeclareReduction: 3263 case Decl::OMPDeclareMapper: 3264 valueKind = VK_PRValue; 3265 break; 3266 3267 // Fields and indirect fields that got here must be for 3268 // pointer-to-member expressions; we just call them l-values for 3269 // internal consistency, because this subexpression doesn't really 3270 // exist in the high-level semantics. 3271 case Decl::Field: 3272 case Decl::IndirectField: 3273 case Decl::ObjCIvar: 3274 assert(getLangOpts().CPlusPlus && "building reference to field in C?"); 3275 3276 // These can't have reference type in well-formed programs, but 3277 // for internal consistency we do this anyway. 3278 type = type.getNonReferenceType(); 3279 valueKind = VK_LValue; 3280 break; 3281 3282 // Non-type template parameters are either l-values or r-values 3283 // depending on the type. 3284 case Decl::NonTypeTemplateParm: { 3285 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3286 type = reftype->getPointeeType(); 3287 valueKind = VK_LValue; // even if the parameter is an r-value reference 3288 break; 3289 } 3290 3291 // [expr.prim.id.unqual]p2: 3292 // If the entity is a template parameter object for a template 3293 // parameter of type T, the type of the expression is const T. 3294 // [...] The expression is an lvalue if the entity is a [...] template 3295 // parameter object. 3296 if (type->isRecordType()) { 3297 type = type.getUnqualifiedType().withConst(); 3298 valueKind = VK_LValue; 3299 break; 3300 } 3301 3302 // For non-references, we need to strip qualifiers just in case 3303 // the template parameter was declared as 'const int' or whatever. 3304 valueKind = VK_PRValue; 3305 type = type.getUnqualifiedType(); 3306 break; 3307 } 3308 3309 case Decl::Var: 3310 case Decl::VarTemplateSpecialization: 3311 case Decl::VarTemplatePartialSpecialization: 3312 case Decl::Decomposition: 3313 case Decl::OMPCapturedExpr: 3314 // In C, "extern void blah;" is valid and is an r-value. 3315 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && 3316 type->isVoidType()) { 3317 valueKind = VK_PRValue; 3318 break; 3319 } 3320 LLVM_FALLTHROUGH; 3321 3322 case Decl::ImplicitParam: 3323 case Decl::ParmVar: { 3324 // These are always l-values. 3325 valueKind = VK_LValue; 3326 type = type.getNonReferenceType(); 3327 3328 // FIXME: Does the addition of const really only apply in 3329 // potentially-evaluated contexts? Since the variable isn't actually 3330 // captured in an unevaluated context, it seems that the answer is no. 3331 if (!isUnevaluatedContext()) { 3332 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3333 if (!CapturedType.isNull()) 3334 type = CapturedType; 3335 } 3336 3337 break; 3338 } 3339 3340 case Decl::Binding: { 3341 // These are always lvalues. 3342 valueKind = VK_LValue; 3343 type = type.getNonReferenceType(); 3344 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3345 // decides how that's supposed to work. 3346 auto *BD = cast<BindingDecl>(VD); 3347 if (BD->getDeclContext() != CurContext) { 3348 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3349 if (DD && DD->hasLocalStorage()) 3350 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3351 } 3352 break; 3353 } 3354 3355 case Decl::Function: { 3356 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3357 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3358 type = Context.BuiltinFnTy; 3359 valueKind = VK_PRValue; 3360 break; 3361 } 3362 } 3363 3364 const FunctionType *fty = type->castAs<FunctionType>(); 3365 3366 // If we're referring to a function with an __unknown_anytype 3367 // result type, make the entire expression __unknown_anytype. 3368 if (fty->getReturnType() == Context.UnknownAnyTy) { 3369 type = Context.UnknownAnyTy; 3370 valueKind = VK_PRValue; 3371 break; 3372 } 3373 3374 // Functions are l-values in C++. 3375 if (getLangOpts().CPlusPlus) { 3376 valueKind = VK_LValue; 3377 break; 3378 } 3379 3380 // C99 DR 316 says that, if a function type comes from a 3381 // function definition (without a prototype), that type is only 3382 // used for checking compatibility. Therefore, when referencing 3383 // the function, we pretend that we don't have the full function 3384 // type. 3385 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty)) 3386 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3387 fty->getExtInfo()); 3388 3389 // Functions are r-values in C. 3390 valueKind = VK_PRValue; 3391 break; 3392 } 3393 3394 case Decl::CXXDeductionGuide: 3395 llvm_unreachable("building reference to deduction guide"); 3396 3397 case Decl::MSProperty: 3398 case Decl::MSGuid: 3399 case Decl::TemplateParamObject: 3400 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3401 // capture in OpenMP, or duplicated between host and device? 3402 valueKind = VK_LValue; 3403 break; 3404 3405 case Decl::CXXMethod: 3406 // If we're referring to a method with an __unknown_anytype 3407 // result type, make the entire expression __unknown_anytype. 3408 // This should only be possible with a type written directly. 3409 if (const FunctionProtoType *proto = 3410 dyn_cast<FunctionProtoType>(VD->getType())) 3411 if (proto->getReturnType() == Context.UnknownAnyTy) { 3412 type = Context.UnknownAnyTy; 3413 valueKind = VK_PRValue; 3414 break; 3415 } 3416 3417 // C++ methods are l-values if static, r-values if non-static. 3418 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3419 valueKind = VK_LValue; 3420 break; 3421 } 3422 LLVM_FALLTHROUGH; 3423 3424 case Decl::CXXConversion: 3425 case Decl::CXXDestructor: 3426 case Decl::CXXConstructor: 3427 valueKind = VK_PRValue; 3428 break; 3429 } 3430 3431 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3432 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3433 TemplateArgs); 3434 } 3435 3436 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3437 SmallString<32> &Target) { 3438 Target.resize(CharByteWidth * (Source.size() + 1)); 3439 char *ResultPtr = &Target[0]; 3440 const llvm::UTF8 *ErrorPtr; 3441 bool success = 3442 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3443 (void)success; 3444 assert(success); 3445 Target.resize(ResultPtr - &Target[0]); 3446 } 3447 3448 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3449 PredefinedExpr::IdentKind IK) { 3450 // Pick the current block, lambda, captured statement or function. 3451 Decl *currentDecl = nullptr; 3452 if (const BlockScopeInfo *BSI = getCurBlock()) 3453 currentDecl = BSI->TheDecl; 3454 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3455 currentDecl = LSI->CallOperator; 3456 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3457 currentDecl = CSI->TheCapturedDecl; 3458 else 3459 currentDecl = getCurFunctionOrMethodDecl(); 3460 3461 if (!currentDecl) { 3462 Diag(Loc, diag::ext_predef_outside_function); 3463 currentDecl = Context.getTranslationUnitDecl(); 3464 } 3465 3466 QualType ResTy; 3467 StringLiteral *SL = nullptr; 3468 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3469 ResTy = Context.DependentTy; 3470 else { 3471 // Pre-defined identifiers are of type char[x], where x is the length of 3472 // the string. 3473 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3474 unsigned Length = Str.length(); 3475 3476 llvm::APInt LengthI(32, Length + 1); 3477 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3478 ResTy = 3479 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3480 SmallString<32> RawChars; 3481 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3482 Str, RawChars); 3483 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3484 ArrayType::Normal, 3485 /*IndexTypeQuals*/ 0); 3486 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3487 /*Pascal*/ false, ResTy, Loc); 3488 } else { 3489 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3490 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3491 ArrayType::Normal, 3492 /*IndexTypeQuals*/ 0); 3493 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3494 /*Pascal*/ false, ResTy, Loc); 3495 } 3496 } 3497 3498 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3499 } 3500 3501 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3502 SourceLocation LParen, 3503 SourceLocation RParen, 3504 TypeSourceInfo *TSI) { 3505 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); 3506 } 3507 3508 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3509 SourceLocation LParen, 3510 SourceLocation RParen, 3511 ParsedType ParsedTy) { 3512 TypeSourceInfo *TSI = nullptr; 3513 QualType Ty = GetTypeFromParser(ParsedTy, &TSI); 3514 3515 if (Ty.isNull()) 3516 return ExprError(); 3517 if (!TSI) 3518 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); 3519 3520 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); 3521 } 3522 3523 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3524 PredefinedExpr::IdentKind IK; 3525 3526 switch (Kind) { 3527 default: llvm_unreachable("Unknown simple primary expr!"); 3528 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3529 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3530 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3531 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3532 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3533 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3534 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3535 } 3536 3537 return BuildPredefinedExpr(Loc, IK); 3538 } 3539 3540 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3541 SmallString<16> CharBuffer; 3542 bool Invalid = false; 3543 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3544 if (Invalid) 3545 return ExprError(); 3546 3547 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3548 PP, Tok.getKind()); 3549 if (Literal.hadError()) 3550 return ExprError(); 3551 3552 QualType Ty; 3553 if (Literal.isWide()) 3554 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3555 else if (Literal.isUTF8() && getLangOpts().Char8) 3556 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3557 else if (Literal.isUTF16()) 3558 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3559 else if (Literal.isUTF32()) 3560 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3561 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3562 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3563 else 3564 Ty = Context.CharTy; // 'x' -> char in C++ 3565 3566 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3567 if (Literal.isWide()) 3568 Kind = CharacterLiteral::Wide; 3569 else if (Literal.isUTF16()) 3570 Kind = CharacterLiteral::UTF16; 3571 else if (Literal.isUTF32()) 3572 Kind = CharacterLiteral::UTF32; 3573 else if (Literal.isUTF8()) 3574 Kind = CharacterLiteral::UTF8; 3575 3576 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3577 Tok.getLocation()); 3578 3579 if (Literal.getUDSuffix().empty()) 3580 return Lit; 3581 3582 // We're building a user-defined literal. 3583 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3584 SourceLocation UDSuffixLoc = 3585 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3586 3587 // Make sure we're allowed user-defined literals here. 3588 if (!UDLScope) 3589 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3590 3591 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3592 // operator "" X (ch) 3593 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3594 Lit, Tok.getLocation()); 3595 } 3596 3597 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3598 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3599 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3600 Context.IntTy, Loc); 3601 } 3602 3603 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3604 QualType Ty, SourceLocation Loc) { 3605 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3606 3607 using llvm::APFloat; 3608 APFloat Val(Format); 3609 3610 APFloat::opStatus result = Literal.GetFloatValue(Val); 3611 3612 // Overflow is always an error, but underflow is only an error if 3613 // we underflowed to zero (APFloat reports denormals as underflow). 3614 if ((result & APFloat::opOverflow) || 3615 ((result & APFloat::opUnderflow) && Val.isZero())) { 3616 unsigned diagnostic; 3617 SmallString<20> buffer; 3618 if (result & APFloat::opOverflow) { 3619 diagnostic = diag::warn_float_overflow; 3620 APFloat::getLargest(Format).toString(buffer); 3621 } else { 3622 diagnostic = diag::warn_float_underflow; 3623 APFloat::getSmallest(Format).toString(buffer); 3624 } 3625 3626 S.Diag(Loc, diagnostic) 3627 << Ty 3628 << StringRef(buffer.data(), buffer.size()); 3629 } 3630 3631 bool isExact = (result == APFloat::opOK); 3632 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3633 } 3634 3635 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3636 assert(E && "Invalid expression"); 3637 3638 if (E->isValueDependent()) 3639 return false; 3640 3641 QualType QT = E->getType(); 3642 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3643 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3644 return true; 3645 } 3646 3647 llvm::APSInt ValueAPS; 3648 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3649 3650 if (R.isInvalid()) 3651 return true; 3652 3653 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3654 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3655 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3656 << toString(ValueAPS, 10) << ValueIsPositive; 3657 return true; 3658 } 3659 3660 return false; 3661 } 3662 3663 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3664 // Fast path for a single digit (which is quite common). A single digit 3665 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3666 if (Tok.getLength() == 1) { 3667 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3668 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3669 } 3670 3671 SmallString<128> SpellingBuffer; 3672 // NumericLiteralParser wants to overread by one character. Add padding to 3673 // the buffer in case the token is copied to the buffer. If getSpelling() 3674 // returns a StringRef to the memory buffer, it should have a null char at 3675 // the EOF, so it is also safe. 3676 SpellingBuffer.resize(Tok.getLength() + 1); 3677 3678 // Get the spelling of the token, which eliminates trigraphs, etc. 3679 bool Invalid = false; 3680 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3681 if (Invalid) 3682 return ExprError(); 3683 3684 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3685 PP.getSourceManager(), PP.getLangOpts(), 3686 PP.getTargetInfo(), PP.getDiagnostics()); 3687 if (Literal.hadError) 3688 return ExprError(); 3689 3690 if (Literal.hasUDSuffix()) { 3691 // We're building a user-defined literal. 3692 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3693 SourceLocation UDSuffixLoc = 3694 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3695 3696 // Make sure we're allowed user-defined literals here. 3697 if (!UDLScope) 3698 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3699 3700 QualType CookedTy; 3701 if (Literal.isFloatingLiteral()) { 3702 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3703 // long double, the literal is treated as a call of the form 3704 // operator "" X (f L) 3705 CookedTy = Context.LongDoubleTy; 3706 } else { 3707 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3708 // unsigned long long, the literal is treated as a call of the form 3709 // operator "" X (n ULL) 3710 CookedTy = Context.UnsignedLongLongTy; 3711 } 3712 3713 DeclarationName OpName = 3714 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3715 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3716 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3717 3718 SourceLocation TokLoc = Tok.getLocation(); 3719 3720 // Perform literal operator lookup to determine if we're building a raw 3721 // literal or a cooked one. 3722 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3723 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3724 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3725 /*AllowStringTemplatePack*/ false, 3726 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3727 case LOLR_ErrorNoDiagnostic: 3728 // Lookup failure for imaginary constants isn't fatal, there's still the 3729 // GNU extension producing _Complex types. 3730 break; 3731 case LOLR_Error: 3732 return ExprError(); 3733 case LOLR_Cooked: { 3734 Expr *Lit; 3735 if (Literal.isFloatingLiteral()) { 3736 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3737 } else { 3738 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3739 if (Literal.GetIntegerValue(ResultVal)) 3740 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3741 << /* Unsigned */ 1; 3742 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3743 Tok.getLocation()); 3744 } 3745 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3746 } 3747 3748 case LOLR_Raw: { 3749 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3750 // literal is treated as a call of the form 3751 // operator "" X ("n") 3752 unsigned Length = Literal.getUDSuffixOffset(); 3753 QualType StrTy = Context.getConstantArrayType( 3754 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3755 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3756 Expr *Lit = StringLiteral::Create( 3757 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3758 /*Pascal*/false, StrTy, &TokLoc, 1); 3759 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3760 } 3761 3762 case LOLR_Template: { 3763 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3764 // template), L is treated as a call fo the form 3765 // operator "" X <'c1', 'c2', ... 'ck'>() 3766 // where n is the source character sequence c1 c2 ... ck. 3767 TemplateArgumentListInfo ExplicitArgs; 3768 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3769 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3770 llvm::APSInt Value(CharBits, CharIsUnsigned); 3771 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3772 Value = TokSpelling[I]; 3773 TemplateArgument Arg(Context, Value, Context.CharTy); 3774 TemplateArgumentLocInfo ArgInfo; 3775 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3776 } 3777 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3778 &ExplicitArgs); 3779 } 3780 case LOLR_StringTemplatePack: 3781 llvm_unreachable("unexpected literal operator lookup result"); 3782 } 3783 } 3784 3785 Expr *Res; 3786 3787 if (Literal.isFixedPointLiteral()) { 3788 QualType Ty; 3789 3790 if (Literal.isAccum) { 3791 if (Literal.isHalf) { 3792 Ty = Context.ShortAccumTy; 3793 } else if (Literal.isLong) { 3794 Ty = Context.LongAccumTy; 3795 } else { 3796 Ty = Context.AccumTy; 3797 } 3798 } else if (Literal.isFract) { 3799 if (Literal.isHalf) { 3800 Ty = Context.ShortFractTy; 3801 } else if (Literal.isLong) { 3802 Ty = Context.LongFractTy; 3803 } else { 3804 Ty = Context.FractTy; 3805 } 3806 } 3807 3808 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3809 3810 bool isSigned = !Literal.isUnsigned; 3811 unsigned scale = Context.getFixedPointScale(Ty); 3812 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3813 3814 llvm::APInt Val(bit_width, 0, isSigned); 3815 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3816 bool ValIsZero = Val.isNullValue() && !Overflowed; 3817 3818 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3819 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3820 // Clause 6.4.4 - The value of a constant shall be in the range of 3821 // representable values for its type, with exception for constants of a 3822 // fract type with a value of exactly 1; such a constant shall denote 3823 // the maximal value for the type. 3824 --Val; 3825 else if (Val.ugt(MaxVal) || Overflowed) 3826 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3827 3828 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3829 Tok.getLocation(), scale); 3830 } else if (Literal.isFloatingLiteral()) { 3831 QualType Ty; 3832 if (Literal.isHalf){ 3833 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3834 Ty = Context.HalfTy; 3835 else { 3836 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3837 return ExprError(); 3838 } 3839 } else if (Literal.isFloat) 3840 Ty = Context.FloatTy; 3841 else if (Literal.isLong) 3842 Ty = Context.LongDoubleTy; 3843 else if (Literal.isFloat16) 3844 Ty = Context.Float16Ty; 3845 else if (Literal.isFloat128) 3846 Ty = Context.Float128Ty; 3847 else 3848 Ty = Context.DoubleTy; 3849 3850 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3851 3852 if (Ty == Context.DoubleTy) { 3853 if (getLangOpts().SinglePrecisionConstants) { 3854 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3855 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3856 } 3857 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3858 "cl_khr_fp64", getLangOpts())) { 3859 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3860 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) 3861 << (getLangOpts().getOpenCLCompatibleVersion() >= 300); 3862 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3863 } 3864 } 3865 } else if (!Literal.isIntegerLiteral()) { 3866 return ExprError(); 3867 } else { 3868 QualType Ty; 3869 3870 // 'long long' is a C99 or C++11 feature. 3871 if (!getLangOpts().C99 && Literal.isLongLong) { 3872 if (getLangOpts().CPlusPlus) 3873 Diag(Tok.getLocation(), 3874 getLangOpts().CPlusPlus11 ? 3875 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3876 else 3877 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3878 } 3879 3880 // 'z/uz' literals are a C++2b feature. 3881 if (Literal.isSizeT) 3882 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3883 ? getLangOpts().CPlusPlus2b 3884 ? diag::warn_cxx20_compat_size_t_suffix 3885 : diag::ext_cxx2b_size_t_suffix 3886 : diag::err_cxx2b_size_t_suffix); 3887 3888 // Get the value in the widest-possible width. 3889 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3890 llvm::APInt ResultVal(MaxWidth, 0); 3891 3892 if (Literal.GetIntegerValue(ResultVal)) { 3893 // If this value didn't fit into uintmax_t, error and force to ull. 3894 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3895 << /* Unsigned */ 1; 3896 Ty = Context.UnsignedLongLongTy; 3897 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3898 "long long is not intmax_t?"); 3899 } else { 3900 // If this value fits into a ULL, try to figure out what else it fits into 3901 // according to the rules of C99 6.4.4.1p5. 3902 3903 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3904 // be an unsigned int. 3905 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3906 3907 // Check from smallest to largest, picking the smallest type we can. 3908 unsigned Width = 0; 3909 3910 // Microsoft specific integer suffixes are explicitly sized. 3911 if (Literal.MicrosoftInteger) { 3912 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3913 Width = 8; 3914 Ty = Context.CharTy; 3915 } else { 3916 Width = Literal.MicrosoftInteger; 3917 Ty = Context.getIntTypeForBitwidth(Width, 3918 /*Signed=*/!Literal.isUnsigned); 3919 } 3920 } 3921 3922 // Check C++2b size_t literals. 3923 if (Literal.isSizeT) { 3924 assert(!Literal.MicrosoftInteger && 3925 "size_t literals can't be Microsoft literals"); 3926 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 3927 Context.getTargetInfo().getSizeType()); 3928 3929 // Does it fit in size_t? 3930 if (ResultVal.isIntN(SizeTSize)) { 3931 // Does it fit in ssize_t? 3932 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 3933 Ty = Context.getSignedSizeType(); 3934 else if (AllowUnsigned) 3935 Ty = Context.getSizeType(); 3936 Width = SizeTSize; 3937 } 3938 } 3939 3940 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 3941 !Literal.isSizeT) { 3942 // Are int/unsigned possibilities? 3943 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3944 3945 // Does it fit in a unsigned int? 3946 if (ResultVal.isIntN(IntSize)) { 3947 // Does it fit in a signed int? 3948 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3949 Ty = Context.IntTy; 3950 else if (AllowUnsigned) 3951 Ty = Context.UnsignedIntTy; 3952 Width = IntSize; 3953 } 3954 } 3955 3956 // Are long/unsigned long possibilities? 3957 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 3958 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3959 3960 // Does it fit in a unsigned long? 3961 if (ResultVal.isIntN(LongSize)) { 3962 // Does it fit in a signed long? 3963 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3964 Ty = Context.LongTy; 3965 else if (AllowUnsigned) 3966 Ty = Context.UnsignedLongTy; 3967 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3968 // is compatible. 3969 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3970 const unsigned LongLongSize = 3971 Context.getTargetInfo().getLongLongWidth(); 3972 Diag(Tok.getLocation(), 3973 getLangOpts().CPlusPlus 3974 ? Literal.isLong 3975 ? diag::warn_old_implicitly_unsigned_long_cxx 3976 : /*C++98 UB*/ diag:: 3977 ext_old_implicitly_unsigned_long_cxx 3978 : diag::warn_old_implicitly_unsigned_long) 3979 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3980 : /*will be ill-formed*/ 1); 3981 Ty = Context.UnsignedLongTy; 3982 } 3983 Width = LongSize; 3984 } 3985 } 3986 3987 // Check long long if needed. 3988 if (Ty.isNull() && !Literal.isSizeT) { 3989 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3990 3991 // Does it fit in a unsigned long long? 3992 if (ResultVal.isIntN(LongLongSize)) { 3993 // Does it fit in a signed long long? 3994 // To be compatible with MSVC, hex integer literals ending with the 3995 // LL or i64 suffix are always signed in Microsoft mode. 3996 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3997 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3998 Ty = Context.LongLongTy; 3999 else if (AllowUnsigned) 4000 Ty = Context.UnsignedLongLongTy; 4001 Width = LongLongSize; 4002 } 4003 } 4004 4005 // If we still couldn't decide a type, we either have 'size_t' literal 4006 // that is out of range, or a decimal literal that does not fit in a 4007 // signed long long and has no U suffix. 4008 if (Ty.isNull()) { 4009 if (Literal.isSizeT) 4010 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 4011 << Literal.isUnsigned; 4012 else 4013 Diag(Tok.getLocation(), 4014 diag::ext_integer_literal_too_large_for_signed); 4015 Ty = Context.UnsignedLongLongTy; 4016 Width = Context.getTargetInfo().getLongLongWidth(); 4017 } 4018 4019 if (ResultVal.getBitWidth() != Width) 4020 ResultVal = ResultVal.trunc(Width); 4021 } 4022 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 4023 } 4024 4025 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 4026 if (Literal.isImaginary) { 4027 Res = new (Context) ImaginaryLiteral(Res, 4028 Context.getComplexType(Res->getType())); 4029 4030 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4031 } 4032 return Res; 4033 } 4034 4035 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4036 assert(E && "ActOnParenExpr() missing expr"); 4037 QualType ExprTy = E->getType(); 4038 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && 4039 !E->isLValue() && ExprTy->hasFloatingRepresentation()) 4040 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); 4041 return new (Context) ParenExpr(L, R, E); 4042 } 4043 4044 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4045 SourceLocation Loc, 4046 SourceRange ArgRange) { 4047 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4048 // scalar or vector data type argument..." 4049 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4050 // type (C99 6.2.5p18) or void. 4051 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4052 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4053 << T << ArgRange; 4054 return true; 4055 } 4056 4057 assert((T->isVoidType() || !T->isIncompleteType()) && 4058 "Scalar types should always be complete"); 4059 return false; 4060 } 4061 4062 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4063 SourceLocation Loc, 4064 SourceRange ArgRange, 4065 UnaryExprOrTypeTrait TraitKind) { 4066 // Invalid types must be hard errors for SFINAE in C++. 4067 if (S.LangOpts.CPlusPlus) 4068 return true; 4069 4070 // C99 6.5.3.4p1: 4071 if (T->isFunctionType() && 4072 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4073 TraitKind == UETT_PreferredAlignOf)) { 4074 // sizeof(function)/alignof(function) is allowed as an extension. 4075 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4076 << getTraitSpelling(TraitKind) << ArgRange; 4077 return false; 4078 } 4079 4080 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4081 // this is an error (OpenCL v1.1 s6.3.k) 4082 if (T->isVoidType()) { 4083 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4084 : diag::ext_sizeof_alignof_void_type; 4085 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4086 return false; 4087 } 4088 4089 return true; 4090 } 4091 4092 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4093 SourceLocation Loc, 4094 SourceRange ArgRange, 4095 UnaryExprOrTypeTrait TraitKind) { 4096 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4097 // runtime doesn't allow it. 4098 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4099 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4100 << T << (TraitKind == UETT_SizeOf) 4101 << ArgRange; 4102 return true; 4103 } 4104 4105 return false; 4106 } 4107 4108 /// Check whether E is a pointer from a decayed array type (the decayed 4109 /// pointer type is equal to T) and emit a warning if it is. 4110 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4111 Expr *E) { 4112 // Don't warn if the operation changed the type. 4113 if (T != E->getType()) 4114 return; 4115 4116 // Now look for array decays. 4117 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4118 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4119 return; 4120 4121 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4122 << ICE->getType() 4123 << ICE->getSubExpr()->getType(); 4124 } 4125 4126 /// Check the constraints on expression operands to unary type expression 4127 /// and type traits. 4128 /// 4129 /// Completes any types necessary and validates the constraints on the operand 4130 /// expression. The logic mostly mirrors the type-based overload, but may modify 4131 /// the expression as it completes the type for that expression through template 4132 /// instantiation, etc. 4133 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4134 UnaryExprOrTypeTrait ExprKind) { 4135 QualType ExprTy = E->getType(); 4136 assert(!ExprTy->isReferenceType()); 4137 4138 bool IsUnevaluatedOperand = 4139 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4140 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4141 if (IsUnevaluatedOperand) { 4142 ExprResult Result = CheckUnevaluatedOperand(E); 4143 if (Result.isInvalid()) 4144 return true; 4145 E = Result.get(); 4146 } 4147 4148 // The operand for sizeof and alignof is in an unevaluated expression context, 4149 // so side effects could result in unintended consequences. 4150 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4151 // used to build SFINAE gadgets. 4152 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4153 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4154 !E->isInstantiationDependent() && 4155 E->HasSideEffects(Context, false)) 4156 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4157 4158 if (ExprKind == UETT_VecStep) 4159 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4160 E->getSourceRange()); 4161 4162 // Explicitly list some types as extensions. 4163 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4164 E->getSourceRange(), ExprKind)) 4165 return false; 4166 4167 // 'alignof' applied to an expression only requires the base element type of 4168 // the expression to be complete. 'sizeof' requires the expression's type to 4169 // be complete (and will attempt to complete it if it's an array of unknown 4170 // bound). 4171 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4172 if (RequireCompleteSizedType( 4173 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4174 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4175 getTraitSpelling(ExprKind), E->getSourceRange())) 4176 return true; 4177 } else { 4178 if (RequireCompleteSizedExprType( 4179 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4180 getTraitSpelling(ExprKind), E->getSourceRange())) 4181 return true; 4182 } 4183 4184 // Completing the expression's type may have changed it. 4185 ExprTy = E->getType(); 4186 assert(!ExprTy->isReferenceType()); 4187 4188 if (ExprTy->isFunctionType()) { 4189 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4190 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4191 return true; 4192 } 4193 4194 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4195 E->getSourceRange(), ExprKind)) 4196 return true; 4197 4198 if (ExprKind == UETT_SizeOf) { 4199 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4200 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4201 QualType OType = PVD->getOriginalType(); 4202 QualType Type = PVD->getType(); 4203 if (Type->isPointerType() && OType->isArrayType()) { 4204 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4205 << Type << OType; 4206 Diag(PVD->getLocation(), diag::note_declared_at); 4207 } 4208 } 4209 } 4210 4211 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4212 // decays into a pointer and returns an unintended result. This is most 4213 // likely a typo for "sizeof(array) op x". 4214 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4215 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4216 BO->getLHS()); 4217 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4218 BO->getRHS()); 4219 } 4220 } 4221 4222 return false; 4223 } 4224 4225 /// Check the constraints on operands to unary expression and type 4226 /// traits. 4227 /// 4228 /// This will complete any types necessary, and validate the various constraints 4229 /// on those operands. 4230 /// 4231 /// The UsualUnaryConversions() function is *not* called by this routine. 4232 /// C99 6.3.2.1p[2-4] all state: 4233 /// Except when it is the operand of the sizeof operator ... 4234 /// 4235 /// C++ [expr.sizeof]p4 4236 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4237 /// standard conversions are not applied to the operand of sizeof. 4238 /// 4239 /// This policy is followed for all of the unary trait expressions. 4240 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4241 SourceLocation OpLoc, 4242 SourceRange ExprRange, 4243 UnaryExprOrTypeTrait ExprKind) { 4244 if (ExprType->isDependentType()) 4245 return false; 4246 4247 // C++ [expr.sizeof]p2: 4248 // When applied to a reference or a reference type, the result 4249 // is the size of the referenced type. 4250 // C++11 [expr.alignof]p3: 4251 // When alignof is applied to a reference type, the result 4252 // shall be the alignment of the referenced type. 4253 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4254 ExprType = Ref->getPointeeType(); 4255 4256 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4257 // When alignof or _Alignof is applied to an array type, the result 4258 // is the alignment of the element type. 4259 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4260 ExprKind == UETT_OpenMPRequiredSimdAlign) 4261 ExprType = Context.getBaseElementType(ExprType); 4262 4263 if (ExprKind == UETT_VecStep) 4264 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4265 4266 // Explicitly list some types as extensions. 4267 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4268 ExprKind)) 4269 return false; 4270 4271 if (RequireCompleteSizedType( 4272 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4273 getTraitSpelling(ExprKind), ExprRange)) 4274 return true; 4275 4276 if (ExprType->isFunctionType()) { 4277 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4278 << getTraitSpelling(ExprKind) << ExprRange; 4279 return true; 4280 } 4281 4282 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4283 ExprKind)) 4284 return true; 4285 4286 return false; 4287 } 4288 4289 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4290 // Cannot know anything else if the expression is dependent. 4291 if (E->isTypeDependent()) 4292 return false; 4293 4294 if (E->getObjectKind() == OK_BitField) { 4295 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4296 << 1 << E->getSourceRange(); 4297 return true; 4298 } 4299 4300 ValueDecl *D = nullptr; 4301 Expr *Inner = E->IgnoreParens(); 4302 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4303 D = DRE->getDecl(); 4304 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4305 D = ME->getMemberDecl(); 4306 } 4307 4308 // If it's a field, require the containing struct to have a 4309 // complete definition so that we can compute the layout. 4310 // 4311 // This can happen in C++11 onwards, either by naming the member 4312 // in a way that is not transformed into a member access expression 4313 // (in an unevaluated operand, for instance), or by naming the member 4314 // in a trailing-return-type. 4315 // 4316 // For the record, since __alignof__ on expressions is a GCC 4317 // extension, GCC seems to permit this but always gives the 4318 // nonsensical answer 0. 4319 // 4320 // We don't really need the layout here --- we could instead just 4321 // directly check for all the appropriate alignment-lowing 4322 // attributes --- but that would require duplicating a lot of 4323 // logic that just isn't worth duplicating for such a marginal 4324 // use-case. 4325 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4326 // Fast path this check, since we at least know the record has a 4327 // definition if we can find a member of it. 4328 if (!FD->getParent()->isCompleteDefinition()) { 4329 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4330 << E->getSourceRange(); 4331 return true; 4332 } 4333 4334 // Otherwise, if it's a field, and the field doesn't have 4335 // reference type, then it must have a complete type (or be a 4336 // flexible array member, which we explicitly want to 4337 // white-list anyway), which makes the following checks trivial. 4338 if (!FD->getType()->isReferenceType()) 4339 return false; 4340 } 4341 4342 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4343 } 4344 4345 bool Sema::CheckVecStepExpr(Expr *E) { 4346 E = E->IgnoreParens(); 4347 4348 // Cannot know anything else if the expression is dependent. 4349 if (E->isTypeDependent()) 4350 return false; 4351 4352 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4353 } 4354 4355 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4356 CapturingScopeInfo *CSI) { 4357 assert(T->isVariablyModifiedType()); 4358 assert(CSI != nullptr); 4359 4360 // We're going to walk down into the type and look for VLA expressions. 4361 do { 4362 const Type *Ty = T.getTypePtr(); 4363 switch (Ty->getTypeClass()) { 4364 #define TYPE(Class, Base) 4365 #define ABSTRACT_TYPE(Class, Base) 4366 #define NON_CANONICAL_TYPE(Class, Base) 4367 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4368 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4369 #include "clang/AST/TypeNodes.inc" 4370 T = QualType(); 4371 break; 4372 // These types are never variably-modified. 4373 case Type::Builtin: 4374 case Type::Complex: 4375 case Type::Vector: 4376 case Type::ExtVector: 4377 case Type::ConstantMatrix: 4378 case Type::Record: 4379 case Type::Enum: 4380 case Type::Elaborated: 4381 case Type::TemplateSpecialization: 4382 case Type::ObjCObject: 4383 case Type::ObjCInterface: 4384 case Type::ObjCObjectPointer: 4385 case Type::ObjCTypeParam: 4386 case Type::Pipe: 4387 case Type::ExtInt: 4388 llvm_unreachable("type class is never variably-modified!"); 4389 case Type::Adjusted: 4390 T = cast<AdjustedType>(Ty)->getOriginalType(); 4391 break; 4392 case Type::Decayed: 4393 T = cast<DecayedType>(Ty)->getPointeeType(); 4394 break; 4395 case Type::Pointer: 4396 T = cast<PointerType>(Ty)->getPointeeType(); 4397 break; 4398 case Type::BlockPointer: 4399 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4400 break; 4401 case Type::LValueReference: 4402 case Type::RValueReference: 4403 T = cast<ReferenceType>(Ty)->getPointeeType(); 4404 break; 4405 case Type::MemberPointer: 4406 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4407 break; 4408 case Type::ConstantArray: 4409 case Type::IncompleteArray: 4410 // Losing element qualification here is fine. 4411 T = cast<ArrayType>(Ty)->getElementType(); 4412 break; 4413 case Type::VariableArray: { 4414 // Losing element qualification here is fine. 4415 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4416 4417 // Unknown size indication requires no size computation. 4418 // Otherwise, evaluate and record it. 4419 auto Size = VAT->getSizeExpr(); 4420 if (Size && !CSI->isVLATypeCaptured(VAT) && 4421 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4422 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4423 4424 T = VAT->getElementType(); 4425 break; 4426 } 4427 case Type::FunctionProto: 4428 case Type::FunctionNoProto: 4429 T = cast<FunctionType>(Ty)->getReturnType(); 4430 break; 4431 case Type::Paren: 4432 case Type::TypeOf: 4433 case Type::UnaryTransform: 4434 case Type::Attributed: 4435 case Type::SubstTemplateTypeParm: 4436 case Type::MacroQualified: 4437 // Keep walking after single level desugaring. 4438 T = T.getSingleStepDesugaredType(Context); 4439 break; 4440 case Type::Typedef: 4441 T = cast<TypedefType>(Ty)->desugar(); 4442 break; 4443 case Type::Decltype: 4444 T = cast<DecltypeType>(Ty)->desugar(); 4445 break; 4446 case Type::Auto: 4447 case Type::DeducedTemplateSpecialization: 4448 T = cast<DeducedType>(Ty)->getDeducedType(); 4449 break; 4450 case Type::TypeOfExpr: 4451 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4452 break; 4453 case Type::Atomic: 4454 T = cast<AtomicType>(Ty)->getValueType(); 4455 break; 4456 } 4457 } while (!T.isNull() && T->isVariablyModifiedType()); 4458 } 4459 4460 /// Build a sizeof or alignof expression given a type operand. 4461 ExprResult 4462 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4463 SourceLocation OpLoc, 4464 UnaryExprOrTypeTrait ExprKind, 4465 SourceRange R) { 4466 if (!TInfo) 4467 return ExprError(); 4468 4469 QualType T = TInfo->getType(); 4470 4471 if (!T->isDependentType() && 4472 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4473 return ExprError(); 4474 4475 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4476 if (auto *TT = T->getAs<TypedefType>()) { 4477 for (auto I = FunctionScopes.rbegin(), 4478 E = std::prev(FunctionScopes.rend()); 4479 I != E; ++I) { 4480 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4481 if (CSI == nullptr) 4482 break; 4483 DeclContext *DC = nullptr; 4484 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4485 DC = LSI->CallOperator; 4486 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4487 DC = CRSI->TheCapturedDecl; 4488 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4489 DC = BSI->TheDecl; 4490 if (DC) { 4491 if (DC->containsDecl(TT->getDecl())) 4492 break; 4493 captureVariablyModifiedType(Context, T, CSI); 4494 } 4495 } 4496 } 4497 } 4498 4499 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4500 return new (Context) UnaryExprOrTypeTraitExpr( 4501 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4502 } 4503 4504 /// Build a sizeof or alignof expression given an expression 4505 /// operand. 4506 ExprResult 4507 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4508 UnaryExprOrTypeTrait ExprKind) { 4509 ExprResult PE = CheckPlaceholderExpr(E); 4510 if (PE.isInvalid()) 4511 return ExprError(); 4512 4513 E = PE.get(); 4514 4515 // Verify that the operand is valid. 4516 bool isInvalid = false; 4517 if (E->isTypeDependent()) { 4518 // Delay type-checking for type-dependent expressions. 4519 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4520 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4521 } else if (ExprKind == UETT_VecStep) { 4522 isInvalid = CheckVecStepExpr(E); 4523 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4524 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4525 isInvalid = true; 4526 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4527 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4528 isInvalid = true; 4529 } else { 4530 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4531 } 4532 4533 if (isInvalid) 4534 return ExprError(); 4535 4536 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4537 PE = TransformToPotentiallyEvaluated(E); 4538 if (PE.isInvalid()) return ExprError(); 4539 E = PE.get(); 4540 } 4541 4542 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4543 return new (Context) UnaryExprOrTypeTraitExpr( 4544 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4545 } 4546 4547 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4548 /// expr and the same for @c alignof and @c __alignof 4549 /// Note that the ArgRange is invalid if isType is false. 4550 ExprResult 4551 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4552 UnaryExprOrTypeTrait ExprKind, bool IsType, 4553 void *TyOrEx, SourceRange ArgRange) { 4554 // If error parsing type, ignore. 4555 if (!TyOrEx) return ExprError(); 4556 4557 if (IsType) { 4558 TypeSourceInfo *TInfo; 4559 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4560 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4561 } 4562 4563 Expr *ArgEx = (Expr *)TyOrEx; 4564 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4565 return Result; 4566 } 4567 4568 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4569 bool IsReal) { 4570 if (V.get()->isTypeDependent()) 4571 return S.Context.DependentTy; 4572 4573 // _Real and _Imag are only l-values for normal l-values. 4574 if (V.get()->getObjectKind() != OK_Ordinary) { 4575 V = S.DefaultLvalueConversion(V.get()); 4576 if (V.isInvalid()) 4577 return QualType(); 4578 } 4579 4580 // These operators return the element type of a complex type. 4581 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4582 return CT->getElementType(); 4583 4584 // Otherwise they pass through real integer and floating point types here. 4585 if (V.get()->getType()->isArithmeticType()) 4586 return V.get()->getType(); 4587 4588 // Test for placeholders. 4589 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4590 if (PR.isInvalid()) return QualType(); 4591 if (PR.get() != V.get()) { 4592 V = PR; 4593 return CheckRealImagOperand(S, V, Loc, IsReal); 4594 } 4595 4596 // Reject anything else. 4597 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4598 << (IsReal ? "__real" : "__imag"); 4599 return QualType(); 4600 } 4601 4602 4603 4604 ExprResult 4605 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4606 tok::TokenKind Kind, Expr *Input) { 4607 UnaryOperatorKind Opc; 4608 switch (Kind) { 4609 default: llvm_unreachable("Unknown unary op!"); 4610 case tok::plusplus: Opc = UO_PostInc; break; 4611 case tok::minusminus: Opc = UO_PostDec; break; 4612 } 4613 4614 // Since this might is a postfix expression, get rid of ParenListExprs. 4615 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4616 if (Result.isInvalid()) return ExprError(); 4617 Input = Result.get(); 4618 4619 return BuildUnaryOp(S, OpLoc, Opc, Input); 4620 } 4621 4622 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4623 /// 4624 /// \return true on error 4625 static bool checkArithmeticOnObjCPointer(Sema &S, 4626 SourceLocation opLoc, 4627 Expr *op) { 4628 assert(op->getType()->isObjCObjectPointerType()); 4629 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4630 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4631 return false; 4632 4633 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4634 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4635 << op->getSourceRange(); 4636 return true; 4637 } 4638 4639 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4640 auto *BaseNoParens = Base->IgnoreParens(); 4641 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4642 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4643 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4644 } 4645 4646 ExprResult 4647 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4648 Expr *idx, SourceLocation rbLoc) { 4649 if (base && !base->getType().isNull() && 4650 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4651 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4652 SourceLocation(), /*Length*/ nullptr, 4653 /*Stride=*/nullptr, rbLoc); 4654 4655 // Since this might be a postfix expression, get rid of ParenListExprs. 4656 if (isa<ParenListExpr>(base)) { 4657 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4658 if (result.isInvalid()) return ExprError(); 4659 base = result.get(); 4660 } 4661 4662 // Check if base and idx form a MatrixSubscriptExpr. 4663 // 4664 // Helper to check for comma expressions, which are not allowed as indices for 4665 // matrix subscript expressions. 4666 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4667 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4668 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4669 << SourceRange(base->getBeginLoc(), rbLoc); 4670 return true; 4671 } 4672 return false; 4673 }; 4674 // The matrix subscript operator ([][])is considered a single operator. 4675 // Separating the index expressions by parenthesis is not allowed. 4676 if (base->getType()->isSpecificPlaceholderType( 4677 BuiltinType::IncompleteMatrixIdx) && 4678 !isa<MatrixSubscriptExpr>(base)) { 4679 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4680 << SourceRange(base->getBeginLoc(), rbLoc); 4681 return ExprError(); 4682 } 4683 // If the base is a MatrixSubscriptExpr, try to create a new 4684 // MatrixSubscriptExpr. 4685 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4686 if (matSubscriptE) { 4687 if (CheckAndReportCommaError(idx)) 4688 return ExprError(); 4689 4690 assert(matSubscriptE->isIncomplete() && 4691 "base has to be an incomplete matrix subscript"); 4692 return CreateBuiltinMatrixSubscriptExpr( 4693 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4694 } 4695 4696 // Handle any non-overload placeholder types in the base and index 4697 // expressions. We can't handle overloads here because the other 4698 // operand might be an overloadable type, in which case the overload 4699 // resolution for the operator overload should get the first crack 4700 // at the overload. 4701 bool IsMSPropertySubscript = false; 4702 if (base->getType()->isNonOverloadPlaceholderType()) { 4703 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4704 if (!IsMSPropertySubscript) { 4705 ExprResult result = CheckPlaceholderExpr(base); 4706 if (result.isInvalid()) 4707 return ExprError(); 4708 base = result.get(); 4709 } 4710 } 4711 4712 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4713 if (base->getType()->isMatrixType()) { 4714 if (CheckAndReportCommaError(idx)) 4715 return ExprError(); 4716 4717 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4718 } 4719 4720 // A comma-expression as the index is deprecated in C++2a onwards. 4721 if (getLangOpts().CPlusPlus20 && 4722 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4723 (isa<CXXOperatorCallExpr>(idx) && 4724 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4725 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4726 << SourceRange(base->getBeginLoc(), rbLoc); 4727 } 4728 4729 if (idx->getType()->isNonOverloadPlaceholderType()) { 4730 ExprResult result = CheckPlaceholderExpr(idx); 4731 if (result.isInvalid()) return ExprError(); 4732 idx = result.get(); 4733 } 4734 4735 // Build an unanalyzed expression if either operand is type-dependent. 4736 if (getLangOpts().CPlusPlus && 4737 (base->isTypeDependent() || idx->isTypeDependent())) { 4738 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4739 VK_LValue, OK_Ordinary, rbLoc); 4740 } 4741 4742 // MSDN, property (C++) 4743 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4744 // This attribute can also be used in the declaration of an empty array in a 4745 // class or structure definition. For example: 4746 // __declspec(property(get=GetX, put=PutX)) int x[]; 4747 // The above statement indicates that x[] can be used with one or more array 4748 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4749 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4750 if (IsMSPropertySubscript) { 4751 // Build MS property subscript expression if base is MS property reference 4752 // or MS property subscript. 4753 return new (Context) MSPropertySubscriptExpr( 4754 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4755 } 4756 4757 // Use C++ overloaded-operator rules if either operand has record 4758 // type. The spec says to do this if either type is *overloadable*, 4759 // but enum types can't declare subscript operators or conversion 4760 // operators, so there's nothing interesting for overload resolution 4761 // to do if there aren't any record types involved. 4762 // 4763 // ObjC pointers have their own subscripting logic that is not tied 4764 // to overload resolution and so should not take this path. 4765 if (getLangOpts().CPlusPlus && 4766 (base->getType()->isRecordType() || 4767 (!base->getType()->isObjCObjectPointerType() && 4768 idx->getType()->isRecordType()))) { 4769 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4770 } 4771 4772 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4773 4774 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4775 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4776 4777 return Res; 4778 } 4779 4780 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4781 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4782 InitializationKind Kind = 4783 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4784 InitializationSequence InitSeq(*this, Entity, Kind, E); 4785 return InitSeq.Perform(*this, Entity, Kind, E); 4786 } 4787 4788 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4789 Expr *ColumnIdx, 4790 SourceLocation RBLoc) { 4791 ExprResult BaseR = CheckPlaceholderExpr(Base); 4792 if (BaseR.isInvalid()) 4793 return BaseR; 4794 Base = BaseR.get(); 4795 4796 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4797 if (RowR.isInvalid()) 4798 return RowR; 4799 RowIdx = RowR.get(); 4800 4801 if (!ColumnIdx) 4802 return new (Context) MatrixSubscriptExpr( 4803 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4804 4805 // Build an unanalyzed expression if any of the operands is type-dependent. 4806 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4807 ColumnIdx->isTypeDependent()) 4808 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4809 Context.DependentTy, RBLoc); 4810 4811 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4812 if (ColumnR.isInvalid()) 4813 return ColumnR; 4814 ColumnIdx = ColumnR.get(); 4815 4816 // Check that IndexExpr is an integer expression. If it is a constant 4817 // expression, check that it is less than Dim (= the number of elements in the 4818 // corresponding dimension). 4819 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4820 bool IsColumnIdx) -> Expr * { 4821 if (!IndexExpr->getType()->isIntegerType() && 4822 !IndexExpr->isTypeDependent()) { 4823 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4824 << IsColumnIdx; 4825 return nullptr; 4826 } 4827 4828 if (Optional<llvm::APSInt> Idx = 4829 IndexExpr->getIntegerConstantExpr(Context)) { 4830 if ((*Idx < 0 || *Idx >= Dim)) { 4831 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4832 << IsColumnIdx << Dim; 4833 return nullptr; 4834 } 4835 } 4836 4837 ExprResult ConvExpr = 4838 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4839 assert(!ConvExpr.isInvalid() && 4840 "should be able to convert any integer type to size type"); 4841 return ConvExpr.get(); 4842 }; 4843 4844 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4845 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4846 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4847 if (!RowIdx || !ColumnIdx) 4848 return ExprError(); 4849 4850 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4851 MTy->getElementType(), RBLoc); 4852 } 4853 4854 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4855 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4856 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4857 4858 // For expressions like `&(*s).b`, the base is recorded and what should be 4859 // checked. 4860 const MemberExpr *Member = nullptr; 4861 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4862 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4863 4864 LastRecord.PossibleDerefs.erase(StrippedExpr); 4865 } 4866 4867 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4868 if (isUnevaluatedContext()) 4869 return; 4870 4871 QualType ResultTy = E->getType(); 4872 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4873 4874 // Bail if the element is an array since it is not memory access. 4875 if (isa<ArrayType>(ResultTy)) 4876 return; 4877 4878 if (ResultTy->hasAttr(attr::NoDeref)) { 4879 LastRecord.PossibleDerefs.insert(E); 4880 return; 4881 } 4882 4883 // Check if the base type is a pointer to a member access of a struct 4884 // marked with noderef. 4885 const Expr *Base = E->getBase(); 4886 QualType BaseTy = Base->getType(); 4887 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4888 // Not a pointer access 4889 return; 4890 4891 const MemberExpr *Member = nullptr; 4892 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4893 Member->isArrow()) 4894 Base = Member->getBase(); 4895 4896 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4897 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4898 LastRecord.PossibleDerefs.insert(E); 4899 } 4900 } 4901 4902 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4903 Expr *LowerBound, 4904 SourceLocation ColonLocFirst, 4905 SourceLocation ColonLocSecond, 4906 Expr *Length, Expr *Stride, 4907 SourceLocation RBLoc) { 4908 if (Base->getType()->isPlaceholderType() && 4909 !Base->getType()->isSpecificPlaceholderType( 4910 BuiltinType::OMPArraySection)) { 4911 ExprResult Result = CheckPlaceholderExpr(Base); 4912 if (Result.isInvalid()) 4913 return ExprError(); 4914 Base = Result.get(); 4915 } 4916 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4917 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4918 if (Result.isInvalid()) 4919 return ExprError(); 4920 Result = DefaultLvalueConversion(Result.get()); 4921 if (Result.isInvalid()) 4922 return ExprError(); 4923 LowerBound = Result.get(); 4924 } 4925 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4926 ExprResult Result = CheckPlaceholderExpr(Length); 4927 if (Result.isInvalid()) 4928 return ExprError(); 4929 Result = DefaultLvalueConversion(Result.get()); 4930 if (Result.isInvalid()) 4931 return ExprError(); 4932 Length = Result.get(); 4933 } 4934 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4935 ExprResult Result = CheckPlaceholderExpr(Stride); 4936 if (Result.isInvalid()) 4937 return ExprError(); 4938 Result = DefaultLvalueConversion(Result.get()); 4939 if (Result.isInvalid()) 4940 return ExprError(); 4941 Stride = Result.get(); 4942 } 4943 4944 // Build an unanalyzed expression if either operand is type-dependent. 4945 if (Base->isTypeDependent() || 4946 (LowerBound && 4947 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4948 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4949 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4950 return new (Context) OMPArraySectionExpr( 4951 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4952 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4953 } 4954 4955 // Perform default conversions. 4956 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4957 QualType ResultTy; 4958 if (OriginalTy->isAnyPointerType()) { 4959 ResultTy = OriginalTy->getPointeeType(); 4960 } else if (OriginalTy->isArrayType()) { 4961 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4962 } else { 4963 return ExprError( 4964 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4965 << Base->getSourceRange()); 4966 } 4967 // C99 6.5.2.1p1 4968 if (LowerBound) { 4969 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4970 LowerBound); 4971 if (Res.isInvalid()) 4972 return ExprError(Diag(LowerBound->getExprLoc(), 4973 diag::err_omp_typecheck_section_not_integer) 4974 << 0 << LowerBound->getSourceRange()); 4975 LowerBound = Res.get(); 4976 4977 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4978 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4979 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4980 << 0 << LowerBound->getSourceRange(); 4981 } 4982 if (Length) { 4983 auto Res = 4984 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4985 if (Res.isInvalid()) 4986 return ExprError(Diag(Length->getExprLoc(), 4987 diag::err_omp_typecheck_section_not_integer) 4988 << 1 << Length->getSourceRange()); 4989 Length = Res.get(); 4990 4991 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4992 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4993 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4994 << 1 << Length->getSourceRange(); 4995 } 4996 if (Stride) { 4997 ExprResult Res = 4998 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 4999 if (Res.isInvalid()) 5000 return ExprError(Diag(Stride->getExprLoc(), 5001 diag::err_omp_typecheck_section_not_integer) 5002 << 1 << Stride->getSourceRange()); 5003 Stride = Res.get(); 5004 5005 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5006 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5007 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5008 << 1 << Stride->getSourceRange(); 5009 } 5010 5011 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5012 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5013 // type. Note that functions are not objects, and that (in C99 parlance) 5014 // incomplete types are not object types. 5015 if (ResultTy->isFunctionType()) { 5016 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5017 << ResultTy << Base->getSourceRange(); 5018 return ExprError(); 5019 } 5020 5021 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5022 diag::err_omp_section_incomplete_type, Base)) 5023 return ExprError(); 5024 5025 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5026 Expr::EvalResult Result; 5027 if (LowerBound->EvaluateAsInt(Result, Context)) { 5028 // OpenMP 5.0, [2.1.5 Array Sections] 5029 // The array section must be a subset of the original array. 5030 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5031 if (LowerBoundValue.isNegative()) { 5032 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5033 << LowerBound->getSourceRange(); 5034 return ExprError(); 5035 } 5036 } 5037 } 5038 5039 if (Length) { 5040 Expr::EvalResult Result; 5041 if (Length->EvaluateAsInt(Result, Context)) { 5042 // OpenMP 5.0, [2.1.5 Array Sections] 5043 // The length must evaluate to non-negative integers. 5044 llvm::APSInt LengthValue = Result.Val.getInt(); 5045 if (LengthValue.isNegative()) { 5046 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5047 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5048 << Length->getSourceRange(); 5049 return ExprError(); 5050 } 5051 } 5052 } else if (ColonLocFirst.isValid() && 5053 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5054 !OriginalTy->isVariableArrayType()))) { 5055 // OpenMP 5.0, [2.1.5 Array Sections] 5056 // When the size of the array dimension is not known, the length must be 5057 // specified explicitly. 5058 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5059 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5060 return ExprError(); 5061 } 5062 5063 if (Stride) { 5064 Expr::EvalResult Result; 5065 if (Stride->EvaluateAsInt(Result, Context)) { 5066 // OpenMP 5.0, [2.1.5 Array Sections] 5067 // The stride must evaluate to a positive integer. 5068 llvm::APSInt StrideValue = Result.Val.getInt(); 5069 if (!StrideValue.isStrictlyPositive()) { 5070 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5071 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5072 << Stride->getSourceRange(); 5073 return ExprError(); 5074 } 5075 } 5076 } 5077 5078 if (!Base->getType()->isSpecificPlaceholderType( 5079 BuiltinType::OMPArraySection)) { 5080 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5081 if (Result.isInvalid()) 5082 return ExprError(); 5083 Base = Result.get(); 5084 } 5085 return new (Context) OMPArraySectionExpr( 5086 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5087 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5088 } 5089 5090 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5091 SourceLocation RParenLoc, 5092 ArrayRef<Expr *> Dims, 5093 ArrayRef<SourceRange> Brackets) { 5094 if (Base->getType()->isPlaceholderType()) { 5095 ExprResult Result = CheckPlaceholderExpr(Base); 5096 if (Result.isInvalid()) 5097 return ExprError(); 5098 Result = DefaultLvalueConversion(Result.get()); 5099 if (Result.isInvalid()) 5100 return ExprError(); 5101 Base = Result.get(); 5102 } 5103 QualType BaseTy = Base->getType(); 5104 // Delay analysis of the types/expressions if instantiation/specialization is 5105 // required. 5106 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5107 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5108 LParenLoc, RParenLoc, Dims, Brackets); 5109 if (!BaseTy->isPointerType() || 5110 (!Base->isTypeDependent() && 5111 BaseTy->getPointeeType()->isIncompleteType())) 5112 return ExprError(Diag(Base->getExprLoc(), 5113 diag::err_omp_non_pointer_type_array_shaping_base) 5114 << Base->getSourceRange()); 5115 5116 SmallVector<Expr *, 4> NewDims; 5117 bool ErrorFound = false; 5118 for (Expr *Dim : Dims) { 5119 if (Dim->getType()->isPlaceholderType()) { 5120 ExprResult Result = CheckPlaceholderExpr(Dim); 5121 if (Result.isInvalid()) { 5122 ErrorFound = true; 5123 continue; 5124 } 5125 Result = DefaultLvalueConversion(Result.get()); 5126 if (Result.isInvalid()) { 5127 ErrorFound = true; 5128 continue; 5129 } 5130 Dim = Result.get(); 5131 } 5132 if (!Dim->isTypeDependent()) { 5133 ExprResult Result = 5134 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5135 if (Result.isInvalid()) { 5136 ErrorFound = true; 5137 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5138 << Dim->getSourceRange(); 5139 continue; 5140 } 5141 Dim = Result.get(); 5142 Expr::EvalResult EvResult; 5143 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5144 // OpenMP 5.0, [2.1.4 Array Shaping] 5145 // Each si is an integral type expression that must evaluate to a 5146 // positive integer. 5147 llvm::APSInt Value = EvResult.Val.getInt(); 5148 if (!Value.isStrictlyPositive()) { 5149 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5150 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5151 << Dim->getSourceRange(); 5152 ErrorFound = true; 5153 continue; 5154 } 5155 } 5156 } 5157 NewDims.push_back(Dim); 5158 } 5159 if (ErrorFound) 5160 return ExprError(); 5161 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5162 LParenLoc, RParenLoc, NewDims, Brackets); 5163 } 5164 5165 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5166 SourceLocation LLoc, SourceLocation RLoc, 5167 ArrayRef<OMPIteratorData> Data) { 5168 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5169 bool IsCorrect = true; 5170 for (const OMPIteratorData &D : Data) { 5171 TypeSourceInfo *TInfo = nullptr; 5172 SourceLocation StartLoc; 5173 QualType DeclTy; 5174 if (!D.Type.getAsOpaquePtr()) { 5175 // OpenMP 5.0, 2.1.6 Iterators 5176 // In an iterator-specifier, if the iterator-type is not specified then 5177 // the type of that iterator is of int type. 5178 DeclTy = Context.IntTy; 5179 StartLoc = D.DeclIdentLoc; 5180 } else { 5181 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5182 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5183 } 5184 5185 bool IsDeclTyDependent = DeclTy->isDependentType() || 5186 DeclTy->containsUnexpandedParameterPack() || 5187 DeclTy->isInstantiationDependentType(); 5188 if (!IsDeclTyDependent) { 5189 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5190 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5191 // The iterator-type must be an integral or pointer type. 5192 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5193 << DeclTy; 5194 IsCorrect = false; 5195 continue; 5196 } 5197 if (DeclTy.isConstant(Context)) { 5198 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5199 // The iterator-type must not be const qualified. 5200 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5201 << DeclTy; 5202 IsCorrect = false; 5203 continue; 5204 } 5205 } 5206 5207 // Iterator declaration. 5208 assert(D.DeclIdent && "Identifier expected."); 5209 // Always try to create iterator declarator to avoid extra error messages 5210 // about unknown declarations use. 5211 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5212 D.DeclIdent, DeclTy, TInfo, SC_None); 5213 VD->setImplicit(); 5214 if (S) { 5215 // Check for conflicting previous declaration. 5216 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5217 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5218 ForVisibleRedeclaration); 5219 Previous.suppressDiagnostics(); 5220 LookupName(Previous, S); 5221 5222 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5223 /*AllowInlineNamespace=*/false); 5224 if (!Previous.empty()) { 5225 NamedDecl *Old = Previous.getRepresentativeDecl(); 5226 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5227 Diag(Old->getLocation(), diag::note_previous_definition); 5228 } else { 5229 PushOnScopeChains(VD, S); 5230 } 5231 } else { 5232 CurContext->addDecl(VD); 5233 } 5234 Expr *Begin = D.Range.Begin; 5235 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5236 ExprResult BeginRes = 5237 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5238 Begin = BeginRes.get(); 5239 } 5240 Expr *End = D.Range.End; 5241 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5242 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5243 End = EndRes.get(); 5244 } 5245 Expr *Step = D.Range.Step; 5246 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5247 if (!Step->getType()->isIntegralType(Context)) { 5248 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5249 << Step << Step->getSourceRange(); 5250 IsCorrect = false; 5251 continue; 5252 } 5253 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5254 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5255 // If the step expression of a range-specification equals zero, the 5256 // behavior is unspecified. 5257 if (Result && Result->isNullValue()) { 5258 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5259 << Step << Step->getSourceRange(); 5260 IsCorrect = false; 5261 continue; 5262 } 5263 } 5264 if (!Begin || !End || !IsCorrect) { 5265 IsCorrect = false; 5266 continue; 5267 } 5268 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5269 IDElem.IteratorDecl = VD; 5270 IDElem.AssignmentLoc = D.AssignLoc; 5271 IDElem.Range.Begin = Begin; 5272 IDElem.Range.End = End; 5273 IDElem.Range.Step = Step; 5274 IDElem.ColonLoc = D.ColonLoc; 5275 IDElem.SecondColonLoc = D.SecColonLoc; 5276 } 5277 if (!IsCorrect) { 5278 // Invalidate all created iterator declarations if error is found. 5279 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5280 if (Decl *ID = D.IteratorDecl) 5281 ID->setInvalidDecl(); 5282 } 5283 return ExprError(); 5284 } 5285 SmallVector<OMPIteratorHelperData, 4> Helpers; 5286 if (!CurContext->isDependentContext()) { 5287 // Build number of ityeration for each iteration range. 5288 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5289 // ((Begini-Stepi-1-Endi) / -Stepi); 5290 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5291 // (Endi - Begini) 5292 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5293 D.Range.Begin); 5294 if(!Res.isUsable()) { 5295 IsCorrect = false; 5296 continue; 5297 } 5298 ExprResult St, St1; 5299 if (D.Range.Step) { 5300 St = D.Range.Step; 5301 // (Endi - Begini) + Stepi 5302 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5303 if (!Res.isUsable()) { 5304 IsCorrect = false; 5305 continue; 5306 } 5307 // (Endi - Begini) + Stepi - 1 5308 Res = 5309 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5310 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5311 if (!Res.isUsable()) { 5312 IsCorrect = false; 5313 continue; 5314 } 5315 // ((Endi - Begini) + Stepi - 1) / Stepi 5316 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5317 if (!Res.isUsable()) { 5318 IsCorrect = false; 5319 continue; 5320 } 5321 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5322 // (Begini - Endi) 5323 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5324 D.Range.Begin, D.Range.End); 5325 if (!Res1.isUsable()) { 5326 IsCorrect = false; 5327 continue; 5328 } 5329 // (Begini - Endi) - Stepi 5330 Res1 = 5331 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5332 if (!Res1.isUsable()) { 5333 IsCorrect = false; 5334 continue; 5335 } 5336 // (Begini - Endi) - Stepi - 1 5337 Res1 = 5338 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5339 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5340 if (!Res1.isUsable()) { 5341 IsCorrect = false; 5342 continue; 5343 } 5344 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5345 Res1 = 5346 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5347 if (!Res1.isUsable()) { 5348 IsCorrect = false; 5349 continue; 5350 } 5351 // Stepi > 0. 5352 ExprResult CmpRes = 5353 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5354 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5355 if (!CmpRes.isUsable()) { 5356 IsCorrect = false; 5357 continue; 5358 } 5359 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5360 Res.get(), Res1.get()); 5361 if (!Res.isUsable()) { 5362 IsCorrect = false; 5363 continue; 5364 } 5365 } 5366 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5367 if (!Res.isUsable()) { 5368 IsCorrect = false; 5369 continue; 5370 } 5371 5372 // Build counter update. 5373 // Build counter. 5374 auto *CounterVD = 5375 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5376 D.IteratorDecl->getBeginLoc(), nullptr, 5377 Res.get()->getType(), nullptr, SC_None); 5378 CounterVD->setImplicit(); 5379 ExprResult RefRes = 5380 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5381 D.IteratorDecl->getBeginLoc()); 5382 // Build counter update. 5383 // I = Begini + counter * Stepi; 5384 ExprResult UpdateRes; 5385 if (D.Range.Step) { 5386 UpdateRes = CreateBuiltinBinOp( 5387 D.AssignmentLoc, BO_Mul, 5388 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5389 } else { 5390 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5391 } 5392 if (!UpdateRes.isUsable()) { 5393 IsCorrect = false; 5394 continue; 5395 } 5396 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5397 UpdateRes.get()); 5398 if (!UpdateRes.isUsable()) { 5399 IsCorrect = false; 5400 continue; 5401 } 5402 ExprResult VDRes = 5403 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5404 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5405 D.IteratorDecl->getBeginLoc()); 5406 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5407 UpdateRes.get()); 5408 if (!UpdateRes.isUsable()) { 5409 IsCorrect = false; 5410 continue; 5411 } 5412 UpdateRes = 5413 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5414 if (!UpdateRes.isUsable()) { 5415 IsCorrect = false; 5416 continue; 5417 } 5418 ExprResult CounterUpdateRes = 5419 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5420 if (!CounterUpdateRes.isUsable()) { 5421 IsCorrect = false; 5422 continue; 5423 } 5424 CounterUpdateRes = 5425 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5426 if (!CounterUpdateRes.isUsable()) { 5427 IsCorrect = false; 5428 continue; 5429 } 5430 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5431 HD.CounterVD = CounterVD; 5432 HD.Upper = Res.get(); 5433 HD.Update = UpdateRes.get(); 5434 HD.CounterUpdate = CounterUpdateRes.get(); 5435 } 5436 } else { 5437 Helpers.assign(ID.size(), {}); 5438 } 5439 if (!IsCorrect) { 5440 // Invalidate all created iterator declarations if error is found. 5441 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5442 if (Decl *ID = D.IteratorDecl) 5443 ID->setInvalidDecl(); 5444 } 5445 return ExprError(); 5446 } 5447 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5448 LLoc, RLoc, ID, Helpers); 5449 } 5450 5451 ExprResult 5452 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5453 Expr *Idx, SourceLocation RLoc) { 5454 Expr *LHSExp = Base; 5455 Expr *RHSExp = Idx; 5456 5457 ExprValueKind VK = VK_LValue; 5458 ExprObjectKind OK = OK_Ordinary; 5459 5460 // Per C++ core issue 1213, the result is an xvalue if either operand is 5461 // a non-lvalue array, and an lvalue otherwise. 5462 if (getLangOpts().CPlusPlus11) { 5463 for (auto *Op : {LHSExp, RHSExp}) { 5464 Op = Op->IgnoreImplicit(); 5465 if (Op->getType()->isArrayType() && !Op->isLValue()) 5466 VK = VK_XValue; 5467 } 5468 } 5469 5470 // Perform default conversions. 5471 if (!LHSExp->getType()->getAs<VectorType>()) { 5472 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5473 if (Result.isInvalid()) 5474 return ExprError(); 5475 LHSExp = Result.get(); 5476 } 5477 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5478 if (Result.isInvalid()) 5479 return ExprError(); 5480 RHSExp = Result.get(); 5481 5482 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5483 5484 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5485 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5486 // in the subscript position. As a result, we need to derive the array base 5487 // and index from the expression types. 5488 Expr *BaseExpr, *IndexExpr; 5489 QualType ResultType; 5490 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5491 BaseExpr = LHSExp; 5492 IndexExpr = RHSExp; 5493 ResultType = Context.DependentTy; 5494 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5495 BaseExpr = LHSExp; 5496 IndexExpr = RHSExp; 5497 ResultType = PTy->getPointeeType(); 5498 } else if (const ObjCObjectPointerType *PTy = 5499 LHSTy->getAs<ObjCObjectPointerType>()) { 5500 BaseExpr = LHSExp; 5501 IndexExpr = RHSExp; 5502 5503 // Use custom logic if this should be the pseudo-object subscript 5504 // expression. 5505 if (!LangOpts.isSubscriptPointerArithmetic()) 5506 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5507 nullptr); 5508 5509 ResultType = PTy->getPointeeType(); 5510 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5511 // Handle the uncommon case of "123[Ptr]". 5512 BaseExpr = RHSExp; 5513 IndexExpr = LHSExp; 5514 ResultType = PTy->getPointeeType(); 5515 } else if (const ObjCObjectPointerType *PTy = 5516 RHSTy->getAs<ObjCObjectPointerType>()) { 5517 // Handle the uncommon case of "123[Ptr]". 5518 BaseExpr = RHSExp; 5519 IndexExpr = LHSExp; 5520 ResultType = PTy->getPointeeType(); 5521 if (!LangOpts.isSubscriptPointerArithmetic()) { 5522 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5523 << ResultType << BaseExpr->getSourceRange(); 5524 return ExprError(); 5525 } 5526 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5527 BaseExpr = LHSExp; // vectors: V[123] 5528 IndexExpr = RHSExp; 5529 // We apply C++ DR1213 to vector subscripting too. 5530 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5531 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5532 if (Materialized.isInvalid()) 5533 return ExprError(); 5534 LHSExp = Materialized.get(); 5535 } 5536 VK = LHSExp->getValueKind(); 5537 if (VK != VK_PRValue) 5538 OK = OK_VectorComponent; 5539 5540 ResultType = VTy->getElementType(); 5541 QualType BaseType = BaseExpr->getType(); 5542 Qualifiers BaseQuals = BaseType.getQualifiers(); 5543 Qualifiers MemberQuals = ResultType.getQualifiers(); 5544 Qualifiers Combined = BaseQuals + MemberQuals; 5545 if (Combined != MemberQuals) 5546 ResultType = Context.getQualifiedType(ResultType, Combined); 5547 } else if (LHSTy->isArrayType()) { 5548 // If we see an array that wasn't promoted by 5549 // DefaultFunctionArrayLvalueConversion, it must be an array that 5550 // wasn't promoted because of the C90 rule that doesn't 5551 // allow promoting non-lvalue arrays. Warn, then 5552 // force the promotion here. 5553 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5554 << LHSExp->getSourceRange(); 5555 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5556 CK_ArrayToPointerDecay).get(); 5557 LHSTy = LHSExp->getType(); 5558 5559 BaseExpr = LHSExp; 5560 IndexExpr = RHSExp; 5561 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5562 } else if (RHSTy->isArrayType()) { 5563 // Same as previous, except for 123[f().a] case 5564 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5565 << RHSExp->getSourceRange(); 5566 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5567 CK_ArrayToPointerDecay).get(); 5568 RHSTy = RHSExp->getType(); 5569 5570 BaseExpr = RHSExp; 5571 IndexExpr = LHSExp; 5572 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5573 } else { 5574 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5575 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5576 } 5577 // C99 6.5.2.1p1 5578 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5579 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5580 << IndexExpr->getSourceRange()); 5581 5582 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5583 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5584 && !IndexExpr->isTypeDependent()) 5585 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5586 5587 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5588 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5589 // type. Note that Functions are not objects, and that (in C99 parlance) 5590 // incomplete types are not object types. 5591 if (ResultType->isFunctionType()) { 5592 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5593 << ResultType << BaseExpr->getSourceRange(); 5594 return ExprError(); 5595 } 5596 5597 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5598 // GNU extension: subscripting on pointer to void 5599 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5600 << BaseExpr->getSourceRange(); 5601 5602 // C forbids expressions of unqualified void type from being l-values. 5603 // See IsCForbiddenLValueType. 5604 if (!ResultType.hasQualifiers()) 5605 VK = VK_PRValue; 5606 } else if (!ResultType->isDependentType() && 5607 RequireCompleteSizedType( 5608 LLoc, ResultType, 5609 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5610 return ExprError(); 5611 5612 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 5613 !ResultType.isCForbiddenLValueType()); 5614 5615 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5616 FunctionScopes.size() > 1) { 5617 if (auto *TT = 5618 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5619 for (auto I = FunctionScopes.rbegin(), 5620 E = std::prev(FunctionScopes.rend()); 5621 I != E; ++I) { 5622 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5623 if (CSI == nullptr) 5624 break; 5625 DeclContext *DC = nullptr; 5626 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5627 DC = LSI->CallOperator; 5628 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5629 DC = CRSI->TheCapturedDecl; 5630 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5631 DC = BSI->TheDecl; 5632 if (DC) { 5633 if (DC->containsDecl(TT->getDecl())) 5634 break; 5635 captureVariablyModifiedType( 5636 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5637 } 5638 } 5639 } 5640 } 5641 5642 return new (Context) 5643 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5644 } 5645 5646 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5647 ParmVarDecl *Param) { 5648 if (Param->hasUnparsedDefaultArg()) { 5649 // If we've already cleared out the location for the default argument, 5650 // that means we're parsing it right now. 5651 if (!UnparsedDefaultArgLocs.count(Param)) { 5652 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5653 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5654 Param->setInvalidDecl(); 5655 return true; 5656 } 5657 5658 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5659 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5660 Diag(UnparsedDefaultArgLocs[Param], 5661 diag::note_default_argument_declared_here); 5662 return true; 5663 } 5664 5665 if (Param->hasUninstantiatedDefaultArg() && 5666 InstantiateDefaultArgument(CallLoc, FD, Param)) 5667 return true; 5668 5669 assert(Param->hasInit() && "default argument but no initializer?"); 5670 5671 // If the default expression creates temporaries, we need to 5672 // push them to the current stack of expression temporaries so they'll 5673 // be properly destroyed. 5674 // FIXME: We should really be rebuilding the default argument with new 5675 // bound temporaries; see the comment in PR5810. 5676 // We don't need to do that with block decls, though, because 5677 // blocks in default argument expression can never capture anything. 5678 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5679 // Set the "needs cleanups" bit regardless of whether there are 5680 // any explicit objects. 5681 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5682 5683 // Append all the objects to the cleanup list. Right now, this 5684 // should always be a no-op, because blocks in default argument 5685 // expressions should never be able to capture anything. 5686 assert(!Init->getNumObjects() && 5687 "default argument expression has capturing blocks?"); 5688 } 5689 5690 // We already type-checked the argument, so we know it works. 5691 // Just mark all of the declarations in this potentially-evaluated expression 5692 // as being "referenced". 5693 EnterExpressionEvaluationContext EvalContext( 5694 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5695 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5696 /*SkipLocalVariables=*/true); 5697 return false; 5698 } 5699 5700 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5701 FunctionDecl *FD, ParmVarDecl *Param) { 5702 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5703 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5704 return ExprError(); 5705 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5706 } 5707 5708 Sema::VariadicCallType 5709 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5710 Expr *Fn) { 5711 if (Proto && Proto->isVariadic()) { 5712 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5713 return VariadicConstructor; 5714 else if (Fn && Fn->getType()->isBlockPointerType()) 5715 return VariadicBlock; 5716 else if (FDecl) { 5717 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5718 if (Method->isInstance()) 5719 return VariadicMethod; 5720 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5721 return VariadicMethod; 5722 return VariadicFunction; 5723 } 5724 return VariadicDoesNotApply; 5725 } 5726 5727 namespace { 5728 class FunctionCallCCC final : public FunctionCallFilterCCC { 5729 public: 5730 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5731 unsigned NumArgs, MemberExpr *ME) 5732 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5733 FunctionName(FuncName) {} 5734 5735 bool ValidateCandidate(const TypoCorrection &candidate) override { 5736 if (!candidate.getCorrectionSpecifier() || 5737 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5738 return false; 5739 } 5740 5741 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5742 } 5743 5744 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5745 return std::make_unique<FunctionCallCCC>(*this); 5746 } 5747 5748 private: 5749 const IdentifierInfo *const FunctionName; 5750 }; 5751 } 5752 5753 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5754 FunctionDecl *FDecl, 5755 ArrayRef<Expr *> Args) { 5756 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5757 DeclarationName FuncName = FDecl->getDeclName(); 5758 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5759 5760 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5761 if (TypoCorrection Corrected = S.CorrectTypo( 5762 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5763 S.getScopeForContext(S.CurContext), nullptr, CCC, 5764 Sema::CTK_ErrorRecovery)) { 5765 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5766 if (Corrected.isOverloaded()) { 5767 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5768 OverloadCandidateSet::iterator Best; 5769 for (NamedDecl *CD : Corrected) { 5770 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5771 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5772 OCS); 5773 } 5774 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5775 case OR_Success: 5776 ND = Best->FoundDecl; 5777 Corrected.setCorrectionDecl(ND); 5778 break; 5779 default: 5780 break; 5781 } 5782 } 5783 ND = ND->getUnderlyingDecl(); 5784 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5785 return Corrected; 5786 } 5787 } 5788 return TypoCorrection(); 5789 } 5790 5791 /// ConvertArgumentsForCall - Converts the arguments specified in 5792 /// Args/NumArgs to the parameter types of the function FDecl with 5793 /// function prototype Proto. Call is the call expression itself, and 5794 /// Fn is the function expression. For a C++ member function, this 5795 /// routine does not attempt to convert the object argument. Returns 5796 /// true if the call is ill-formed. 5797 bool 5798 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5799 FunctionDecl *FDecl, 5800 const FunctionProtoType *Proto, 5801 ArrayRef<Expr *> Args, 5802 SourceLocation RParenLoc, 5803 bool IsExecConfig) { 5804 // Bail out early if calling a builtin with custom typechecking. 5805 if (FDecl) 5806 if (unsigned ID = FDecl->getBuiltinID()) 5807 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5808 return false; 5809 5810 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5811 // assignment, to the types of the corresponding parameter, ... 5812 unsigned NumParams = Proto->getNumParams(); 5813 bool Invalid = false; 5814 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5815 unsigned FnKind = Fn->getType()->isBlockPointerType() 5816 ? 1 /* block */ 5817 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5818 : 0 /* function */); 5819 5820 // If too few arguments are available (and we don't have default 5821 // arguments for the remaining parameters), don't make the call. 5822 if (Args.size() < NumParams) { 5823 if (Args.size() < MinArgs) { 5824 TypoCorrection TC; 5825 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5826 unsigned diag_id = 5827 MinArgs == NumParams && !Proto->isVariadic() 5828 ? diag::err_typecheck_call_too_few_args_suggest 5829 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5830 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5831 << static_cast<unsigned>(Args.size()) 5832 << TC.getCorrectionRange()); 5833 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5834 Diag(RParenLoc, 5835 MinArgs == NumParams && !Proto->isVariadic() 5836 ? diag::err_typecheck_call_too_few_args_one 5837 : diag::err_typecheck_call_too_few_args_at_least_one) 5838 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5839 else 5840 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5841 ? diag::err_typecheck_call_too_few_args 5842 : diag::err_typecheck_call_too_few_args_at_least) 5843 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5844 << Fn->getSourceRange(); 5845 5846 // Emit the location of the prototype. 5847 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5848 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5849 5850 return true; 5851 } 5852 // We reserve space for the default arguments when we create 5853 // the call expression, before calling ConvertArgumentsForCall. 5854 assert((Call->getNumArgs() == NumParams) && 5855 "We should have reserved space for the default arguments before!"); 5856 } 5857 5858 // If too many are passed and not variadic, error on the extras and drop 5859 // them. 5860 if (Args.size() > NumParams) { 5861 if (!Proto->isVariadic()) { 5862 TypoCorrection TC; 5863 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5864 unsigned diag_id = 5865 MinArgs == NumParams && !Proto->isVariadic() 5866 ? diag::err_typecheck_call_too_many_args_suggest 5867 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5868 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5869 << static_cast<unsigned>(Args.size()) 5870 << TC.getCorrectionRange()); 5871 } else if (NumParams == 1 && FDecl && 5872 FDecl->getParamDecl(0)->getDeclName()) 5873 Diag(Args[NumParams]->getBeginLoc(), 5874 MinArgs == NumParams 5875 ? diag::err_typecheck_call_too_many_args_one 5876 : diag::err_typecheck_call_too_many_args_at_most_one) 5877 << FnKind << FDecl->getParamDecl(0) 5878 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5879 << SourceRange(Args[NumParams]->getBeginLoc(), 5880 Args.back()->getEndLoc()); 5881 else 5882 Diag(Args[NumParams]->getBeginLoc(), 5883 MinArgs == NumParams 5884 ? diag::err_typecheck_call_too_many_args 5885 : diag::err_typecheck_call_too_many_args_at_most) 5886 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5887 << Fn->getSourceRange() 5888 << SourceRange(Args[NumParams]->getBeginLoc(), 5889 Args.back()->getEndLoc()); 5890 5891 // Emit the location of the prototype. 5892 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5893 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5894 5895 // This deletes the extra arguments. 5896 Call->shrinkNumArgs(NumParams); 5897 return true; 5898 } 5899 } 5900 SmallVector<Expr *, 8> AllArgs; 5901 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5902 5903 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5904 AllArgs, CallType); 5905 if (Invalid) 5906 return true; 5907 unsigned TotalNumArgs = AllArgs.size(); 5908 for (unsigned i = 0; i < TotalNumArgs; ++i) 5909 Call->setArg(i, AllArgs[i]); 5910 5911 Call->computeDependence(); 5912 return false; 5913 } 5914 5915 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5916 const FunctionProtoType *Proto, 5917 unsigned FirstParam, ArrayRef<Expr *> Args, 5918 SmallVectorImpl<Expr *> &AllArgs, 5919 VariadicCallType CallType, bool AllowExplicit, 5920 bool IsListInitialization) { 5921 unsigned NumParams = Proto->getNumParams(); 5922 bool Invalid = false; 5923 size_t ArgIx = 0; 5924 // Continue to check argument types (even if we have too few/many args). 5925 for (unsigned i = FirstParam; i < NumParams; i++) { 5926 QualType ProtoArgType = Proto->getParamType(i); 5927 5928 Expr *Arg; 5929 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5930 if (ArgIx < Args.size()) { 5931 Arg = Args[ArgIx++]; 5932 5933 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5934 diag::err_call_incomplete_argument, Arg)) 5935 return true; 5936 5937 // Strip the unbridged-cast placeholder expression off, if applicable. 5938 bool CFAudited = false; 5939 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5940 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5941 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5942 Arg = stripARCUnbridgedCast(Arg); 5943 else if (getLangOpts().ObjCAutoRefCount && 5944 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5945 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5946 CFAudited = true; 5947 5948 if (Proto->getExtParameterInfo(i).isNoEscape() && 5949 ProtoArgType->isBlockPointerType()) 5950 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5951 BE->getBlockDecl()->setDoesNotEscape(); 5952 5953 InitializedEntity Entity = 5954 Param ? InitializedEntity::InitializeParameter(Context, Param, 5955 ProtoArgType) 5956 : InitializedEntity::InitializeParameter( 5957 Context, ProtoArgType, Proto->isParamConsumed(i)); 5958 5959 // Remember that parameter belongs to a CF audited API. 5960 if (CFAudited) 5961 Entity.setParameterCFAudited(); 5962 5963 ExprResult ArgE = PerformCopyInitialization( 5964 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5965 if (ArgE.isInvalid()) 5966 return true; 5967 5968 Arg = ArgE.getAs<Expr>(); 5969 } else { 5970 assert(Param && "can't use default arguments without a known callee"); 5971 5972 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5973 if (ArgExpr.isInvalid()) 5974 return true; 5975 5976 Arg = ArgExpr.getAs<Expr>(); 5977 } 5978 5979 // Check for array bounds violations for each argument to the call. This 5980 // check only triggers warnings when the argument isn't a more complex Expr 5981 // with its own checking, such as a BinaryOperator. 5982 CheckArrayAccess(Arg); 5983 5984 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5985 CheckStaticArrayArgument(CallLoc, Param, Arg); 5986 5987 AllArgs.push_back(Arg); 5988 } 5989 5990 // If this is a variadic call, handle args passed through "...". 5991 if (CallType != VariadicDoesNotApply) { 5992 // Assume that extern "C" functions with variadic arguments that 5993 // return __unknown_anytype aren't *really* variadic. 5994 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5995 FDecl->isExternC()) { 5996 for (Expr *A : Args.slice(ArgIx)) { 5997 QualType paramType; // ignored 5998 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5999 Invalid |= arg.isInvalid(); 6000 AllArgs.push_back(arg.get()); 6001 } 6002 6003 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6004 } else { 6005 for (Expr *A : Args.slice(ArgIx)) { 6006 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6007 Invalid |= Arg.isInvalid(); 6008 AllArgs.push_back(Arg.get()); 6009 } 6010 } 6011 6012 // Check for array bounds violations. 6013 for (Expr *A : Args.slice(ArgIx)) 6014 CheckArrayAccess(A); 6015 } 6016 return Invalid; 6017 } 6018 6019 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6020 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6021 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6022 TL = DTL.getOriginalLoc(); 6023 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6024 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6025 << ATL.getLocalSourceRange(); 6026 } 6027 6028 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6029 /// array parameter, check that it is non-null, and that if it is formed by 6030 /// array-to-pointer decay, the underlying array is sufficiently large. 6031 /// 6032 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6033 /// array type derivation, then for each call to the function, the value of the 6034 /// corresponding actual argument shall provide access to the first element of 6035 /// an array with at least as many elements as specified by the size expression. 6036 void 6037 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6038 ParmVarDecl *Param, 6039 const Expr *ArgExpr) { 6040 // Static array parameters are not supported in C++. 6041 if (!Param || getLangOpts().CPlusPlus) 6042 return; 6043 6044 QualType OrigTy = Param->getOriginalType(); 6045 6046 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6047 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6048 return; 6049 6050 if (ArgExpr->isNullPointerConstant(Context, 6051 Expr::NPC_NeverValueDependent)) { 6052 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6053 DiagnoseCalleeStaticArrayParam(*this, Param); 6054 return; 6055 } 6056 6057 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6058 if (!CAT) 6059 return; 6060 6061 const ConstantArrayType *ArgCAT = 6062 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6063 if (!ArgCAT) 6064 return; 6065 6066 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6067 ArgCAT->getElementType())) { 6068 if (ArgCAT->getSize().ult(CAT->getSize())) { 6069 Diag(CallLoc, diag::warn_static_array_too_small) 6070 << ArgExpr->getSourceRange() 6071 << (unsigned)ArgCAT->getSize().getZExtValue() 6072 << (unsigned)CAT->getSize().getZExtValue() << 0; 6073 DiagnoseCalleeStaticArrayParam(*this, Param); 6074 } 6075 return; 6076 } 6077 6078 Optional<CharUnits> ArgSize = 6079 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6080 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6081 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6082 Diag(CallLoc, diag::warn_static_array_too_small) 6083 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6084 << (unsigned)ParmSize->getQuantity() << 1; 6085 DiagnoseCalleeStaticArrayParam(*this, Param); 6086 } 6087 } 6088 6089 /// Given a function expression of unknown-any type, try to rebuild it 6090 /// to have a function type. 6091 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6092 6093 /// Is the given type a placeholder that we need to lower out 6094 /// immediately during argument processing? 6095 static bool isPlaceholderToRemoveAsArg(QualType type) { 6096 // Placeholders are never sugared. 6097 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6098 if (!placeholder) return false; 6099 6100 switch (placeholder->getKind()) { 6101 // Ignore all the non-placeholder types. 6102 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6103 case BuiltinType::Id: 6104 #include "clang/Basic/OpenCLImageTypes.def" 6105 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6106 case BuiltinType::Id: 6107 #include "clang/Basic/OpenCLExtensionTypes.def" 6108 // In practice we'll never use this, since all SVE types are sugared 6109 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6110 #define SVE_TYPE(Name, Id, SingletonId) \ 6111 case BuiltinType::Id: 6112 #include "clang/Basic/AArch64SVEACLETypes.def" 6113 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6114 case BuiltinType::Id: 6115 #include "clang/Basic/PPCTypes.def" 6116 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6117 #include "clang/Basic/RISCVVTypes.def" 6118 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6119 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6120 #include "clang/AST/BuiltinTypes.def" 6121 return false; 6122 6123 // We cannot lower out overload sets; they might validly be resolved 6124 // by the call machinery. 6125 case BuiltinType::Overload: 6126 return false; 6127 6128 // Unbridged casts in ARC can be handled in some call positions and 6129 // should be left in place. 6130 case BuiltinType::ARCUnbridgedCast: 6131 return false; 6132 6133 // Pseudo-objects should be converted as soon as possible. 6134 case BuiltinType::PseudoObject: 6135 return true; 6136 6137 // The debugger mode could theoretically but currently does not try 6138 // to resolve unknown-typed arguments based on known parameter types. 6139 case BuiltinType::UnknownAny: 6140 return true; 6141 6142 // These are always invalid as call arguments and should be reported. 6143 case BuiltinType::BoundMember: 6144 case BuiltinType::BuiltinFn: 6145 case BuiltinType::IncompleteMatrixIdx: 6146 case BuiltinType::OMPArraySection: 6147 case BuiltinType::OMPArrayShaping: 6148 case BuiltinType::OMPIterator: 6149 return true; 6150 6151 } 6152 llvm_unreachable("bad builtin type kind"); 6153 } 6154 6155 /// Check an argument list for placeholders that we won't try to 6156 /// handle later. 6157 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6158 // Apply this processing to all the arguments at once instead of 6159 // dying at the first failure. 6160 bool hasInvalid = false; 6161 for (size_t i = 0, e = args.size(); i != e; i++) { 6162 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6163 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6164 if (result.isInvalid()) hasInvalid = true; 6165 else args[i] = result.get(); 6166 } 6167 } 6168 return hasInvalid; 6169 } 6170 6171 /// If a builtin function has a pointer argument with no explicit address 6172 /// space, then it should be able to accept a pointer to any address 6173 /// space as input. In order to do this, we need to replace the 6174 /// standard builtin declaration with one that uses the same address space 6175 /// as the call. 6176 /// 6177 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6178 /// it does not contain any pointer arguments without 6179 /// an address space qualifer. Otherwise the rewritten 6180 /// FunctionDecl is returned. 6181 /// TODO: Handle pointer return types. 6182 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6183 FunctionDecl *FDecl, 6184 MultiExprArg ArgExprs) { 6185 6186 QualType DeclType = FDecl->getType(); 6187 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6188 6189 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6190 ArgExprs.size() < FT->getNumParams()) 6191 return nullptr; 6192 6193 bool NeedsNewDecl = false; 6194 unsigned i = 0; 6195 SmallVector<QualType, 8> OverloadParams; 6196 6197 for (QualType ParamType : FT->param_types()) { 6198 6199 // Convert array arguments to pointer to simplify type lookup. 6200 ExprResult ArgRes = 6201 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6202 if (ArgRes.isInvalid()) 6203 return nullptr; 6204 Expr *Arg = ArgRes.get(); 6205 QualType ArgType = Arg->getType(); 6206 if (!ParamType->isPointerType() || 6207 ParamType.hasAddressSpace() || 6208 !ArgType->isPointerType() || 6209 !ArgType->getPointeeType().hasAddressSpace()) { 6210 OverloadParams.push_back(ParamType); 6211 continue; 6212 } 6213 6214 QualType PointeeType = ParamType->getPointeeType(); 6215 if (PointeeType.hasAddressSpace()) 6216 continue; 6217 6218 NeedsNewDecl = true; 6219 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6220 6221 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6222 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6223 } 6224 6225 if (!NeedsNewDecl) 6226 return nullptr; 6227 6228 FunctionProtoType::ExtProtoInfo EPI; 6229 EPI.Variadic = FT->isVariadic(); 6230 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6231 OverloadParams, EPI); 6232 DeclContext *Parent = FDecl->getParent(); 6233 FunctionDecl *OverloadDecl = FunctionDecl::Create( 6234 Context, Parent, FDecl->getLocation(), FDecl->getLocation(), 6235 FDecl->getIdentifier(), OverloadTy, 6236 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), 6237 false, 6238 /*hasPrototype=*/true); 6239 SmallVector<ParmVarDecl*, 16> Params; 6240 FT = cast<FunctionProtoType>(OverloadTy); 6241 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6242 QualType ParamType = FT->getParamType(i); 6243 ParmVarDecl *Parm = 6244 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6245 SourceLocation(), nullptr, ParamType, 6246 /*TInfo=*/nullptr, SC_None, nullptr); 6247 Parm->setScopeInfo(0, i); 6248 Params.push_back(Parm); 6249 } 6250 OverloadDecl->setParams(Params); 6251 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6252 return OverloadDecl; 6253 } 6254 6255 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6256 FunctionDecl *Callee, 6257 MultiExprArg ArgExprs) { 6258 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6259 // similar attributes) really don't like it when functions are called with an 6260 // invalid number of args. 6261 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6262 /*PartialOverloading=*/false) && 6263 !Callee->isVariadic()) 6264 return; 6265 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6266 return; 6267 6268 if (const EnableIfAttr *Attr = 6269 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6270 S.Diag(Fn->getBeginLoc(), 6271 isa<CXXMethodDecl>(Callee) 6272 ? diag::err_ovl_no_viable_member_function_in_call 6273 : diag::err_ovl_no_viable_function_in_call) 6274 << Callee << Callee->getSourceRange(); 6275 S.Diag(Callee->getLocation(), 6276 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6277 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6278 return; 6279 } 6280 } 6281 6282 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6283 const UnresolvedMemberExpr *const UME, Sema &S) { 6284 6285 const auto GetFunctionLevelDCIfCXXClass = 6286 [](Sema &S) -> const CXXRecordDecl * { 6287 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6288 if (!DC || !DC->getParent()) 6289 return nullptr; 6290 6291 // If the call to some member function was made from within a member 6292 // function body 'M' return return 'M's parent. 6293 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6294 return MD->getParent()->getCanonicalDecl(); 6295 // else the call was made from within a default member initializer of a 6296 // class, so return the class. 6297 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6298 return RD->getCanonicalDecl(); 6299 return nullptr; 6300 }; 6301 // If our DeclContext is neither a member function nor a class (in the 6302 // case of a lambda in a default member initializer), we can't have an 6303 // enclosing 'this'. 6304 6305 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6306 if (!CurParentClass) 6307 return false; 6308 6309 // The naming class for implicit member functions call is the class in which 6310 // name lookup starts. 6311 const CXXRecordDecl *const NamingClass = 6312 UME->getNamingClass()->getCanonicalDecl(); 6313 assert(NamingClass && "Must have naming class even for implicit access"); 6314 6315 // If the unresolved member functions were found in a 'naming class' that is 6316 // related (either the same or derived from) to the class that contains the 6317 // member function that itself contained the implicit member access. 6318 6319 return CurParentClass == NamingClass || 6320 CurParentClass->isDerivedFrom(NamingClass); 6321 } 6322 6323 static void 6324 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6325 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6326 6327 if (!UME) 6328 return; 6329 6330 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6331 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6332 // already been captured, or if this is an implicit member function call (if 6333 // it isn't, an attempt to capture 'this' should already have been made). 6334 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6335 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6336 return; 6337 6338 // Check if the naming class in which the unresolved members were found is 6339 // related (same as or is a base of) to the enclosing class. 6340 6341 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6342 return; 6343 6344 6345 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6346 // If the enclosing function is not dependent, then this lambda is 6347 // capture ready, so if we can capture this, do so. 6348 if (!EnclosingFunctionCtx->isDependentContext()) { 6349 // If the current lambda and all enclosing lambdas can capture 'this' - 6350 // then go ahead and capture 'this' (since our unresolved overload set 6351 // contains at least one non-static member function). 6352 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6353 S.CheckCXXThisCapture(CallLoc); 6354 } else if (S.CurContext->isDependentContext()) { 6355 // ... since this is an implicit member reference, that might potentially 6356 // involve a 'this' capture, mark 'this' for potential capture in 6357 // enclosing lambdas. 6358 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6359 CurLSI->addPotentialThisCapture(CallLoc); 6360 } 6361 } 6362 6363 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6364 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6365 Expr *ExecConfig) { 6366 ExprResult Call = 6367 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6368 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6369 if (Call.isInvalid()) 6370 return Call; 6371 6372 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6373 // language modes. 6374 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6375 if (ULE->hasExplicitTemplateArgs() && 6376 ULE->decls_begin() == ULE->decls_end()) { 6377 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6378 ? diag::warn_cxx17_compat_adl_only_template_id 6379 : diag::ext_adl_only_template_id) 6380 << ULE->getName(); 6381 } 6382 } 6383 6384 if (LangOpts.OpenMP) 6385 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6386 ExecConfig); 6387 6388 return Call; 6389 } 6390 6391 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6392 /// This provides the location of the left/right parens and a list of comma 6393 /// locations. 6394 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6395 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6396 Expr *ExecConfig, bool IsExecConfig, 6397 bool AllowRecovery) { 6398 // Since this might be a postfix expression, get rid of ParenListExprs. 6399 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6400 if (Result.isInvalid()) return ExprError(); 6401 Fn = Result.get(); 6402 6403 if (checkArgsForPlaceholders(*this, ArgExprs)) 6404 return ExprError(); 6405 6406 if (getLangOpts().CPlusPlus) { 6407 // If this is a pseudo-destructor expression, build the call immediately. 6408 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6409 if (!ArgExprs.empty()) { 6410 // Pseudo-destructor calls should not have any arguments. 6411 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6412 << FixItHint::CreateRemoval( 6413 SourceRange(ArgExprs.front()->getBeginLoc(), 6414 ArgExprs.back()->getEndLoc())); 6415 } 6416 6417 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6418 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6419 } 6420 if (Fn->getType() == Context.PseudoObjectTy) { 6421 ExprResult result = CheckPlaceholderExpr(Fn); 6422 if (result.isInvalid()) return ExprError(); 6423 Fn = result.get(); 6424 } 6425 6426 // Determine whether this is a dependent call inside a C++ template, 6427 // in which case we won't do any semantic analysis now. 6428 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6429 if (ExecConfig) { 6430 return CUDAKernelCallExpr::Create(Context, Fn, 6431 cast<CallExpr>(ExecConfig), ArgExprs, 6432 Context.DependentTy, VK_PRValue, 6433 RParenLoc, CurFPFeatureOverrides()); 6434 } else { 6435 6436 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6437 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6438 Fn->getBeginLoc()); 6439 6440 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6441 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6442 } 6443 } 6444 6445 // Determine whether this is a call to an object (C++ [over.call.object]). 6446 if (Fn->getType()->isRecordType()) 6447 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6448 RParenLoc); 6449 6450 if (Fn->getType() == Context.UnknownAnyTy) { 6451 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6452 if (result.isInvalid()) return ExprError(); 6453 Fn = result.get(); 6454 } 6455 6456 if (Fn->getType() == Context.BoundMemberTy) { 6457 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6458 RParenLoc, ExecConfig, IsExecConfig, 6459 AllowRecovery); 6460 } 6461 } 6462 6463 // Check for overloaded calls. This can happen even in C due to extensions. 6464 if (Fn->getType() == Context.OverloadTy) { 6465 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6466 6467 // We aren't supposed to apply this logic if there's an '&' involved. 6468 if (!find.HasFormOfMemberPointer) { 6469 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6470 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6471 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6472 OverloadExpr *ovl = find.Expression; 6473 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6474 return BuildOverloadedCallExpr( 6475 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6476 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6477 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6478 RParenLoc, ExecConfig, IsExecConfig, 6479 AllowRecovery); 6480 } 6481 } 6482 6483 // If we're directly calling a function, get the appropriate declaration. 6484 if (Fn->getType() == Context.UnknownAnyTy) { 6485 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6486 if (result.isInvalid()) return ExprError(); 6487 Fn = result.get(); 6488 } 6489 6490 Expr *NakedFn = Fn->IgnoreParens(); 6491 6492 bool CallingNDeclIndirectly = false; 6493 NamedDecl *NDecl = nullptr; 6494 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6495 if (UnOp->getOpcode() == UO_AddrOf) { 6496 CallingNDeclIndirectly = true; 6497 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6498 } 6499 } 6500 6501 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6502 NDecl = DRE->getDecl(); 6503 6504 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6505 if (FDecl && FDecl->getBuiltinID()) { 6506 // Rewrite the function decl for this builtin by replacing parameters 6507 // with no explicit address space with the address space of the arguments 6508 // in ArgExprs. 6509 if ((FDecl = 6510 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6511 NDecl = FDecl; 6512 Fn = DeclRefExpr::Create( 6513 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6514 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6515 nullptr, DRE->isNonOdrUse()); 6516 } 6517 } 6518 } else if (isa<MemberExpr>(NakedFn)) 6519 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6520 6521 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6522 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6523 FD, /*Complain=*/true, Fn->getBeginLoc())) 6524 return ExprError(); 6525 6526 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6527 6528 // If this expression is a call to a builtin function in HIP device 6529 // compilation, allow a pointer-type argument to default address space to be 6530 // passed as a pointer-type parameter to a non-default address space. 6531 // If Arg is declared in the default address space and Param is declared 6532 // in a non-default address space, perform an implicit address space cast to 6533 // the parameter type. 6534 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && 6535 FD->getBuiltinID()) { 6536 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) { 6537 ParmVarDecl *Param = FD->getParamDecl(Idx); 6538 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || 6539 !ArgExprs[Idx]->getType()->isPointerType()) 6540 continue; 6541 6542 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); 6543 auto ArgTy = ArgExprs[Idx]->getType(); 6544 auto ArgPtTy = ArgTy->getPointeeType(); 6545 auto ArgAS = ArgPtTy.getAddressSpace(); 6546 6547 // Only allow implicit casting from a non-default address space pointee 6548 // type to a default address space pointee type 6549 if (ArgAS != LangAS::Default || ParamAS == LangAS::Default) 6550 continue; 6551 6552 // First, ensure that the Arg is an RValue. 6553 if (ArgExprs[Idx]->isGLValue()) { 6554 ArgExprs[Idx] = ImplicitCastExpr::Create( 6555 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx], 6556 nullptr, VK_PRValue, FPOptionsOverride()); 6557 } 6558 6559 // Construct a new arg type with address space of Param 6560 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); 6561 ArgPtQuals.setAddressSpace(ParamAS); 6562 auto NewArgPtTy = 6563 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); 6564 auto NewArgTy = 6565 Context.getQualifiedType(Context.getPointerType(NewArgPtTy), 6566 ArgTy.getQualifiers()); 6567 6568 // Finally perform an implicit address space cast 6569 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, 6570 CK_AddressSpaceConversion) 6571 .get(); 6572 } 6573 } 6574 } 6575 6576 if (Context.isDependenceAllowed() && 6577 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6578 assert(!getLangOpts().CPlusPlus); 6579 assert((Fn->containsErrors() || 6580 llvm::any_of(ArgExprs, 6581 [](clang::Expr *E) { return E->containsErrors(); })) && 6582 "should only occur in error-recovery path."); 6583 QualType ReturnType = 6584 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6585 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6586 : Context.DependentTy; 6587 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6588 Expr::getValueKindForType(ReturnType), RParenLoc, 6589 CurFPFeatureOverrides()); 6590 } 6591 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6592 ExecConfig, IsExecConfig); 6593 } 6594 6595 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id 6596 // with the specified CallArgs 6597 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 6598 MultiExprArg CallArgs) { 6599 StringRef Name = Context.BuiltinInfo.getName(Id); 6600 LookupResult R(*this, &Context.Idents.get(Name), Loc, 6601 Sema::LookupOrdinaryName); 6602 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); 6603 6604 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); 6605 assert(BuiltInDecl && "failed to find builtin declaration"); 6606 6607 ExprResult DeclRef = 6608 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); 6609 assert(DeclRef.isUsable() && "Builtin reference cannot fail"); 6610 6611 ExprResult Call = 6612 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); 6613 6614 assert(!Call.isInvalid() && "Call to builtin cannot fail!"); 6615 return Call.get(); 6616 } 6617 6618 /// Parse a __builtin_astype expression. 6619 /// 6620 /// __builtin_astype( value, dst type ) 6621 /// 6622 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6623 SourceLocation BuiltinLoc, 6624 SourceLocation RParenLoc) { 6625 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6626 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6627 } 6628 6629 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6630 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6631 SourceLocation BuiltinLoc, 6632 SourceLocation RParenLoc) { 6633 ExprValueKind VK = VK_PRValue; 6634 ExprObjectKind OK = OK_Ordinary; 6635 QualType SrcTy = E->getType(); 6636 if (!SrcTy->isDependentType() && 6637 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6638 return ExprError( 6639 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6640 << DestTy << SrcTy << E->getSourceRange()); 6641 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6642 } 6643 6644 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6645 /// provided arguments. 6646 /// 6647 /// __builtin_convertvector( value, dst type ) 6648 /// 6649 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6650 SourceLocation BuiltinLoc, 6651 SourceLocation RParenLoc) { 6652 TypeSourceInfo *TInfo; 6653 GetTypeFromParser(ParsedDestTy, &TInfo); 6654 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6655 } 6656 6657 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6658 /// i.e. an expression not of \p OverloadTy. The expression should 6659 /// unary-convert to an expression of function-pointer or 6660 /// block-pointer type. 6661 /// 6662 /// \param NDecl the declaration being called, if available 6663 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6664 SourceLocation LParenLoc, 6665 ArrayRef<Expr *> Args, 6666 SourceLocation RParenLoc, Expr *Config, 6667 bool IsExecConfig, ADLCallKind UsesADL) { 6668 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6669 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6670 6671 // Functions with 'interrupt' attribute cannot be called directly. 6672 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6673 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6674 return ExprError(); 6675 } 6676 6677 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6678 // so there's some risk when calling out to non-interrupt handler functions 6679 // that the callee might not preserve them. This is easy to diagnose here, 6680 // but can be very challenging to debug. 6681 // Likewise, X86 interrupt handlers may only call routines with attribute 6682 // no_caller_saved_registers since there is no efficient way to 6683 // save and restore the non-GPR state. 6684 if (auto *Caller = getCurFunctionDecl()) { 6685 if (Caller->hasAttr<ARMInterruptAttr>()) { 6686 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6687 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6688 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6689 if (FDecl) 6690 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6691 } 6692 } 6693 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6694 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6695 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6696 if (FDecl) 6697 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6698 } 6699 } 6700 6701 // Promote the function operand. 6702 // We special-case function promotion here because we only allow promoting 6703 // builtin functions to function pointers in the callee of a call. 6704 ExprResult Result; 6705 QualType ResultTy; 6706 if (BuiltinID && 6707 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6708 // Extract the return type from the (builtin) function pointer type. 6709 // FIXME Several builtins still have setType in 6710 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6711 // Builtins.def to ensure they are correct before removing setType calls. 6712 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6713 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6714 ResultTy = FDecl->getCallResultType(); 6715 } else { 6716 Result = CallExprUnaryConversions(Fn); 6717 ResultTy = Context.BoolTy; 6718 } 6719 if (Result.isInvalid()) 6720 return ExprError(); 6721 Fn = Result.get(); 6722 6723 // Check for a valid function type, but only if it is not a builtin which 6724 // requires custom type checking. These will be handled by 6725 // CheckBuiltinFunctionCall below just after creation of the call expression. 6726 const FunctionType *FuncT = nullptr; 6727 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6728 retry: 6729 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6730 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6731 // have type pointer to function". 6732 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6733 if (!FuncT) 6734 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6735 << Fn->getType() << Fn->getSourceRange()); 6736 } else if (const BlockPointerType *BPT = 6737 Fn->getType()->getAs<BlockPointerType>()) { 6738 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6739 } else { 6740 // Handle calls to expressions of unknown-any type. 6741 if (Fn->getType() == Context.UnknownAnyTy) { 6742 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6743 if (rewrite.isInvalid()) 6744 return ExprError(); 6745 Fn = rewrite.get(); 6746 goto retry; 6747 } 6748 6749 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6750 << Fn->getType() << Fn->getSourceRange()); 6751 } 6752 } 6753 6754 // Get the number of parameters in the function prototype, if any. 6755 // We will allocate space for max(Args.size(), NumParams) arguments 6756 // in the call expression. 6757 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6758 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6759 6760 CallExpr *TheCall; 6761 if (Config) { 6762 assert(UsesADL == ADLCallKind::NotADL && 6763 "CUDAKernelCallExpr should not use ADL"); 6764 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6765 Args, ResultTy, VK_PRValue, RParenLoc, 6766 CurFPFeatureOverrides(), NumParams); 6767 } else { 6768 TheCall = 6769 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6770 CurFPFeatureOverrides(), NumParams, UsesADL); 6771 } 6772 6773 if (!Context.isDependenceAllowed()) { 6774 // Forget about the nulled arguments since typo correction 6775 // do not handle them well. 6776 TheCall->shrinkNumArgs(Args.size()); 6777 // C cannot always handle TypoExpr nodes in builtin calls and direct 6778 // function calls as their argument checking don't necessarily handle 6779 // dependent types properly, so make sure any TypoExprs have been 6780 // dealt with. 6781 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6782 if (!Result.isUsable()) return ExprError(); 6783 CallExpr *TheOldCall = TheCall; 6784 TheCall = dyn_cast<CallExpr>(Result.get()); 6785 bool CorrectedTypos = TheCall != TheOldCall; 6786 if (!TheCall) return Result; 6787 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6788 6789 // A new call expression node was created if some typos were corrected. 6790 // However it may not have been constructed with enough storage. In this 6791 // case, rebuild the node with enough storage. The waste of space is 6792 // immaterial since this only happens when some typos were corrected. 6793 if (CorrectedTypos && Args.size() < NumParams) { 6794 if (Config) 6795 TheCall = CUDAKernelCallExpr::Create( 6796 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 6797 RParenLoc, CurFPFeatureOverrides(), NumParams); 6798 else 6799 TheCall = 6800 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6801 CurFPFeatureOverrides(), NumParams, UsesADL); 6802 } 6803 // We can now handle the nulled arguments for the default arguments. 6804 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6805 } 6806 6807 // Bail out early if calling a builtin with custom type checking. 6808 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6809 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6810 6811 if (getLangOpts().CUDA) { 6812 if (Config) { 6813 // CUDA: Kernel calls must be to global functions 6814 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6815 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6816 << FDecl << Fn->getSourceRange()); 6817 6818 // CUDA: Kernel function must have 'void' return type 6819 if (!FuncT->getReturnType()->isVoidType() && 6820 !FuncT->getReturnType()->getAs<AutoType>() && 6821 !FuncT->getReturnType()->isInstantiationDependentType()) 6822 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6823 << Fn->getType() << Fn->getSourceRange()); 6824 } else { 6825 // CUDA: Calls to global functions must be configured 6826 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6827 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6828 << FDecl << Fn->getSourceRange()); 6829 } 6830 } 6831 6832 // Check for a valid return type 6833 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6834 FDecl)) 6835 return ExprError(); 6836 6837 // We know the result type of the call, set it. 6838 TheCall->setType(FuncT->getCallResultType(Context)); 6839 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6840 6841 if (Proto) { 6842 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6843 IsExecConfig)) 6844 return ExprError(); 6845 } else { 6846 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6847 6848 if (FDecl) { 6849 // Check if we have too few/too many template arguments, based 6850 // on our knowledge of the function definition. 6851 const FunctionDecl *Def = nullptr; 6852 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6853 Proto = Def->getType()->getAs<FunctionProtoType>(); 6854 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6855 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6856 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6857 } 6858 6859 // If the function we're calling isn't a function prototype, but we have 6860 // a function prototype from a prior declaratiom, use that prototype. 6861 if (!FDecl->hasPrototype()) 6862 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6863 } 6864 6865 // Promote the arguments (C99 6.5.2.2p6). 6866 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6867 Expr *Arg = Args[i]; 6868 6869 if (Proto && i < Proto->getNumParams()) { 6870 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6871 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6872 ExprResult ArgE = 6873 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6874 if (ArgE.isInvalid()) 6875 return true; 6876 6877 Arg = ArgE.getAs<Expr>(); 6878 6879 } else { 6880 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6881 6882 if (ArgE.isInvalid()) 6883 return true; 6884 6885 Arg = ArgE.getAs<Expr>(); 6886 } 6887 6888 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6889 diag::err_call_incomplete_argument, Arg)) 6890 return ExprError(); 6891 6892 TheCall->setArg(i, Arg); 6893 } 6894 TheCall->computeDependence(); 6895 } 6896 6897 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6898 if (!Method->isStatic()) 6899 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6900 << Fn->getSourceRange()); 6901 6902 // Check for sentinels 6903 if (NDecl) 6904 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6905 6906 // Warn for unions passing across security boundary (CMSE). 6907 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6908 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6909 if (const auto *RT = 6910 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6911 if (RT->getDecl()->isOrContainsUnion()) 6912 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6913 << 0 << i; 6914 } 6915 } 6916 } 6917 6918 // Do special checking on direct calls to functions. 6919 if (FDecl) { 6920 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6921 return ExprError(); 6922 6923 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6924 6925 if (BuiltinID) 6926 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6927 } else if (NDecl) { 6928 if (CheckPointerCall(NDecl, TheCall, Proto)) 6929 return ExprError(); 6930 } else { 6931 if (CheckOtherCall(TheCall, Proto)) 6932 return ExprError(); 6933 } 6934 6935 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6936 } 6937 6938 ExprResult 6939 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6940 SourceLocation RParenLoc, Expr *InitExpr) { 6941 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6942 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6943 6944 TypeSourceInfo *TInfo; 6945 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6946 if (!TInfo) 6947 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6948 6949 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6950 } 6951 6952 ExprResult 6953 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6954 SourceLocation RParenLoc, Expr *LiteralExpr) { 6955 QualType literalType = TInfo->getType(); 6956 6957 if (literalType->isArrayType()) { 6958 if (RequireCompleteSizedType( 6959 LParenLoc, Context.getBaseElementType(literalType), 6960 diag::err_array_incomplete_or_sizeless_type, 6961 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6962 return ExprError(); 6963 if (literalType->isVariableArrayType()) { 6964 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 6965 diag::err_variable_object_no_init)) { 6966 return ExprError(); 6967 } 6968 } 6969 } else if (!literalType->isDependentType() && 6970 RequireCompleteType(LParenLoc, literalType, 6971 diag::err_typecheck_decl_incomplete_type, 6972 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6973 return ExprError(); 6974 6975 InitializedEntity Entity 6976 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6977 InitializationKind Kind 6978 = InitializationKind::CreateCStyleCast(LParenLoc, 6979 SourceRange(LParenLoc, RParenLoc), 6980 /*InitList=*/true); 6981 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6982 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6983 &literalType); 6984 if (Result.isInvalid()) 6985 return ExprError(); 6986 LiteralExpr = Result.get(); 6987 6988 bool isFileScope = !CurContext->isFunctionOrMethod(); 6989 6990 // In C, compound literals are l-values for some reason. 6991 // For GCC compatibility, in C++, file-scope array compound literals with 6992 // constant initializers are also l-values, and compound literals are 6993 // otherwise prvalues. 6994 // 6995 // (GCC also treats C++ list-initialized file-scope array prvalues with 6996 // constant initializers as l-values, but that's non-conforming, so we don't 6997 // follow it there.) 6998 // 6999 // FIXME: It would be better to handle the lvalue cases as materializing and 7000 // lifetime-extending a temporary object, but our materialized temporaries 7001 // representation only supports lifetime extension from a variable, not "out 7002 // of thin air". 7003 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 7004 // is bound to the result of applying array-to-pointer decay to the compound 7005 // literal. 7006 // FIXME: GCC supports compound literals of reference type, which should 7007 // obviously have a value kind derived from the kind of reference involved. 7008 ExprValueKind VK = 7009 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 7010 ? VK_PRValue 7011 : VK_LValue; 7012 7013 if (isFileScope) 7014 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 7015 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 7016 Expr *Init = ILE->getInit(i); 7017 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 7018 } 7019 7020 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 7021 VK, LiteralExpr, isFileScope); 7022 if (isFileScope) { 7023 if (!LiteralExpr->isTypeDependent() && 7024 !LiteralExpr->isValueDependent() && 7025 !literalType->isDependentType()) // C99 6.5.2.5p3 7026 if (CheckForConstantInitializer(LiteralExpr, literalType)) 7027 return ExprError(); 7028 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 7029 literalType.getAddressSpace() != LangAS::Default) { 7030 // Embedded-C extensions to C99 6.5.2.5: 7031 // "If the compound literal occurs inside the body of a function, the 7032 // type name shall not be qualified by an address-space qualifier." 7033 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 7034 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 7035 return ExprError(); 7036 } 7037 7038 if (!isFileScope && !getLangOpts().CPlusPlus) { 7039 // Compound literals that have automatic storage duration are destroyed at 7040 // the end of the scope in C; in C++, they're just temporaries. 7041 7042 // Emit diagnostics if it is or contains a C union type that is non-trivial 7043 // to destruct. 7044 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 7045 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 7046 NTCUC_CompoundLiteral, NTCUK_Destruct); 7047 7048 // Diagnose jumps that enter or exit the lifetime of the compound literal. 7049 if (literalType.isDestructedType()) { 7050 Cleanup.setExprNeedsCleanups(true); 7051 ExprCleanupObjects.push_back(E); 7052 getCurFunction()->setHasBranchProtectedScope(); 7053 } 7054 } 7055 7056 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7057 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7058 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7059 E->getInitializer()->getExprLoc()); 7060 7061 return MaybeBindToTemporary(E); 7062 } 7063 7064 ExprResult 7065 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7066 SourceLocation RBraceLoc) { 7067 // Only produce each kind of designated initialization diagnostic once. 7068 SourceLocation FirstDesignator; 7069 bool DiagnosedArrayDesignator = false; 7070 bool DiagnosedNestedDesignator = false; 7071 bool DiagnosedMixedDesignator = false; 7072 7073 // Check that any designated initializers are syntactically valid in the 7074 // current language mode. 7075 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7076 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7077 if (FirstDesignator.isInvalid()) 7078 FirstDesignator = DIE->getBeginLoc(); 7079 7080 if (!getLangOpts().CPlusPlus) 7081 break; 7082 7083 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7084 DiagnosedNestedDesignator = true; 7085 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7086 << DIE->getDesignatorsSourceRange(); 7087 } 7088 7089 for (auto &Desig : DIE->designators()) { 7090 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7091 DiagnosedArrayDesignator = true; 7092 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7093 << Desig.getSourceRange(); 7094 } 7095 } 7096 7097 if (!DiagnosedMixedDesignator && 7098 !isa<DesignatedInitExpr>(InitArgList[0])) { 7099 DiagnosedMixedDesignator = true; 7100 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7101 << DIE->getSourceRange(); 7102 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7103 << InitArgList[0]->getSourceRange(); 7104 } 7105 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7106 isa<DesignatedInitExpr>(InitArgList[0])) { 7107 DiagnosedMixedDesignator = true; 7108 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7109 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7110 << DIE->getSourceRange(); 7111 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7112 << InitArgList[I]->getSourceRange(); 7113 } 7114 } 7115 7116 if (FirstDesignator.isValid()) { 7117 // Only diagnose designated initiaization as a C++20 extension if we didn't 7118 // already diagnose use of (non-C++20) C99 designator syntax. 7119 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7120 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7121 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7122 ? diag::warn_cxx17_compat_designated_init 7123 : diag::ext_cxx_designated_init); 7124 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7125 Diag(FirstDesignator, diag::ext_designated_init); 7126 } 7127 } 7128 7129 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7130 } 7131 7132 ExprResult 7133 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7134 SourceLocation RBraceLoc) { 7135 // Semantic analysis for initializers is done by ActOnDeclarator() and 7136 // CheckInitializer() - it requires knowledge of the object being initialized. 7137 7138 // Immediately handle non-overload placeholders. Overloads can be 7139 // resolved contextually, but everything else here can't. 7140 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7141 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7142 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7143 7144 // Ignore failures; dropping the entire initializer list because 7145 // of one failure would be terrible for indexing/etc. 7146 if (result.isInvalid()) continue; 7147 7148 InitArgList[I] = result.get(); 7149 } 7150 } 7151 7152 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7153 RBraceLoc); 7154 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7155 return E; 7156 } 7157 7158 /// Do an explicit extend of the given block pointer if we're in ARC. 7159 void Sema::maybeExtendBlockObject(ExprResult &E) { 7160 assert(E.get()->getType()->isBlockPointerType()); 7161 assert(E.get()->isPRValue()); 7162 7163 // Only do this in an r-value context. 7164 if (!getLangOpts().ObjCAutoRefCount) return; 7165 7166 E = ImplicitCastExpr::Create( 7167 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7168 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 7169 Cleanup.setExprNeedsCleanups(true); 7170 } 7171 7172 /// Prepare a conversion of the given expression to an ObjC object 7173 /// pointer type. 7174 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7175 QualType type = E.get()->getType(); 7176 if (type->isObjCObjectPointerType()) { 7177 return CK_BitCast; 7178 } else if (type->isBlockPointerType()) { 7179 maybeExtendBlockObject(E); 7180 return CK_BlockPointerToObjCPointerCast; 7181 } else { 7182 assert(type->isPointerType()); 7183 return CK_CPointerToObjCPointerCast; 7184 } 7185 } 7186 7187 /// Prepares for a scalar cast, performing all the necessary stages 7188 /// except the final cast and returning the kind required. 7189 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7190 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7191 // Also, callers should have filtered out the invalid cases with 7192 // pointers. Everything else should be possible. 7193 7194 QualType SrcTy = Src.get()->getType(); 7195 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7196 return CK_NoOp; 7197 7198 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7199 case Type::STK_MemberPointer: 7200 llvm_unreachable("member pointer type in C"); 7201 7202 case Type::STK_CPointer: 7203 case Type::STK_BlockPointer: 7204 case Type::STK_ObjCObjectPointer: 7205 switch (DestTy->getScalarTypeKind()) { 7206 case Type::STK_CPointer: { 7207 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7208 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7209 if (SrcAS != DestAS) 7210 return CK_AddressSpaceConversion; 7211 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7212 return CK_NoOp; 7213 return CK_BitCast; 7214 } 7215 case Type::STK_BlockPointer: 7216 return (SrcKind == Type::STK_BlockPointer 7217 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7218 case Type::STK_ObjCObjectPointer: 7219 if (SrcKind == Type::STK_ObjCObjectPointer) 7220 return CK_BitCast; 7221 if (SrcKind == Type::STK_CPointer) 7222 return CK_CPointerToObjCPointerCast; 7223 maybeExtendBlockObject(Src); 7224 return CK_BlockPointerToObjCPointerCast; 7225 case Type::STK_Bool: 7226 return CK_PointerToBoolean; 7227 case Type::STK_Integral: 7228 return CK_PointerToIntegral; 7229 case Type::STK_Floating: 7230 case Type::STK_FloatingComplex: 7231 case Type::STK_IntegralComplex: 7232 case Type::STK_MemberPointer: 7233 case Type::STK_FixedPoint: 7234 llvm_unreachable("illegal cast from pointer"); 7235 } 7236 llvm_unreachable("Should have returned before this"); 7237 7238 case Type::STK_FixedPoint: 7239 switch (DestTy->getScalarTypeKind()) { 7240 case Type::STK_FixedPoint: 7241 return CK_FixedPointCast; 7242 case Type::STK_Bool: 7243 return CK_FixedPointToBoolean; 7244 case Type::STK_Integral: 7245 return CK_FixedPointToIntegral; 7246 case Type::STK_Floating: 7247 return CK_FixedPointToFloating; 7248 case Type::STK_IntegralComplex: 7249 case Type::STK_FloatingComplex: 7250 Diag(Src.get()->getExprLoc(), 7251 diag::err_unimplemented_conversion_with_fixed_point_type) 7252 << DestTy; 7253 return CK_IntegralCast; 7254 case Type::STK_CPointer: 7255 case Type::STK_ObjCObjectPointer: 7256 case Type::STK_BlockPointer: 7257 case Type::STK_MemberPointer: 7258 llvm_unreachable("illegal cast to pointer type"); 7259 } 7260 llvm_unreachable("Should have returned before this"); 7261 7262 case Type::STK_Bool: // casting from bool is like casting from an integer 7263 case Type::STK_Integral: 7264 switch (DestTy->getScalarTypeKind()) { 7265 case Type::STK_CPointer: 7266 case Type::STK_ObjCObjectPointer: 7267 case Type::STK_BlockPointer: 7268 if (Src.get()->isNullPointerConstant(Context, 7269 Expr::NPC_ValueDependentIsNull)) 7270 return CK_NullToPointer; 7271 return CK_IntegralToPointer; 7272 case Type::STK_Bool: 7273 return CK_IntegralToBoolean; 7274 case Type::STK_Integral: 7275 return CK_IntegralCast; 7276 case Type::STK_Floating: 7277 return CK_IntegralToFloating; 7278 case Type::STK_IntegralComplex: 7279 Src = ImpCastExprToType(Src.get(), 7280 DestTy->castAs<ComplexType>()->getElementType(), 7281 CK_IntegralCast); 7282 return CK_IntegralRealToComplex; 7283 case Type::STK_FloatingComplex: 7284 Src = ImpCastExprToType(Src.get(), 7285 DestTy->castAs<ComplexType>()->getElementType(), 7286 CK_IntegralToFloating); 7287 return CK_FloatingRealToComplex; 7288 case Type::STK_MemberPointer: 7289 llvm_unreachable("member pointer type in C"); 7290 case Type::STK_FixedPoint: 7291 return CK_IntegralToFixedPoint; 7292 } 7293 llvm_unreachable("Should have returned before this"); 7294 7295 case Type::STK_Floating: 7296 switch (DestTy->getScalarTypeKind()) { 7297 case Type::STK_Floating: 7298 return CK_FloatingCast; 7299 case Type::STK_Bool: 7300 return CK_FloatingToBoolean; 7301 case Type::STK_Integral: 7302 return CK_FloatingToIntegral; 7303 case Type::STK_FloatingComplex: 7304 Src = ImpCastExprToType(Src.get(), 7305 DestTy->castAs<ComplexType>()->getElementType(), 7306 CK_FloatingCast); 7307 return CK_FloatingRealToComplex; 7308 case Type::STK_IntegralComplex: 7309 Src = ImpCastExprToType(Src.get(), 7310 DestTy->castAs<ComplexType>()->getElementType(), 7311 CK_FloatingToIntegral); 7312 return CK_IntegralRealToComplex; 7313 case Type::STK_CPointer: 7314 case Type::STK_ObjCObjectPointer: 7315 case Type::STK_BlockPointer: 7316 llvm_unreachable("valid float->pointer cast?"); 7317 case Type::STK_MemberPointer: 7318 llvm_unreachable("member pointer type in C"); 7319 case Type::STK_FixedPoint: 7320 return CK_FloatingToFixedPoint; 7321 } 7322 llvm_unreachable("Should have returned before this"); 7323 7324 case Type::STK_FloatingComplex: 7325 switch (DestTy->getScalarTypeKind()) { 7326 case Type::STK_FloatingComplex: 7327 return CK_FloatingComplexCast; 7328 case Type::STK_IntegralComplex: 7329 return CK_FloatingComplexToIntegralComplex; 7330 case Type::STK_Floating: { 7331 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7332 if (Context.hasSameType(ET, DestTy)) 7333 return CK_FloatingComplexToReal; 7334 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7335 return CK_FloatingCast; 7336 } 7337 case Type::STK_Bool: 7338 return CK_FloatingComplexToBoolean; 7339 case Type::STK_Integral: 7340 Src = ImpCastExprToType(Src.get(), 7341 SrcTy->castAs<ComplexType>()->getElementType(), 7342 CK_FloatingComplexToReal); 7343 return CK_FloatingToIntegral; 7344 case Type::STK_CPointer: 7345 case Type::STK_ObjCObjectPointer: 7346 case Type::STK_BlockPointer: 7347 llvm_unreachable("valid complex float->pointer cast?"); 7348 case Type::STK_MemberPointer: 7349 llvm_unreachable("member pointer type in C"); 7350 case Type::STK_FixedPoint: 7351 Diag(Src.get()->getExprLoc(), 7352 diag::err_unimplemented_conversion_with_fixed_point_type) 7353 << SrcTy; 7354 return CK_IntegralCast; 7355 } 7356 llvm_unreachable("Should have returned before this"); 7357 7358 case Type::STK_IntegralComplex: 7359 switch (DestTy->getScalarTypeKind()) { 7360 case Type::STK_FloatingComplex: 7361 return CK_IntegralComplexToFloatingComplex; 7362 case Type::STK_IntegralComplex: 7363 return CK_IntegralComplexCast; 7364 case Type::STK_Integral: { 7365 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7366 if (Context.hasSameType(ET, DestTy)) 7367 return CK_IntegralComplexToReal; 7368 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7369 return CK_IntegralCast; 7370 } 7371 case Type::STK_Bool: 7372 return CK_IntegralComplexToBoolean; 7373 case Type::STK_Floating: 7374 Src = ImpCastExprToType(Src.get(), 7375 SrcTy->castAs<ComplexType>()->getElementType(), 7376 CK_IntegralComplexToReal); 7377 return CK_IntegralToFloating; 7378 case Type::STK_CPointer: 7379 case Type::STK_ObjCObjectPointer: 7380 case Type::STK_BlockPointer: 7381 llvm_unreachable("valid complex int->pointer cast?"); 7382 case Type::STK_MemberPointer: 7383 llvm_unreachable("member pointer type in C"); 7384 case Type::STK_FixedPoint: 7385 Diag(Src.get()->getExprLoc(), 7386 diag::err_unimplemented_conversion_with_fixed_point_type) 7387 << SrcTy; 7388 return CK_IntegralCast; 7389 } 7390 llvm_unreachable("Should have returned before this"); 7391 } 7392 7393 llvm_unreachable("Unhandled scalar cast"); 7394 } 7395 7396 static bool breakDownVectorType(QualType type, uint64_t &len, 7397 QualType &eltType) { 7398 // Vectors are simple. 7399 if (const VectorType *vecType = type->getAs<VectorType>()) { 7400 len = vecType->getNumElements(); 7401 eltType = vecType->getElementType(); 7402 assert(eltType->isScalarType()); 7403 return true; 7404 } 7405 7406 // We allow lax conversion to and from non-vector types, but only if 7407 // they're real types (i.e. non-complex, non-pointer scalar types). 7408 if (!type->isRealType()) return false; 7409 7410 len = 1; 7411 eltType = type; 7412 return true; 7413 } 7414 7415 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7416 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7417 /// allowed? 7418 /// 7419 /// This will also return false if the two given types do not make sense from 7420 /// the perspective of SVE bitcasts. 7421 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7422 assert(srcTy->isVectorType() || destTy->isVectorType()); 7423 7424 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7425 if (!FirstType->isSizelessBuiltinType()) 7426 return false; 7427 7428 const auto *VecTy = SecondType->getAs<VectorType>(); 7429 return VecTy && 7430 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7431 }; 7432 7433 return ValidScalableConversion(srcTy, destTy) || 7434 ValidScalableConversion(destTy, srcTy); 7435 } 7436 7437 /// Are the two types matrix types and do they have the same dimensions i.e. 7438 /// do they have the same number of rows and the same number of columns? 7439 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7440 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7441 return false; 7442 7443 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7444 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7445 7446 return matSrcType->getNumRows() == matDestType->getNumRows() && 7447 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7448 } 7449 7450 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7451 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7452 7453 uint64_t SrcLen, DestLen; 7454 QualType SrcEltTy, DestEltTy; 7455 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7456 return false; 7457 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7458 return false; 7459 7460 // ASTContext::getTypeSize will return the size rounded up to a 7461 // power of 2, so instead of using that, we need to use the raw 7462 // element size multiplied by the element count. 7463 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7464 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7465 7466 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7467 } 7468 7469 /// Are the two types lax-compatible vector types? That is, given 7470 /// that one of them is a vector, do they have equal storage sizes, 7471 /// where the storage size is the number of elements times the element 7472 /// size? 7473 /// 7474 /// This will also return false if either of the types is neither a 7475 /// vector nor a real type. 7476 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7477 assert(destTy->isVectorType() || srcTy->isVectorType()); 7478 7479 // Disallow lax conversions between scalars and ExtVectors (these 7480 // conversions are allowed for other vector types because common headers 7481 // depend on them). Most scalar OP ExtVector cases are handled by the 7482 // splat path anyway, which does what we want (convert, not bitcast). 7483 // What this rules out for ExtVectors is crazy things like char4*float. 7484 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7485 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7486 7487 return areVectorTypesSameSize(srcTy, destTy); 7488 } 7489 7490 /// Is this a legal conversion between two types, one of which is 7491 /// known to be a vector type? 7492 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7493 assert(destTy->isVectorType() || srcTy->isVectorType()); 7494 7495 switch (Context.getLangOpts().getLaxVectorConversions()) { 7496 case LangOptions::LaxVectorConversionKind::None: 7497 return false; 7498 7499 case LangOptions::LaxVectorConversionKind::Integer: 7500 if (!srcTy->isIntegralOrEnumerationType()) { 7501 auto *Vec = srcTy->getAs<VectorType>(); 7502 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7503 return false; 7504 } 7505 if (!destTy->isIntegralOrEnumerationType()) { 7506 auto *Vec = destTy->getAs<VectorType>(); 7507 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7508 return false; 7509 } 7510 // OK, integer (vector) -> integer (vector) bitcast. 7511 break; 7512 7513 case LangOptions::LaxVectorConversionKind::All: 7514 break; 7515 } 7516 7517 return areLaxCompatibleVectorTypes(srcTy, destTy); 7518 } 7519 7520 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7521 CastKind &Kind) { 7522 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7523 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7524 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7525 << DestTy << SrcTy << R; 7526 } 7527 } else if (SrcTy->isMatrixType()) { 7528 return Diag(R.getBegin(), 7529 diag::err_invalid_conversion_between_matrix_and_type) 7530 << SrcTy << DestTy << R; 7531 } else if (DestTy->isMatrixType()) { 7532 return Diag(R.getBegin(), 7533 diag::err_invalid_conversion_between_matrix_and_type) 7534 << DestTy << SrcTy << R; 7535 } 7536 7537 Kind = CK_MatrixCast; 7538 return false; 7539 } 7540 7541 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7542 CastKind &Kind) { 7543 assert(VectorTy->isVectorType() && "Not a vector type!"); 7544 7545 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7546 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7547 return Diag(R.getBegin(), 7548 Ty->isVectorType() ? 7549 diag::err_invalid_conversion_between_vectors : 7550 diag::err_invalid_conversion_between_vector_and_integer) 7551 << VectorTy << Ty << R; 7552 } else 7553 return Diag(R.getBegin(), 7554 diag::err_invalid_conversion_between_vector_and_scalar) 7555 << VectorTy << Ty << R; 7556 7557 Kind = CK_BitCast; 7558 return false; 7559 } 7560 7561 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7562 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7563 7564 if (DestElemTy == SplattedExpr->getType()) 7565 return SplattedExpr; 7566 7567 assert(DestElemTy->isFloatingType() || 7568 DestElemTy->isIntegralOrEnumerationType()); 7569 7570 CastKind CK; 7571 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7572 // OpenCL requires that we convert `true` boolean expressions to -1, but 7573 // only when splatting vectors. 7574 if (DestElemTy->isFloatingType()) { 7575 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7576 // in two steps: boolean to signed integral, then to floating. 7577 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7578 CK_BooleanToSignedIntegral); 7579 SplattedExpr = CastExprRes.get(); 7580 CK = CK_IntegralToFloating; 7581 } else { 7582 CK = CK_BooleanToSignedIntegral; 7583 } 7584 } else { 7585 ExprResult CastExprRes = SplattedExpr; 7586 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7587 if (CastExprRes.isInvalid()) 7588 return ExprError(); 7589 SplattedExpr = CastExprRes.get(); 7590 } 7591 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7592 } 7593 7594 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7595 Expr *CastExpr, CastKind &Kind) { 7596 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7597 7598 QualType SrcTy = CastExpr->getType(); 7599 7600 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7601 // an ExtVectorType. 7602 // In OpenCL, casts between vectors of different types are not allowed. 7603 // (See OpenCL 6.2). 7604 if (SrcTy->isVectorType()) { 7605 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7606 (getLangOpts().OpenCL && 7607 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7608 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7609 << DestTy << SrcTy << R; 7610 return ExprError(); 7611 } 7612 Kind = CK_BitCast; 7613 return CastExpr; 7614 } 7615 7616 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7617 // conversion will take place first from scalar to elt type, and then 7618 // splat from elt type to vector. 7619 if (SrcTy->isPointerType()) 7620 return Diag(R.getBegin(), 7621 diag::err_invalid_conversion_between_vector_and_scalar) 7622 << DestTy << SrcTy << R; 7623 7624 Kind = CK_VectorSplat; 7625 return prepareVectorSplat(DestTy, CastExpr); 7626 } 7627 7628 ExprResult 7629 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7630 Declarator &D, ParsedType &Ty, 7631 SourceLocation RParenLoc, Expr *CastExpr) { 7632 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7633 "ActOnCastExpr(): missing type or expr"); 7634 7635 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7636 if (D.isInvalidType()) 7637 return ExprError(); 7638 7639 if (getLangOpts().CPlusPlus) { 7640 // Check that there are no default arguments (C++ only). 7641 CheckExtraCXXDefaultArguments(D); 7642 } else { 7643 // Make sure any TypoExprs have been dealt with. 7644 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7645 if (!Res.isUsable()) 7646 return ExprError(); 7647 CastExpr = Res.get(); 7648 } 7649 7650 checkUnusedDeclAttributes(D); 7651 7652 QualType castType = castTInfo->getType(); 7653 Ty = CreateParsedType(castType, castTInfo); 7654 7655 bool isVectorLiteral = false; 7656 7657 // Check for an altivec or OpenCL literal, 7658 // i.e. all the elements are integer constants. 7659 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7660 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7661 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7662 && castType->isVectorType() && (PE || PLE)) { 7663 if (PLE && PLE->getNumExprs() == 0) { 7664 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7665 return ExprError(); 7666 } 7667 if (PE || PLE->getNumExprs() == 1) { 7668 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7669 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7670 isVectorLiteral = true; 7671 } 7672 else 7673 isVectorLiteral = true; 7674 } 7675 7676 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7677 // then handle it as such. 7678 if (isVectorLiteral) 7679 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7680 7681 // If the Expr being casted is a ParenListExpr, handle it specially. 7682 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7683 // sequence of BinOp comma operators. 7684 if (isa<ParenListExpr>(CastExpr)) { 7685 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7686 if (Result.isInvalid()) return ExprError(); 7687 CastExpr = Result.get(); 7688 } 7689 7690 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7691 !getSourceManager().isInSystemMacro(LParenLoc)) 7692 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7693 7694 CheckTollFreeBridgeCast(castType, CastExpr); 7695 7696 CheckObjCBridgeRelatedCast(castType, CastExpr); 7697 7698 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7699 7700 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7701 } 7702 7703 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7704 SourceLocation RParenLoc, Expr *E, 7705 TypeSourceInfo *TInfo) { 7706 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7707 "Expected paren or paren list expression"); 7708 7709 Expr **exprs; 7710 unsigned numExprs; 7711 Expr *subExpr; 7712 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7713 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7714 LiteralLParenLoc = PE->getLParenLoc(); 7715 LiteralRParenLoc = PE->getRParenLoc(); 7716 exprs = PE->getExprs(); 7717 numExprs = PE->getNumExprs(); 7718 } else { // isa<ParenExpr> by assertion at function entrance 7719 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7720 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7721 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7722 exprs = &subExpr; 7723 numExprs = 1; 7724 } 7725 7726 QualType Ty = TInfo->getType(); 7727 assert(Ty->isVectorType() && "Expected vector type"); 7728 7729 SmallVector<Expr *, 8> initExprs; 7730 const VectorType *VTy = Ty->castAs<VectorType>(); 7731 unsigned numElems = VTy->getNumElements(); 7732 7733 // '(...)' form of vector initialization in AltiVec: the number of 7734 // initializers must be one or must match the size of the vector. 7735 // If a single value is specified in the initializer then it will be 7736 // replicated to all the components of the vector 7737 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, 7738 VTy->getElementType())) 7739 return ExprError(); 7740 if (ShouldSplatAltivecScalarInCast(VTy)) { 7741 // The number of initializers must be one or must match the size of the 7742 // vector. If a single value is specified in the initializer then it will 7743 // be replicated to all the components of the vector 7744 if (numExprs == 1) { 7745 QualType ElemTy = VTy->getElementType(); 7746 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7747 if (Literal.isInvalid()) 7748 return ExprError(); 7749 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7750 PrepareScalarCast(Literal, ElemTy)); 7751 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7752 } 7753 else if (numExprs < numElems) { 7754 Diag(E->getExprLoc(), 7755 diag::err_incorrect_number_of_vector_initializers); 7756 return ExprError(); 7757 } 7758 else 7759 initExprs.append(exprs, exprs + numExprs); 7760 } 7761 else { 7762 // For OpenCL, when the number of initializers is a single value, 7763 // it will be replicated to all components of the vector. 7764 if (getLangOpts().OpenCL && 7765 VTy->getVectorKind() == VectorType::GenericVector && 7766 numExprs == 1) { 7767 QualType ElemTy = VTy->getElementType(); 7768 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7769 if (Literal.isInvalid()) 7770 return ExprError(); 7771 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7772 PrepareScalarCast(Literal, ElemTy)); 7773 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7774 } 7775 7776 initExprs.append(exprs, exprs + numExprs); 7777 } 7778 // FIXME: This means that pretty-printing the final AST will produce curly 7779 // braces instead of the original commas. 7780 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7781 initExprs, LiteralRParenLoc); 7782 initE->setType(Ty); 7783 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7784 } 7785 7786 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7787 /// the ParenListExpr into a sequence of comma binary operators. 7788 ExprResult 7789 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7790 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7791 if (!E) 7792 return OrigExpr; 7793 7794 ExprResult Result(E->getExpr(0)); 7795 7796 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7797 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7798 E->getExpr(i)); 7799 7800 if (Result.isInvalid()) return ExprError(); 7801 7802 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7803 } 7804 7805 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7806 SourceLocation R, 7807 MultiExprArg Val) { 7808 return ParenListExpr::Create(Context, L, Val, R); 7809 } 7810 7811 /// Emit a specialized diagnostic when one expression is a null pointer 7812 /// constant and the other is not a pointer. Returns true if a diagnostic is 7813 /// emitted. 7814 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7815 SourceLocation QuestionLoc) { 7816 Expr *NullExpr = LHSExpr; 7817 Expr *NonPointerExpr = RHSExpr; 7818 Expr::NullPointerConstantKind NullKind = 7819 NullExpr->isNullPointerConstant(Context, 7820 Expr::NPC_ValueDependentIsNotNull); 7821 7822 if (NullKind == Expr::NPCK_NotNull) { 7823 NullExpr = RHSExpr; 7824 NonPointerExpr = LHSExpr; 7825 NullKind = 7826 NullExpr->isNullPointerConstant(Context, 7827 Expr::NPC_ValueDependentIsNotNull); 7828 } 7829 7830 if (NullKind == Expr::NPCK_NotNull) 7831 return false; 7832 7833 if (NullKind == Expr::NPCK_ZeroExpression) 7834 return false; 7835 7836 if (NullKind == Expr::NPCK_ZeroLiteral) { 7837 // In this case, check to make sure that we got here from a "NULL" 7838 // string in the source code. 7839 NullExpr = NullExpr->IgnoreParenImpCasts(); 7840 SourceLocation loc = NullExpr->getExprLoc(); 7841 if (!findMacroSpelling(loc, "NULL")) 7842 return false; 7843 } 7844 7845 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7846 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7847 << NonPointerExpr->getType() << DiagType 7848 << NonPointerExpr->getSourceRange(); 7849 return true; 7850 } 7851 7852 /// Return false if the condition expression is valid, true otherwise. 7853 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7854 QualType CondTy = Cond->getType(); 7855 7856 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7857 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7858 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7859 << CondTy << Cond->getSourceRange(); 7860 return true; 7861 } 7862 7863 // C99 6.5.15p2 7864 if (CondTy->isScalarType()) return false; 7865 7866 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7867 << CondTy << Cond->getSourceRange(); 7868 return true; 7869 } 7870 7871 /// Handle when one or both operands are void type. 7872 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7873 ExprResult &RHS) { 7874 Expr *LHSExpr = LHS.get(); 7875 Expr *RHSExpr = RHS.get(); 7876 7877 if (!LHSExpr->getType()->isVoidType()) 7878 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7879 << RHSExpr->getSourceRange(); 7880 if (!RHSExpr->getType()->isVoidType()) 7881 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7882 << LHSExpr->getSourceRange(); 7883 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7884 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7885 return S.Context.VoidTy; 7886 } 7887 7888 /// Return false if the NullExpr can be promoted to PointerTy, 7889 /// true otherwise. 7890 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7891 QualType PointerTy) { 7892 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7893 !NullExpr.get()->isNullPointerConstant(S.Context, 7894 Expr::NPC_ValueDependentIsNull)) 7895 return true; 7896 7897 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7898 return false; 7899 } 7900 7901 /// Checks compatibility between two pointers and return the resulting 7902 /// type. 7903 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7904 ExprResult &RHS, 7905 SourceLocation Loc) { 7906 QualType LHSTy = LHS.get()->getType(); 7907 QualType RHSTy = RHS.get()->getType(); 7908 7909 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7910 // Two identical pointers types are always compatible. 7911 return LHSTy; 7912 } 7913 7914 QualType lhptee, rhptee; 7915 7916 // Get the pointee types. 7917 bool IsBlockPointer = false; 7918 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7919 lhptee = LHSBTy->getPointeeType(); 7920 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7921 IsBlockPointer = true; 7922 } else { 7923 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7924 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7925 } 7926 7927 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7928 // differently qualified versions of compatible types, the result type is 7929 // a pointer to an appropriately qualified version of the composite 7930 // type. 7931 7932 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7933 // clause doesn't make sense for our extensions. E.g. address space 2 should 7934 // be incompatible with address space 3: they may live on different devices or 7935 // anything. 7936 Qualifiers lhQual = lhptee.getQualifiers(); 7937 Qualifiers rhQual = rhptee.getQualifiers(); 7938 7939 LangAS ResultAddrSpace = LangAS::Default; 7940 LangAS LAddrSpace = lhQual.getAddressSpace(); 7941 LangAS RAddrSpace = rhQual.getAddressSpace(); 7942 7943 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7944 // spaces is disallowed. 7945 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7946 ResultAddrSpace = LAddrSpace; 7947 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7948 ResultAddrSpace = RAddrSpace; 7949 else { 7950 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7951 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7952 << RHS.get()->getSourceRange(); 7953 return QualType(); 7954 } 7955 7956 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7957 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7958 lhQual.removeCVRQualifiers(); 7959 rhQual.removeCVRQualifiers(); 7960 7961 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7962 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7963 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7964 // qual types are compatible iff 7965 // * corresponded types are compatible 7966 // * CVR qualifiers are equal 7967 // * address spaces are equal 7968 // Thus for conditional operator we merge CVR and address space unqualified 7969 // pointees and if there is a composite type we return a pointer to it with 7970 // merged qualifiers. 7971 LHSCastKind = 7972 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7973 RHSCastKind = 7974 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7975 lhQual.removeAddressSpace(); 7976 rhQual.removeAddressSpace(); 7977 7978 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7979 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7980 7981 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7982 7983 if (CompositeTy.isNull()) { 7984 // In this situation, we assume void* type. No especially good 7985 // reason, but this is what gcc does, and we do have to pick 7986 // to get a consistent AST. 7987 QualType incompatTy; 7988 incompatTy = S.Context.getPointerType( 7989 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7990 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7991 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7992 7993 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7994 // for casts between types with incompatible address space qualifiers. 7995 // For the following code the compiler produces casts between global and 7996 // local address spaces of the corresponded innermost pointees: 7997 // local int *global *a; 7998 // global int *global *b; 7999 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 8000 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 8001 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8002 << RHS.get()->getSourceRange(); 8003 8004 return incompatTy; 8005 } 8006 8007 // The pointer types are compatible. 8008 // In case of OpenCL ResultTy should have the address space qualifier 8009 // which is a superset of address spaces of both the 2nd and the 3rd 8010 // operands of the conditional operator. 8011 QualType ResultTy = [&, ResultAddrSpace]() { 8012 if (S.getLangOpts().OpenCL) { 8013 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 8014 CompositeQuals.setAddressSpace(ResultAddrSpace); 8015 return S.Context 8016 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 8017 .withCVRQualifiers(MergedCVRQual); 8018 } 8019 return CompositeTy.withCVRQualifiers(MergedCVRQual); 8020 }(); 8021 if (IsBlockPointer) 8022 ResultTy = S.Context.getBlockPointerType(ResultTy); 8023 else 8024 ResultTy = S.Context.getPointerType(ResultTy); 8025 8026 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 8027 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 8028 return ResultTy; 8029 } 8030 8031 /// Return the resulting type when the operands are both block pointers. 8032 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 8033 ExprResult &LHS, 8034 ExprResult &RHS, 8035 SourceLocation Loc) { 8036 QualType LHSTy = LHS.get()->getType(); 8037 QualType RHSTy = RHS.get()->getType(); 8038 8039 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 8040 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 8041 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 8042 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8043 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8044 return destType; 8045 } 8046 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 8047 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8048 << RHS.get()->getSourceRange(); 8049 return QualType(); 8050 } 8051 8052 // We have 2 block pointer types. 8053 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8054 } 8055 8056 /// Return the resulting type when the operands are both pointers. 8057 static QualType 8058 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8059 ExprResult &RHS, 8060 SourceLocation Loc) { 8061 // get the pointer types 8062 QualType LHSTy = LHS.get()->getType(); 8063 QualType RHSTy = RHS.get()->getType(); 8064 8065 // get the "pointed to" types 8066 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8067 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8068 8069 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8070 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8071 // Figure out necessary qualifiers (C99 6.5.15p6) 8072 QualType destPointee 8073 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8074 QualType destType = S.Context.getPointerType(destPointee); 8075 // Add qualifiers if necessary. 8076 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8077 // Promote to void*. 8078 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8079 return destType; 8080 } 8081 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8082 QualType destPointee 8083 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8084 QualType destType = S.Context.getPointerType(destPointee); 8085 // Add qualifiers if necessary. 8086 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8087 // Promote to void*. 8088 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8089 return destType; 8090 } 8091 8092 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8093 } 8094 8095 /// Return false if the first expression is not an integer and the second 8096 /// expression is not a pointer, true otherwise. 8097 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8098 Expr* PointerExpr, SourceLocation Loc, 8099 bool IsIntFirstExpr) { 8100 if (!PointerExpr->getType()->isPointerType() || 8101 !Int.get()->getType()->isIntegerType()) 8102 return false; 8103 8104 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8105 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8106 8107 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8108 << Expr1->getType() << Expr2->getType() 8109 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8110 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8111 CK_IntegralToPointer); 8112 return true; 8113 } 8114 8115 /// Simple conversion between integer and floating point types. 8116 /// 8117 /// Used when handling the OpenCL conditional operator where the 8118 /// condition is a vector while the other operands are scalar. 8119 /// 8120 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8121 /// types are either integer or floating type. Between the two 8122 /// operands, the type with the higher rank is defined as the "result 8123 /// type". The other operand needs to be promoted to the same type. No 8124 /// other type promotion is allowed. We cannot use 8125 /// UsualArithmeticConversions() for this purpose, since it always 8126 /// promotes promotable types. 8127 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8128 ExprResult &RHS, 8129 SourceLocation QuestionLoc) { 8130 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8131 if (LHS.isInvalid()) 8132 return QualType(); 8133 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8134 if (RHS.isInvalid()) 8135 return QualType(); 8136 8137 // For conversion purposes, we ignore any qualifiers. 8138 // For example, "const float" and "float" are equivalent. 8139 QualType LHSType = 8140 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8141 QualType RHSType = 8142 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8143 8144 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8145 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8146 << LHSType << LHS.get()->getSourceRange(); 8147 return QualType(); 8148 } 8149 8150 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8151 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8152 << RHSType << RHS.get()->getSourceRange(); 8153 return QualType(); 8154 } 8155 8156 // If both types are identical, no conversion is needed. 8157 if (LHSType == RHSType) 8158 return LHSType; 8159 8160 // Now handle "real" floating types (i.e. float, double, long double). 8161 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8162 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8163 /*IsCompAssign = */ false); 8164 8165 // Finally, we have two differing integer types. 8166 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8167 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8168 } 8169 8170 /// Convert scalar operands to a vector that matches the 8171 /// condition in length. 8172 /// 8173 /// Used when handling the OpenCL conditional operator where the 8174 /// condition is a vector while the other operands are scalar. 8175 /// 8176 /// We first compute the "result type" for the scalar operands 8177 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8178 /// into a vector of that type where the length matches the condition 8179 /// vector type. s6.11.6 requires that the element types of the result 8180 /// and the condition must have the same number of bits. 8181 static QualType 8182 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8183 QualType CondTy, SourceLocation QuestionLoc) { 8184 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8185 if (ResTy.isNull()) return QualType(); 8186 8187 const VectorType *CV = CondTy->getAs<VectorType>(); 8188 assert(CV); 8189 8190 // Determine the vector result type 8191 unsigned NumElements = CV->getNumElements(); 8192 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8193 8194 // Ensure that all types have the same number of bits 8195 if (S.Context.getTypeSize(CV->getElementType()) 8196 != S.Context.getTypeSize(ResTy)) { 8197 // Since VectorTy is created internally, it does not pretty print 8198 // with an OpenCL name. Instead, we just print a description. 8199 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8200 SmallString<64> Str; 8201 llvm::raw_svector_ostream OS(Str); 8202 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8203 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8204 << CondTy << OS.str(); 8205 return QualType(); 8206 } 8207 8208 // Convert operands to the vector result type 8209 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8210 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8211 8212 return VectorTy; 8213 } 8214 8215 /// Return false if this is a valid OpenCL condition vector 8216 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8217 SourceLocation QuestionLoc) { 8218 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8219 // integral type. 8220 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8221 assert(CondTy); 8222 QualType EleTy = CondTy->getElementType(); 8223 if (EleTy->isIntegerType()) return false; 8224 8225 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8226 << Cond->getType() << Cond->getSourceRange(); 8227 return true; 8228 } 8229 8230 /// Return false if the vector condition type and the vector 8231 /// result type are compatible. 8232 /// 8233 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8234 /// number of elements, and their element types have the same number 8235 /// of bits. 8236 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8237 SourceLocation QuestionLoc) { 8238 const VectorType *CV = CondTy->getAs<VectorType>(); 8239 const VectorType *RV = VecResTy->getAs<VectorType>(); 8240 assert(CV && RV); 8241 8242 if (CV->getNumElements() != RV->getNumElements()) { 8243 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8244 << CondTy << VecResTy; 8245 return true; 8246 } 8247 8248 QualType CVE = CV->getElementType(); 8249 QualType RVE = RV->getElementType(); 8250 8251 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8252 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8253 << CondTy << VecResTy; 8254 return true; 8255 } 8256 8257 return false; 8258 } 8259 8260 /// Return the resulting type for the conditional operator in 8261 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8262 /// s6.3.i) when the condition is a vector type. 8263 static QualType 8264 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8265 ExprResult &LHS, ExprResult &RHS, 8266 SourceLocation QuestionLoc) { 8267 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8268 if (Cond.isInvalid()) 8269 return QualType(); 8270 QualType CondTy = Cond.get()->getType(); 8271 8272 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8273 return QualType(); 8274 8275 // If either operand is a vector then find the vector type of the 8276 // result as specified in OpenCL v1.1 s6.3.i. 8277 if (LHS.get()->getType()->isVectorType() || 8278 RHS.get()->getType()->isVectorType()) { 8279 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8280 /*isCompAssign*/false, 8281 /*AllowBothBool*/true, 8282 /*AllowBoolConversions*/false); 8283 if (VecResTy.isNull()) return QualType(); 8284 // The result type must match the condition type as specified in 8285 // OpenCL v1.1 s6.11.6. 8286 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8287 return QualType(); 8288 return VecResTy; 8289 } 8290 8291 // Both operands are scalar. 8292 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8293 } 8294 8295 /// Return true if the Expr is block type 8296 static bool checkBlockType(Sema &S, const Expr *E) { 8297 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8298 QualType Ty = CE->getCallee()->getType(); 8299 if (Ty->isBlockPointerType()) { 8300 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8301 return true; 8302 } 8303 } 8304 return false; 8305 } 8306 8307 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8308 /// In that case, LHS = cond. 8309 /// C99 6.5.15 8310 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8311 ExprResult &RHS, ExprValueKind &VK, 8312 ExprObjectKind &OK, 8313 SourceLocation QuestionLoc) { 8314 8315 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8316 if (!LHSResult.isUsable()) return QualType(); 8317 LHS = LHSResult; 8318 8319 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8320 if (!RHSResult.isUsable()) return QualType(); 8321 RHS = RHSResult; 8322 8323 // C++ is sufficiently different to merit its own checker. 8324 if (getLangOpts().CPlusPlus) 8325 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8326 8327 VK = VK_PRValue; 8328 OK = OK_Ordinary; 8329 8330 if (Context.isDependenceAllowed() && 8331 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8332 RHS.get()->isTypeDependent())) { 8333 assert(!getLangOpts().CPlusPlus); 8334 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8335 RHS.get()->containsErrors()) && 8336 "should only occur in error-recovery path."); 8337 return Context.DependentTy; 8338 } 8339 8340 // The OpenCL operator with a vector condition is sufficiently 8341 // different to merit its own checker. 8342 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8343 Cond.get()->getType()->isExtVectorType()) 8344 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8345 8346 // First, check the condition. 8347 Cond = UsualUnaryConversions(Cond.get()); 8348 if (Cond.isInvalid()) 8349 return QualType(); 8350 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8351 return QualType(); 8352 8353 // Now check the two expressions. 8354 if (LHS.get()->getType()->isVectorType() || 8355 RHS.get()->getType()->isVectorType()) 8356 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8357 /*AllowBothBool*/true, 8358 /*AllowBoolConversions*/false); 8359 8360 QualType ResTy = 8361 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8362 if (LHS.isInvalid() || RHS.isInvalid()) 8363 return QualType(); 8364 8365 QualType LHSTy = LHS.get()->getType(); 8366 QualType RHSTy = RHS.get()->getType(); 8367 8368 // Diagnose attempts to convert between __ibm128, __float128 and long double 8369 // where such conversions currently can't be handled. 8370 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8371 Diag(QuestionLoc, 8372 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8373 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8374 return QualType(); 8375 } 8376 8377 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8378 // selection operator (?:). 8379 if (getLangOpts().OpenCL && 8380 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8381 return QualType(); 8382 } 8383 8384 // If both operands have arithmetic type, do the usual arithmetic conversions 8385 // to find a common type: C99 6.5.15p3,5. 8386 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8387 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8388 // different sizes, or between ExtInts and other types. 8389 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8390 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8391 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8392 << RHS.get()->getSourceRange(); 8393 return QualType(); 8394 } 8395 8396 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8397 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8398 8399 return ResTy; 8400 } 8401 8402 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8403 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8404 return LHSTy; 8405 } 8406 8407 // If both operands are the same structure or union type, the result is that 8408 // type. 8409 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8410 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8411 if (LHSRT->getDecl() == RHSRT->getDecl()) 8412 // "If both the operands have structure or union type, the result has 8413 // that type." This implies that CV qualifiers are dropped. 8414 return LHSTy.getUnqualifiedType(); 8415 // FIXME: Type of conditional expression must be complete in C mode. 8416 } 8417 8418 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8419 // The following || allows only one side to be void (a GCC-ism). 8420 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8421 return checkConditionalVoidType(*this, LHS, RHS); 8422 } 8423 8424 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8425 // the type of the other operand." 8426 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8427 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8428 8429 // All objective-c pointer type analysis is done here. 8430 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8431 QuestionLoc); 8432 if (LHS.isInvalid() || RHS.isInvalid()) 8433 return QualType(); 8434 if (!compositeType.isNull()) 8435 return compositeType; 8436 8437 8438 // Handle block pointer types. 8439 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8440 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8441 QuestionLoc); 8442 8443 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8444 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8445 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8446 QuestionLoc); 8447 8448 // GCC compatibility: soften pointer/integer mismatch. Note that 8449 // null pointers have been filtered out by this point. 8450 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8451 /*IsIntFirstExpr=*/true)) 8452 return RHSTy; 8453 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8454 /*IsIntFirstExpr=*/false)) 8455 return LHSTy; 8456 8457 // Allow ?: operations in which both operands have the same 8458 // built-in sizeless type. 8459 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) 8460 return LHSTy; 8461 8462 // Emit a better diagnostic if one of the expressions is a null pointer 8463 // constant and the other is not a pointer type. In this case, the user most 8464 // likely forgot to take the address of the other expression. 8465 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8466 return QualType(); 8467 8468 // Otherwise, the operands are not compatible. 8469 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8470 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8471 << RHS.get()->getSourceRange(); 8472 return QualType(); 8473 } 8474 8475 /// FindCompositeObjCPointerType - Helper method to find composite type of 8476 /// two objective-c pointer types of the two input expressions. 8477 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8478 SourceLocation QuestionLoc) { 8479 QualType LHSTy = LHS.get()->getType(); 8480 QualType RHSTy = RHS.get()->getType(); 8481 8482 // Handle things like Class and struct objc_class*. Here we case the result 8483 // to the pseudo-builtin, because that will be implicitly cast back to the 8484 // redefinition type if an attempt is made to access its fields. 8485 if (LHSTy->isObjCClassType() && 8486 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8487 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8488 return LHSTy; 8489 } 8490 if (RHSTy->isObjCClassType() && 8491 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8492 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8493 return RHSTy; 8494 } 8495 // And the same for struct objc_object* / id 8496 if (LHSTy->isObjCIdType() && 8497 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8498 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8499 return LHSTy; 8500 } 8501 if (RHSTy->isObjCIdType() && 8502 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8503 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8504 return RHSTy; 8505 } 8506 // And the same for struct objc_selector* / SEL 8507 if (Context.isObjCSelType(LHSTy) && 8508 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8509 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8510 return LHSTy; 8511 } 8512 if (Context.isObjCSelType(RHSTy) && 8513 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8514 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8515 return RHSTy; 8516 } 8517 // Check constraints for Objective-C object pointers types. 8518 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8519 8520 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8521 // Two identical object pointer types are always compatible. 8522 return LHSTy; 8523 } 8524 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8525 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8526 QualType compositeType = LHSTy; 8527 8528 // If both operands are interfaces and either operand can be 8529 // assigned to the other, use that type as the composite 8530 // type. This allows 8531 // xxx ? (A*) a : (B*) b 8532 // where B is a subclass of A. 8533 // 8534 // Additionally, as for assignment, if either type is 'id' 8535 // allow silent coercion. Finally, if the types are 8536 // incompatible then make sure to use 'id' as the composite 8537 // type so the result is acceptable for sending messages to. 8538 8539 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8540 // It could return the composite type. 8541 if (!(compositeType = 8542 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8543 // Nothing more to do. 8544 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8545 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8546 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8547 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8548 } else if ((LHSOPT->isObjCQualifiedIdType() || 8549 RHSOPT->isObjCQualifiedIdType()) && 8550 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8551 true)) { 8552 // Need to handle "id<xx>" explicitly. 8553 // GCC allows qualified id and any Objective-C type to devolve to 8554 // id. Currently localizing to here until clear this should be 8555 // part of ObjCQualifiedIdTypesAreCompatible. 8556 compositeType = Context.getObjCIdType(); 8557 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8558 compositeType = Context.getObjCIdType(); 8559 } else { 8560 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8561 << LHSTy << RHSTy 8562 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8563 QualType incompatTy = Context.getObjCIdType(); 8564 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8565 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8566 return incompatTy; 8567 } 8568 // The object pointer types are compatible. 8569 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8570 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8571 return compositeType; 8572 } 8573 // Check Objective-C object pointer types and 'void *' 8574 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8575 if (getLangOpts().ObjCAutoRefCount) { 8576 // ARC forbids the implicit conversion of object pointers to 'void *', 8577 // so these types are not compatible. 8578 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8579 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8580 LHS = RHS = true; 8581 return QualType(); 8582 } 8583 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8584 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8585 QualType destPointee 8586 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8587 QualType destType = Context.getPointerType(destPointee); 8588 // Add qualifiers if necessary. 8589 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8590 // Promote to void*. 8591 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8592 return destType; 8593 } 8594 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8595 if (getLangOpts().ObjCAutoRefCount) { 8596 // ARC forbids the implicit conversion of object pointers to 'void *', 8597 // so these types are not compatible. 8598 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8599 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8600 LHS = RHS = true; 8601 return QualType(); 8602 } 8603 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8604 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8605 QualType destPointee 8606 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8607 QualType destType = Context.getPointerType(destPointee); 8608 // Add qualifiers if necessary. 8609 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8610 // Promote to void*. 8611 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8612 return destType; 8613 } 8614 return QualType(); 8615 } 8616 8617 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8618 /// ParenRange in parentheses. 8619 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8620 const PartialDiagnostic &Note, 8621 SourceRange ParenRange) { 8622 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8623 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8624 EndLoc.isValid()) { 8625 Self.Diag(Loc, Note) 8626 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8627 << FixItHint::CreateInsertion(EndLoc, ")"); 8628 } else { 8629 // We can't display the parentheses, so just show the bare note. 8630 Self.Diag(Loc, Note) << ParenRange; 8631 } 8632 } 8633 8634 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8635 return BinaryOperator::isAdditiveOp(Opc) || 8636 BinaryOperator::isMultiplicativeOp(Opc) || 8637 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8638 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8639 // not any of the logical operators. Bitwise-xor is commonly used as a 8640 // logical-xor because there is no logical-xor operator. The logical 8641 // operators, including uses of xor, have a high false positive rate for 8642 // precedence warnings. 8643 } 8644 8645 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8646 /// expression, either using a built-in or overloaded operator, 8647 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8648 /// expression. 8649 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8650 Expr **RHSExprs) { 8651 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8652 E = E->IgnoreImpCasts(); 8653 E = E->IgnoreConversionOperatorSingleStep(); 8654 E = E->IgnoreImpCasts(); 8655 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8656 E = MTE->getSubExpr(); 8657 E = E->IgnoreImpCasts(); 8658 } 8659 8660 // Built-in binary operator. 8661 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8662 if (IsArithmeticOp(OP->getOpcode())) { 8663 *Opcode = OP->getOpcode(); 8664 *RHSExprs = OP->getRHS(); 8665 return true; 8666 } 8667 } 8668 8669 // Overloaded operator. 8670 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8671 if (Call->getNumArgs() != 2) 8672 return false; 8673 8674 // Make sure this is really a binary operator that is safe to pass into 8675 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8676 OverloadedOperatorKind OO = Call->getOperator(); 8677 if (OO < OO_Plus || OO > OO_Arrow || 8678 OO == OO_PlusPlus || OO == OO_MinusMinus) 8679 return false; 8680 8681 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8682 if (IsArithmeticOp(OpKind)) { 8683 *Opcode = OpKind; 8684 *RHSExprs = Call->getArg(1); 8685 return true; 8686 } 8687 } 8688 8689 return false; 8690 } 8691 8692 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8693 /// or is a logical expression such as (x==y) which has int type, but is 8694 /// commonly interpreted as boolean. 8695 static bool ExprLooksBoolean(Expr *E) { 8696 E = E->IgnoreParenImpCasts(); 8697 8698 if (E->getType()->isBooleanType()) 8699 return true; 8700 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8701 return OP->isComparisonOp() || OP->isLogicalOp(); 8702 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8703 return OP->getOpcode() == UO_LNot; 8704 if (E->getType()->isPointerType()) 8705 return true; 8706 // FIXME: What about overloaded operator calls returning "unspecified boolean 8707 // type"s (commonly pointer-to-members)? 8708 8709 return false; 8710 } 8711 8712 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8713 /// and binary operator are mixed in a way that suggests the programmer assumed 8714 /// the conditional operator has higher precedence, for example: 8715 /// "int x = a + someBinaryCondition ? 1 : 2". 8716 static void DiagnoseConditionalPrecedence(Sema &Self, 8717 SourceLocation OpLoc, 8718 Expr *Condition, 8719 Expr *LHSExpr, 8720 Expr *RHSExpr) { 8721 BinaryOperatorKind CondOpcode; 8722 Expr *CondRHS; 8723 8724 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8725 return; 8726 if (!ExprLooksBoolean(CondRHS)) 8727 return; 8728 8729 // The condition is an arithmetic binary expression, with a right- 8730 // hand side that looks boolean, so warn. 8731 8732 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8733 ? diag::warn_precedence_bitwise_conditional 8734 : diag::warn_precedence_conditional; 8735 8736 Self.Diag(OpLoc, DiagID) 8737 << Condition->getSourceRange() 8738 << BinaryOperator::getOpcodeStr(CondOpcode); 8739 8740 SuggestParentheses( 8741 Self, OpLoc, 8742 Self.PDiag(diag::note_precedence_silence) 8743 << BinaryOperator::getOpcodeStr(CondOpcode), 8744 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8745 8746 SuggestParentheses(Self, OpLoc, 8747 Self.PDiag(diag::note_precedence_conditional_first), 8748 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8749 } 8750 8751 /// Compute the nullability of a conditional expression. 8752 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8753 QualType LHSTy, QualType RHSTy, 8754 ASTContext &Ctx) { 8755 if (!ResTy->isAnyPointerType()) 8756 return ResTy; 8757 8758 auto GetNullability = [&Ctx](QualType Ty) { 8759 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8760 if (Kind) { 8761 // For our purposes, treat _Nullable_result as _Nullable. 8762 if (*Kind == NullabilityKind::NullableResult) 8763 return NullabilityKind::Nullable; 8764 return *Kind; 8765 } 8766 return NullabilityKind::Unspecified; 8767 }; 8768 8769 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8770 NullabilityKind MergedKind; 8771 8772 // Compute nullability of a binary conditional expression. 8773 if (IsBin) { 8774 if (LHSKind == NullabilityKind::NonNull) 8775 MergedKind = NullabilityKind::NonNull; 8776 else 8777 MergedKind = RHSKind; 8778 // Compute nullability of a normal conditional expression. 8779 } else { 8780 if (LHSKind == NullabilityKind::Nullable || 8781 RHSKind == NullabilityKind::Nullable) 8782 MergedKind = NullabilityKind::Nullable; 8783 else if (LHSKind == NullabilityKind::NonNull) 8784 MergedKind = RHSKind; 8785 else if (RHSKind == NullabilityKind::NonNull) 8786 MergedKind = LHSKind; 8787 else 8788 MergedKind = NullabilityKind::Unspecified; 8789 } 8790 8791 // Return if ResTy already has the correct nullability. 8792 if (GetNullability(ResTy) == MergedKind) 8793 return ResTy; 8794 8795 // Strip all nullability from ResTy. 8796 while (ResTy->getNullability(Ctx)) 8797 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8798 8799 // Create a new AttributedType with the new nullability kind. 8800 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8801 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8802 } 8803 8804 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8805 /// in the case of a the GNU conditional expr extension. 8806 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8807 SourceLocation ColonLoc, 8808 Expr *CondExpr, Expr *LHSExpr, 8809 Expr *RHSExpr) { 8810 if (!Context.isDependenceAllowed()) { 8811 // C cannot handle TypoExpr nodes in the condition because it 8812 // doesn't handle dependent types properly, so make sure any TypoExprs have 8813 // been dealt with before checking the operands. 8814 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8815 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8816 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8817 8818 if (!CondResult.isUsable()) 8819 return ExprError(); 8820 8821 if (LHSExpr) { 8822 if (!LHSResult.isUsable()) 8823 return ExprError(); 8824 } 8825 8826 if (!RHSResult.isUsable()) 8827 return ExprError(); 8828 8829 CondExpr = CondResult.get(); 8830 LHSExpr = LHSResult.get(); 8831 RHSExpr = RHSResult.get(); 8832 } 8833 8834 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8835 // was the condition. 8836 OpaqueValueExpr *opaqueValue = nullptr; 8837 Expr *commonExpr = nullptr; 8838 if (!LHSExpr) { 8839 commonExpr = CondExpr; 8840 // Lower out placeholder types first. This is important so that we don't 8841 // try to capture a placeholder. This happens in few cases in C++; such 8842 // as Objective-C++'s dictionary subscripting syntax. 8843 if (commonExpr->hasPlaceholderType()) { 8844 ExprResult result = CheckPlaceholderExpr(commonExpr); 8845 if (!result.isUsable()) return ExprError(); 8846 commonExpr = result.get(); 8847 } 8848 // We usually want to apply unary conversions *before* saving, except 8849 // in the special case of a C++ l-value conditional. 8850 if (!(getLangOpts().CPlusPlus 8851 && !commonExpr->isTypeDependent() 8852 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8853 && commonExpr->isGLValue() 8854 && commonExpr->isOrdinaryOrBitFieldObject() 8855 && RHSExpr->isOrdinaryOrBitFieldObject() 8856 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8857 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8858 if (commonRes.isInvalid()) 8859 return ExprError(); 8860 commonExpr = commonRes.get(); 8861 } 8862 8863 // If the common expression is a class or array prvalue, materialize it 8864 // so that we can safely refer to it multiple times. 8865 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 8866 commonExpr->getType()->isArrayType())) { 8867 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8868 if (MatExpr.isInvalid()) 8869 return ExprError(); 8870 commonExpr = MatExpr.get(); 8871 } 8872 8873 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8874 commonExpr->getType(), 8875 commonExpr->getValueKind(), 8876 commonExpr->getObjectKind(), 8877 commonExpr); 8878 LHSExpr = CondExpr = opaqueValue; 8879 } 8880 8881 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8882 ExprValueKind VK = VK_PRValue; 8883 ExprObjectKind OK = OK_Ordinary; 8884 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8885 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8886 VK, OK, QuestionLoc); 8887 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8888 RHS.isInvalid()) 8889 return ExprError(); 8890 8891 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8892 RHS.get()); 8893 8894 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8895 8896 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8897 Context); 8898 8899 if (!commonExpr) 8900 return new (Context) 8901 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8902 RHS.get(), result, VK, OK); 8903 8904 return new (Context) BinaryConditionalOperator( 8905 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8906 ColonLoc, result, VK, OK); 8907 } 8908 8909 // Check if we have a conversion between incompatible cmse function pointer 8910 // types, that is, a conversion between a function pointer with the 8911 // cmse_nonsecure_call attribute and one without. 8912 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8913 QualType ToType) { 8914 if (const auto *ToFn = 8915 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8916 if (const auto *FromFn = 8917 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8918 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8919 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8920 8921 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8922 } 8923 } 8924 return false; 8925 } 8926 8927 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8928 // being closely modeled after the C99 spec:-). The odd characteristic of this 8929 // routine is it effectively iqnores the qualifiers on the top level pointee. 8930 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8931 // FIXME: add a couple examples in this comment. 8932 static Sema::AssignConvertType 8933 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8934 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8935 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8936 8937 // get the "pointed to" type (ignoring qualifiers at the top level) 8938 const Type *lhptee, *rhptee; 8939 Qualifiers lhq, rhq; 8940 std::tie(lhptee, lhq) = 8941 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8942 std::tie(rhptee, rhq) = 8943 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8944 8945 Sema::AssignConvertType ConvTy = Sema::Compatible; 8946 8947 // C99 6.5.16.1p1: This following citation is common to constraints 8948 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8949 // qualifiers of the type *pointed to* by the right; 8950 8951 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8952 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8953 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8954 // Ignore lifetime for further calculation. 8955 lhq.removeObjCLifetime(); 8956 rhq.removeObjCLifetime(); 8957 } 8958 8959 if (!lhq.compatiblyIncludes(rhq)) { 8960 // Treat address-space mismatches as fatal. 8961 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8962 return Sema::IncompatiblePointerDiscardsQualifiers; 8963 8964 // It's okay to add or remove GC or lifetime qualifiers when converting to 8965 // and from void*. 8966 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8967 .compatiblyIncludes( 8968 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8969 && (lhptee->isVoidType() || rhptee->isVoidType())) 8970 ; // keep old 8971 8972 // Treat lifetime mismatches as fatal. 8973 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8974 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8975 8976 // For GCC/MS compatibility, other qualifier mismatches are treated 8977 // as still compatible in C. 8978 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8979 } 8980 8981 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8982 // incomplete type and the other is a pointer to a qualified or unqualified 8983 // version of void... 8984 if (lhptee->isVoidType()) { 8985 if (rhptee->isIncompleteOrObjectType()) 8986 return ConvTy; 8987 8988 // As an extension, we allow cast to/from void* to function pointer. 8989 assert(rhptee->isFunctionType()); 8990 return Sema::FunctionVoidPointer; 8991 } 8992 8993 if (rhptee->isVoidType()) { 8994 if (lhptee->isIncompleteOrObjectType()) 8995 return ConvTy; 8996 8997 // As an extension, we allow cast to/from void* to function pointer. 8998 assert(lhptee->isFunctionType()); 8999 return Sema::FunctionVoidPointer; 9000 } 9001 9002 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 9003 // unqualified versions of compatible types, ... 9004 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 9005 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 9006 // Check if the pointee types are compatible ignoring the sign. 9007 // We explicitly check for char so that we catch "char" vs 9008 // "unsigned char" on systems where "char" is unsigned. 9009 if (lhptee->isCharType()) 9010 ltrans = S.Context.UnsignedCharTy; 9011 else if (lhptee->hasSignedIntegerRepresentation()) 9012 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 9013 9014 if (rhptee->isCharType()) 9015 rtrans = S.Context.UnsignedCharTy; 9016 else if (rhptee->hasSignedIntegerRepresentation()) 9017 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 9018 9019 if (ltrans == rtrans) { 9020 // Types are compatible ignoring the sign. Qualifier incompatibility 9021 // takes priority over sign incompatibility because the sign 9022 // warning can be disabled. 9023 if (ConvTy != Sema::Compatible) 9024 return ConvTy; 9025 9026 return Sema::IncompatiblePointerSign; 9027 } 9028 9029 // If we are a multi-level pointer, it's possible that our issue is simply 9030 // one of qualification - e.g. char ** -> const char ** is not allowed. If 9031 // the eventual target type is the same and the pointers have the same 9032 // level of indirection, this must be the issue. 9033 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 9034 do { 9035 std::tie(lhptee, lhq) = 9036 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 9037 std::tie(rhptee, rhq) = 9038 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 9039 9040 // Inconsistent address spaces at this point is invalid, even if the 9041 // address spaces would be compatible. 9042 // FIXME: This doesn't catch address space mismatches for pointers of 9043 // different nesting levels, like: 9044 // __local int *** a; 9045 // int ** b = a; 9046 // It's not clear how to actually determine when such pointers are 9047 // invalidly incompatible. 9048 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 9049 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 9050 9051 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 9052 9053 if (lhptee == rhptee) 9054 return Sema::IncompatibleNestedPointerQualifiers; 9055 } 9056 9057 // General pointer incompatibility takes priority over qualifiers. 9058 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9059 return Sema::IncompatibleFunctionPointer; 9060 return Sema::IncompatiblePointer; 9061 } 9062 if (!S.getLangOpts().CPlusPlus && 9063 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9064 return Sema::IncompatibleFunctionPointer; 9065 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9066 return Sema::IncompatibleFunctionPointer; 9067 return ConvTy; 9068 } 9069 9070 /// checkBlockPointerTypesForAssignment - This routine determines whether two 9071 /// block pointer types are compatible or whether a block and normal pointer 9072 /// are compatible. It is more restrict than comparing two function pointer 9073 // types. 9074 static Sema::AssignConvertType 9075 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9076 QualType RHSType) { 9077 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9078 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9079 9080 QualType lhptee, rhptee; 9081 9082 // get the "pointed to" type (ignoring qualifiers at the top level) 9083 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9084 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9085 9086 // In C++, the types have to match exactly. 9087 if (S.getLangOpts().CPlusPlus) 9088 return Sema::IncompatibleBlockPointer; 9089 9090 Sema::AssignConvertType ConvTy = Sema::Compatible; 9091 9092 // For blocks we enforce that qualifiers are identical. 9093 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9094 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9095 if (S.getLangOpts().OpenCL) { 9096 LQuals.removeAddressSpace(); 9097 RQuals.removeAddressSpace(); 9098 } 9099 if (LQuals != RQuals) 9100 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9101 9102 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9103 // assignment. 9104 // The current behavior is similar to C++ lambdas. A block might be 9105 // assigned to a variable iff its return type and parameters are compatible 9106 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9107 // an assignment. Presumably it should behave in way that a function pointer 9108 // assignment does in C, so for each parameter and return type: 9109 // * CVR and address space of LHS should be a superset of CVR and address 9110 // space of RHS. 9111 // * unqualified types should be compatible. 9112 if (S.getLangOpts().OpenCL) { 9113 if (!S.Context.typesAreBlockPointerCompatible( 9114 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9115 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9116 return Sema::IncompatibleBlockPointer; 9117 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9118 return Sema::IncompatibleBlockPointer; 9119 9120 return ConvTy; 9121 } 9122 9123 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9124 /// for assignment compatibility. 9125 static Sema::AssignConvertType 9126 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9127 QualType RHSType) { 9128 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9129 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9130 9131 if (LHSType->isObjCBuiltinType()) { 9132 // Class is not compatible with ObjC object pointers. 9133 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9134 !RHSType->isObjCQualifiedClassType()) 9135 return Sema::IncompatiblePointer; 9136 return Sema::Compatible; 9137 } 9138 if (RHSType->isObjCBuiltinType()) { 9139 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9140 !LHSType->isObjCQualifiedClassType()) 9141 return Sema::IncompatiblePointer; 9142 return Sema::Compatible; 9143 } 9144 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9145 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9146 9147 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9148 // make an exception for id<P> 9149 !LHSType->isObjCQualifiedIdType()) 9150 return Sema::CompatiblePointerDiscardsQualifiers; 9151 9152 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9153 return Sema::Compatible; 9154 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9155 return Sema::IncompatibleObjCQualifiedId; 9156 return Sema::IncompatiblePointer; 9157 } 9158 9159 Sema::AssignConvertType 9160 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9161 QualType LHSType, QualType RHSType) { 9162 // Fake up an opaque expression. We don't actually care about what 9163 // cast operations are required, so if CheckAssignmentConstraints 9164 // adds casts to this they'll be wasted, but fortunately that doesn't 9165 // usually happen on valid code. 9166 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 9167 ExprResult RHSPtr = &RHSExpr; 9168 CastKind K; 9169 9170 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9171 } 9172 9173 /// This helper function returns true if QT is a vector type that has element 9174 /// type ElementType. 9175 static bool isVector(QualType QT, QualType ElementType) { 9176 if (const VectorType *VT = QT->getAs<VectorType>()) 9177 return VT->getElementType().getCanonicalType() == ElementType; 9178 return false; 9179 } 9180 9181 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9182 /// has code to accommodate several GCC extensions when type checking 9183 /// pointers. Here are some objectionable examples that GCC considers warnings: 9184 /// 9185 /// int a, *pint; 9186 /// short *pshort; 9187 /// struct foo *pfoo; 9188 /// 9189 /// pint = pshort; // warning: assignment from incompatible pointer type 9190 /// a = pint; // warning: assignment makes integer from pointer without a cast 9191 /// pint = a; // warning: assignment makes pointer from integer without a cast 9192 /// pint = pfoo; // warning: assignment from incompatible pointer type 9193 /// 9194 /// As a result, the code for dealing with pointers is more complex than the 9195 /// C99 spec dictates. 9196 /// 9197 /// Sets 'Kind' for any result kind except Incompatible. 9198 Sema::AssignConvertType 9199 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9200 CastKind &Kind, bool ConvertRHS) { 9201 QualType RHSType = RHS.get()->getType(); 9202 QualType OrigLHSType = LHSType; 9203 9204 // Get canonical types. We're not formatting these types, just comparing 9205 // them. 9206 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9207 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9208 9209 // Common case: no conversion required. 9210 if (LHSType == RHSType) { 9211 Kind = CK_NoOp; 9212 return Compatible; 9213 } 9214 9215 // If we have an atomic type, try a non-atomic assignment, then just add an 9216 // atomic qualification step. 9217 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9218 Sema::AssignConvertType result = 9219 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9220 if (result != Compatible) 9221 return result; 9222 if (Kind != CK_NoOp && ConvertRHS) 9223 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9224 Kind = CK_NonAtomicToAtomic; 9225 return Compatible; 9226 } 9227 9228 // If the left-hand side is a reference type, then we are in a 9229 // (rare!) case where we've allowed the use of references in C, 9230 // e.g., as a parameter type in a built-in function. In this case, 9231 // just make sure that the type referenced is compatible with the 9232 // right-hand side type. The caller is responsible for adjusting 9233 // LHSType so that the resulting expression does not have reference 9234 // type. 9235 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9236 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9237 Kind = CK_LValueBitCast; 9238 return Compatible; 9239 } 9240 return Incompatible; 9241 } 9242 9243 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9244 // to the same ExtVector type. 9245 if (LHSType->isExtVectorType()) { 9246 if (RHSType->isExtVectorType()) 9247 return Incompatible; 9248 if (RHSType->isArithmeticType()) { 9249 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9250 if (ConvertRHS) 9251 RHS = prepareVectorSplat(LHSType, RHS.get()); 9252 Kind = CK_VectorSplat; 9253 return Compatible; 9254 } 9255 } 9256 9257 // Conversions to or from vector type. 9258 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9259 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9260 // Allow assignments of an AltiVec vector type to an equivalent GCC 9261 // vector type and vice versa 9262 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9263 Kind = CK_BitCast; 9264 return Compatible; 9265 } 9266 9267 // If we are allowing lax vector conversions, and LHS and RHS are both 9268 // vectors, the total size only needs to be the same. This is a bitcast; 9269 // no bits are changed but the result type is different. 9270 if (isLaxVectorConversion(RHSType, LHSType)) { 9271 Kind = CK_BitCast; 9272 return IncompatibleVectors; 9273 } 9274 } 9275 9276 // When the RHS comes from another lax conversion (e.g. binops between 9277 // scalars and vectors) the result is canonicalized as a vector. When the 9278 // LHS is also a vector, the lax is allowed by the condition above. Handle 9279 // the case where LHS is a scalar. 9280 if (LHSType->isScalarType()) { 9281 const VectorType *VecType = RHSType->getAs<VectorType>(); 9282 if (VecType && VecType->getNumElements() == 1 && 9283 isLaxVectorConversion(RHSType, LHSType)) { 9284 ExprResult *VecExpr = &RHS; 9285 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9286 Kind = CK_BitCast; 9287 return Compatible; 9288 } 9289 } 9290 9291 // Allow assignments between fixed-length and sizeless SVE vectors. 9292 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9293 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9294 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9295 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9296 Kind = CK_BitCast; 9297 return Compatible; 9298 } 9299 9300 return Incompatible; 9301 } 9302 9303 // Diagnose attempts to convert between __ibm128, __float128 and long double 9304 // where such conversions currently can't be handled. 9305 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9306 return Incompatible; 9307 9308 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9309 // discards the imaginary part. 9310 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9311 !LHSType->getAs<ComplexType>()) 9312 return Incompatible; 9313 9314 // Arithmetic conversions. 9315 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9316 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9317 if (ConvertRHS) 9318 Kind = PrepareScalarCast(RHS, LHSType); 9319 return Compatible; 9320 } 9321 9322 // Conversions to normal pointers. 9323 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9324 // U* -> T* 9325 if (isa<PointerType>(RHSType)) { 9326 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9327 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9328 if (AddrSpaceL != AddrSpaceR) 9329 Kind = CK_AddressSpaceConversion; 9330 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9331 Kind = CK_NoOp; 9332 else 9333 Kind = CK_BitCast; 9334 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9335 } 9336 9337 // int -> T* 9338 if (RHSType->isIntegerType()) { 9339 Kind = CK_IntegralToPointer; // FIXME: null? 9340 return IntToPointer; 9341 } 9342 9343 // C pointers are not compatible with ObjC object pointers, 9344 // with two exceptions: 9345 if (isa<ObjCObjectPointerType>(RHSType)) { 9346 // - conversions to void* 9347 if (LHSPointer->getPointeeType()->isVoidType()) { 9348 Kind = CK_BitCast; 9349 return Compatible; 9350 } 9351 9352 // - conversions from 'Class' to the redefinition type 9353 if (RHSType->isObjCClassType() && 9354 Context.hasSameType(LHSType, 9355 Context.getObjCClassRedefinitionType())) { 9356 Kind = CK_BitCast; 9357 return Compatible; 9358 } 9359 9360 Kind = CK_BitCast; 9361 return IncompatiblePointer; 9362 } 9363 9364 // U^ -> void* 9365 if (RHSType->getAs<BlockPointerType>()) { 9366 if (LHSPointer->getPointeeType()->isVoidType()) { 9367 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9368 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9369 ->getPointeeType() 9370 .getAddressSpace(); 9371 Kind = 9372 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9373 return Compatible; 9374 } 9375 } 9376 9377 return Incompatible; 9378 } 9379 9380 // Conversions to block pointers. 9381 if (isa<BlockPointerType>(LHSType)) { 9382 // U^ -> T^ 9383 if (RHSType->isBlockPointerType()) { 9384 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9385 ->getPointeeType() 9386 .getAddressSpace(); 9387 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9388 ->getPointeeType() 9389 .getAddressSpace(); 9390 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9391 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9392 } 9393 9394 // int or null -> T^ 9395 if (RHSType->isIntegerType()) { 9396 Kind = CK_IntegralToPointer; // FIXME: null 9397 return IntToBlockPointer; 9398 } 9399 9400 // id -> T^ 9401 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9402 Kind = CK_AnyPointerToBlockPointerCast; 9403 return Compatible; 9404 } 9405 9406 // void* -> T^ 9407 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9408 if (RHSPT->getPointeeType()->isVoidType()) { 9409 Kind = CK_AnyPointerToBlockPointerCast; 9410 return Compatible; 9411 } 9412 9413 return Incompatible; 9414 } 9415 9416 // Conversions to Objective-C pointers. 9417 if (isa<ObjCObjectPointerType>(LHSType)) { 9418 // A* -> B* 9419 if (RHSType->isObjCObjectPointerType()) { 9420 Kind = CK_BitCast; 9421 Sema::AssignConvertType result = 9422 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9423 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9424 result == Compatible && 9425 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9426 result = IncompatibleObjCWeakRef; 9427 return result; 9428 } 9429 9430 // int or null -> A* 9431 if (RHSType->isIntegerType()) { 9432 Kind = CK_IntegralToPointer; // FIXME: null 9433 return IntToPointer; 9434 } 9435 9436 // In general, C pointers are not compatible with ObjC object pointers, 9437 // with two exceptions: 9438 if (isa<PointerType>(RHSType)) { 9439 Kind = CK_CPointerToObjCPointerCast; 9440 9441 // - conversions from 'void*' 9442 if (RHSType->isVoidPointerType()) { 9443 return Compatible; 9444 } 9445 9446 // - conversions to 'Class' from its redefinition type 9447 if (LHSType->isObjCClassType() && 9448 Context.hasSameType(RHSType, 9449 Context.getObjCClassRedefinitionType())) { 9450 return Compatible; 9451 } 9452 9453 return IncompatiblePointer; 9454 } 9455 9456 // Only under strict condition T^ is compatible with an Objective-C pointer. 9457 if (RHSType->isBlockPointerType() && 9458 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9459 if (ConvertRHS) 9460 maybeExtendBlockObject(RHS); 9461 Kind = CK_BlockPointerToObjCPointerCast; 9462 return Compatible; 9463 } 9464 9465 return Incompatible; 9466 } 9467 9468 // Conversions from pointers that are not covered by the above. 9469 if (isa<PointerType>(RHSType)) { 9470 // T* -> _Bool 9471 if (LHSType == Context.BoolTy) { 9472 Kind = CK_PointerToBoolean; 9473 return Compatible; 9474 } 9475 9476 // T* -> int 9477 if (LHSType->isIntegerType()) { 9478 Kind = CK_PointerToIntegral; 9479 return PointerToInt; 9480 } 9481 9482 return Incompatible; 9483 } 9484 9485 // Conversions from Objective-C pointers that are not covered by the above. 9486 if (isa<ObjCObjectPointerType>(RHSType)) { 9487 // T* -> _Bool 9488 if (LHSType == Context.BoolTy) { 9489 Kind = CK_PointerToBoolean; 9490 return Compatible; 9491 } 9492 9493 // T* -> int 9494 if (LHSType->isIntegerType()) { 9495 Kind = CK_PointerToIntegral; 9496 return PointerToInt; 9497 } 9498 9499 return Incompatible; 9500 } 9501 9502 // struct A -> struct B 9503 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9504 if (Context.typesAreCompatible(LHSType, RHSType)) { 9505 Kind = CK_NoOp; 9506 return Compatible; 9507 } 9508 } 9509 9510 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9511 Kind = CK_IntToOCLSampler; 9512 return Compatible; 9513 } 9514 9515 return Incompatible; 9516 } 9517 9518 /// Constructs a transparent union from an expression that is 9519 /// used to initialize the transparent union. 9520 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9521 ExprResult &EResult, QualType UnionType, 9522 FieldDecl *Field) { 9523 // Build an initializer list that designates the appropriate member 9524 // of the transparent union. 9525 Expr *E = EResult.get(); 9526 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9527 E, SourceLocation()); 9528 Initializer->setType(UnionType); 9529 Initializer->setInitializedFieldInUnion(Field); 9530 9531 // Build a compound literal constructing a value of the transparent 9532 // union type from this initializer list. 9533 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9534 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9535 VK_PRValue, Initializer, false); 9536 } 9537 9538 Sema::AssignConvertType 9539 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9540 ExprResult &RHS) { 9541 QualType RHSType = RHS.get()->getType(); 9542 9543 // If the ArgType is a Union type, we want to handle a potential 9544 // transparent_union GCC extension. 9545 const RecordType *UT = ArgType->getAsUnionType(); 9546 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9547 return Incompatible; 9548 9549 // The field to initialize within the transparent union. 9550 RecordDecl *UD = UT->getDecl(); 9551 FieldDecl *InitField = nullptr; 9552 // It's compatible if the expression matches any of the fields. 9553 for (auto *it : UD->fields()) { 9554 if (it->getType()->isPointerType()) { 9555 // If the transparent union contains a pointer type, we allow: 9556 // 1) void pointer 9557 // 2) null pointer constant 9558 if (RHSType->isPointerType()) 9559 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9560 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9561 InitField = it; 9562 break; 9563 } 9564 9565 if (RHS.get()->isNullPointerConstant(Context, 9566 Expr::NPC_ValueDependentIsNull)) { 9567 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9568 CK_NullToPointer); 9569 InitField = it; 9570 break; 9571 } 9572 } 9573 9574 CastKind Kind; 9575 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9576 == Compatible) { 9577 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9578 InitField = it; 9579 break; 9580 } 9581 } 9582 9583 if (!InitField) 9584 return Incompatible; 9585 9586 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9587 return Compatible; 9588 } 9589 9590 Sema::AssignConvertType 9591 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9592 bool Diagnose, 9593 bool DiagnoseCFAudited, 9594 bool ConvertRHS) { 9595 // We need to be able to tell the caller whether we diagnosed a problem, if 9596 // they ask us to issue diagnostics. 9597 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9598 9599 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9600 // we can't avoid *all* modifications at the moment, so we need some somewhere 9601 // to put the updated value. 9602 ExprResult LocalRHS = CallerRHS; 9603 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9604 9605 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9606 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9607 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9608 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9609 Diag(RHS.get()->getExprLoc(), 9610 diag::warn_noderef_to_dereferenceable_pointer) 9611 << RHS.get()->getSourceRange(); 9612 } 9613 } 9614 } 9615 9616 if (getLangOpts().CPlusPlus) { 9617 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9618 // C++ 5.17p3: If the left operand is not of class type, the 9619 // expression is implicitly converted (C++ 4) to the 9620 // cv-unqualified type of the left operand. 9621 QualType RHSType = RHS.get()->getType(); 9622 if (Diagnose) { 9623 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9624 AA_Assigning); 9625 } else { 9626 ImplicitConversionSequence ICS = 9627 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9628 /*SuppressUserConversions=*/false, 9629 AllowedExplicit::None, 9630 /*InOverloadResolution=*/false, 9631 /*CStyle=*/false, 9632 /*AllowObjCWritebackConversion=*/false); 9633 if (ICS.isFailure()) 9634 return Incompatible; 9635 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9636 ICS, AA_Assigning); 9637 } 9638 if (RHS.isInvalid()) 9639 return Incompatible; 9640 Sema::AssignConvertType result = Compatible; 9641 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9642 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9643 result = IncompatibleObjCWeakRef; 9644 return result; 9645 } 9646 9647 // FIXME: Currently, we fall through and treat C++ classes like C 9648 // structures. 9649 // FIXME: We also fall through for atomics; not sure what should 9650 // happen there, though. 9651 } else if (RHS.get()->getType() == Context.OverloadTy) { 9652 // As a set of extensions to C, we support overloading on functions. These 9653 // functions need to be resolved here. 9654 DeclAccessPair DAP; 9655 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9656 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9657 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9658 else 9659 return Incompatible; 9660 } 9661 9662 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9663 // a null pointer constant. 9664 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9665 LHSType->isBlockPointerType()) && 9666 RHS.get()->isNullPointerConstant(Context, 9667 Expr::NPC_ValueDependentIsNull)) { 9668 if (Diagnose || ConvertRHS) { 9669 CastKind Kind; 9670 CXXCastPath Path; 9671 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9672 /*IgnoreBaseAccess=*/false, Diagnose); 9673 if (ConvertRHS) 9674 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 9675 } 9676 return Compatible; 9677 } 9678 9679 // OpenCL queue_t type assignment. 9680 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9681 Context, Expr::NPC_ValueDependentIsNull)) { 9682 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9683 return Compatible; 9684 } 9685 9686 // This check seems unnatural, however it is necessary to ensure the proper 9687 // conversion of functions/arrays. If the conversion were done for all 9688 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9689 // expressions that suppress this implicit conversion (&, sizeof). 9690 // 9691 // Suppress this for references: C++ 8.5.3p5. 9692 if (!LHSType->isReferenceType()) { 9693 // FIXME: We potentially allocate here even if ConvertRHS is false. 9694 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9695 if (RHS.isInvalid()) 9696 return Incompatible; 9697 } 9698 CastKind Kind; 9699 Sema::AssignConvertType result = 9700 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9701 9702 // C99 6.5.16.1p2: The value of the right operand is converted to the 9703 // type of the assignment expression. 9704 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9705 // so that we can use references in built-in functions even in C. 9706 // The getNonReferenceType() call makes sure that the resulting expression 9707 // does not have reference type. 9708 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9709 QualType Ty = LHSType.getNonLValueExprType(Context); 9710 Expr *E = RHS.get(); 9711 9712 // Check for various Objective-C errors. If we are not reporting 9713 // diagnostics and just checking for errors, e.g., during overload 9714 // resolution, return Incompatible to indicate the failure. 9715 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9716 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9717 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9718 if (!Diagnose) 9719 return Incompatible; 9720 } 9721 if (getLangOpts().ObjC && 9722 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9723 E->getType(), E, Diagnose) || 9724 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9725 if (!Diagnose) 9726 return Incompatible; 9727 // Replace the expression with a corrected version and continue so we 9728 // can find further errors. 9729 RHS = E; 9730 return Compatible; 9731 } 9732 9733 if (ConvertRHS) 9734 RHS = ImpCastExprToType(E, Ty, Kind); 9735 } 9736 9737 return result; 9738 } 9739 9740 namespace { 9741 /// The original operand to an operator, prior to the application of the usual 9742 /// arithmetic conversions and converting the arguments of a builtin operator 9743 /// candidate. 9744 struct OriginalOperand { 9745 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9746 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9747 Op = MTE->getSubExpr(); 9748 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9749 Op = BTE->getSubExpr(); 9750 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9751 Orig = ICE->getSubExprAsWritten(); 9752 Conversion = ICE->getConversionFunction(); 9753 } 9754 } 9755 9756 QualType getType() const { return Orig->getType(); } 9757 9758 Expr *Orig; 9759 NamedDecl *Conversion; 9760 }; 9761 } 9762 9763 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9764 ExprResult &RHS) { 9765 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9766 9767 Diag(Loc, diag::err_typecheck_invalid_operands) 9768 << OrigLHS.getType() << OrigRHS.getType() 9769 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9770 9771 // If a user-defined conversion was applied to either of the operands prior 9772 // to applying the built-in operator rules, tell the user about it. 9773 if (OrigLHS.Conversion) { 9774 Diag(OrigLHS.Conversion->getLocation(), 9775 diag::note_typecheck_invalid_operands_converted) 9776 << 0 << LHS.get()->getType(); 9777 } 9778 if (OrigRHS.Conversion) { 9779 Diag(OrigRHS.Conversion->getLocation(), 9780 diag::note_typecheck_invalid_operands_converted) 9781 << 1 << RHS.get()->getType(); 9782 } 9783 9784 return QualType(); 9785 } 9786 9787 // Diagnose cases where a scalar was implicitly converted to a vector and 9788 // diagnose the underlying types. Otherwise, diagnose the error 9789 // as invalid vector logical operands for non-C++ cases. 9790 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9791 ExprResult &RHS) { 9792 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9793 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9794 9795 bool LHSNatVec = LHSType->isVectorType(); 9796 bool RHSNatVec = RHSType->isVectorType(); 9797 9798 if (!(LHSNatVec && RHSNatVec)) { 9799 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9800 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9801 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9802 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9803 << Vector->getSourceRange(); 9804 return QualType(); 9805 } 9806 9807 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9808 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9809 << RHS.get()->getSourceRange(); 9810 9811 return QualType(); 9812 } 9813 9814 /// Try to convert a value of non-vector type to a vector type by converting 9815 /// the type to the element type of the vector and then performing a splat. 9816 /// If the language is OpenCL, we only use conversions that promote scalar 9817 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9818 /// for float->int. 9819 /// 9820 /// OpenCL V2.0 6.2.6.p2: 9821 /// An error shall occur if any scalar operand type has greater rank 9822 /// than the type of the vector element. 9823 /// 9824 /// \param scalar - if non-null, actually perform the conversions 9825 /// \return true if the operation fails (but without diagnosing the failure) 9826 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9827 QualType scalarTy, 9828 QualType vectorEltTy, 9829 QualType vectorTy, 9830 unsigned &DiagID) { 9831 // The conversion to apply to the scalar before splatting it, 9832 // if necessary. 9833 CastKind scalarCast = CK_NoOp; 9834 9835 if (vectorEltTy->isIntegralType(S.Context)) { 9836 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9837 (scalarTy->isIntegerType() && 9838 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9839 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9840 return true; 9841 } 9842 if (!scalarTy->isIntegralType(S.Context)) 9843 return true; 9844 scalarCast = CK_IntegralCast; 9845 } else if (vectorEltTy->isRealFloatingType()) { 9846 if (scalarTy->isRealFloatingType()) { 9847 if (S.getLangOpts().OpenCL && 9848 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9849 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9850 return true; 9851 } 9852 scalarCast = CK_FloatingCast; 9853 } 9854 else if (scalarTy->isIntegralType(S.Context)) 9855 scalarCast = CK_IntegralToFloating; 9856 else 9857 return true; 9858 } else { 9859 return true; 9860 } 9861 9862 // Adjust scalar if desired. 9863 if (scalar) { 9864 if (scalarCast != CK_NoOp) 9865 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9866 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9867 } 9868 return false; 9869 } 9870 9871 /// Convert vector E to a vector with the same number of elements but different 9872 /// element type. 9873 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9874 const auto *VecTy = E->getType()->getAs<VectorType>(); 9875 assert(VecTy && "Expression E must be a vector"); 9876 QualType NewVecTy = S.Context.getVectorType(ElementType, 9877 VecTy->getNumElements(), 9878 VecTy->getVectorKind()); 9879 9880 // Look through the implicit cast. Return the subexpression if its type is 9881 // NewVecTy. 9882 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9883 if (ICE->getSubExpr()->getType() == NewVecTy) 9884 return ICE->getSubExpr(); 9885 9886 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9887 return S.ImpCastExprToType(E, NewVecTy, Cast); 9888 } 9889 9890 /// Test if a (constant) integer Int can be casted to another integer type 9891 /// IntTy without losing precision. 9892 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9893 QualType OtherIntTy) { 9894 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9895 9896 // Reject cases where the value of the Int is unknown as that would 9897 // possibly cause truncation, but accept cases where the scalar can be 9898 // demoted without loss of precision. 9899 Expr::EvalResult EVResult; 9900 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9901 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9902 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9903 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9904 9905 if (CstInt) { 9906 // If the scalar is constant and is of a higher order and has more active 9907 // bits that the vector element type, reject it. 9908 llvm::APSInt Result = EVResult.Val.getInt(); 9909 unsigned NumBits = IntSigned 9910 ? (Result.isNegative() ? Result.getMinSignedBits() 9911 : Result.getActiveBits()) 9912 : Result.getActiveBits(); 9913 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9914 return true; 9915 9916 // If the signedness of the scalar type and the vector element type 9917 // differs and the number of bits is greater than that of the vector 9918 // element reject it. 9919 return (IntSigned != OtherIntSigned && 9920 NumBits > S.Context.getIntWidth(OtherIntTy)); 9921 } 9922 9923 // Reject cases where the value of the scalar is not constant and it's 9924 // order is greater than that of the vector element type. 9925 return (Order < 0); 9926 } 9927 9928 /// Test if a (constant) integer Int can be casted to floating point type 9929 /// FloatTy without losing precision. 9930 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9931 QualType FloatTy) { 9932 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9933 9934 // Determine if the integer constant can be expressed as a floating point 9935 // number of the appropriate type. 9936 Expr::EvalResult EVResult; 9937 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9938 9939 uint64_t Bits = 0; 9940 if (CstInt) { 9941 // Reject constants that would be truncated if they were converted to 9942 // the floating point type. Test by simple to/from conversion. 9943 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9944 // could be avoided if there was a convertFromAPInt method 9945 // which could signal back if implicit truncation occurred. 9946 llvm::APSInt Result = EVResult.Val.getInt(); 9947 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9948 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9949 llvm::APFloat::rmTowardZero); 9950 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9951 !IntTy->hasSignedIntegerRepresentation()); 9952 bool Ignored = false; 9953 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9954 &Ignored); 9955 if (Result != ConvertBack) 9956 return true; 9957 } else { 9958 // Reject types that cannot be fully encoded into the mantissa of 9959 // the float. 9960 Bits = S.Context.getTypeSize(IntTy); 9961 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9962 S.Context.getFloatTypeSemantics(FloatTy)); 9963 if (Bits > FloatPrec) 9964 return true; 9965 } 9966 9967 return false; 9968 } 9969 9970 /// Attempt to convert and splat Scalar into a vector whose types matches 9971 /// Vector following GCC conversion rules. The rule is that implicit 9972 /// conversion can occur when Scalar can be casted to match Vector's element 9973 /// type without causing truncation of Scalar. 9974 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9975 ExprResult *Vector) { 9976 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9977 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9978 const VectorType *VT = VectorTy->getAs<VectorType>(); 9979 9980 assert(!isa<ExtVectorType>(VT) && 9981 "ExtVectorTypes should not be handled here!"); 9982 9983 QualType VectorEltTy = VT->getElementType(); 9984 9985 // Reject cases where the vector element type or the scalar element type are 9986 // not integral or floating point types. 9987 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9988 return true; 9989 9990 // The conversion to apply to the scalar before splatting it, 9991 // if necessary. 9992 CastKind ScalarCast = CK_NoOp; 9993 9994 // Accept cases where the vector elements are integers and the scalar is 9995 // an integer. 9996 // FIXME: Notionally if the scalar was a floating point value with a precise 9997 // integral representation, we could cast it to an appropriate integer 9998 // type and then perform the rest of the checks here. GCC will perform 9999 // this conversion in some cases as determined by the input language. 10000 // We should accept it on a language independent basis. 10001 if (VectorEltTy->isIntegralType(S.Context) && 10002 ScalarTy->isIntegralType(S.Context) && 10003 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 10004 10005 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 10006 return true; 10007 10008 ScalarCast = CK_IntegralCast; 10009 } else if (VectorEltTy->isIntegralType(S.Context) && 10010 ScalarTy->isRealFloatingType()) { 10011 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 10012 ScalarCast = CK_FloatingToIntegral; 10013 else 10014 return true; 10015 } else if (VectorEltTy->isRealFloatingType()) { 10016 if (ScalarTy->isRealFloatingType()) { 10017 10018 // Reject cases where the scalar type is not a constant and has a higher 10019 // Order than the vector element type. 10020 llvm::APFloat Result(0.0); 10021 10022 // Determine whether this is a constant scalar. In the event that the 10023 // value is dependent (and thus cannot be evaluated by the constant 10024 // evaluator), skip the evaluation. This will then diagnose once the 10025 // expression is instantiated. 10026 bool CstScalar = Scalar->get()->isValueDependent() || 10027 Scalar->get()->EvaluateAsFloat(Result, S.Context); 10028 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 10029 if (!CstScalar && Order < 0) 10030 return true; 10031 10032 // If the scalar cannot be safely casted to the vector element type, 10033 // reject it. 10034 if (CstScalar) { 10035 bool Truncated = false; 10036 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 10037 llvm::APFloat::rmNearestTiesToEven, &Truncated); 10038 if (Truncated) 10039 return true; 10040 } 10041 10042 ScalarCast = CK_FloatingCast; 10043 } else if (ScalarTy->isIntegralType(S.Context)) { 10044 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 10045 return true; 10046 10047 ScalarCast = CK_IntegralToFloating; 10048 } else 10049 return true; 10050 } else if (ScalarTy->isEnumeralType()) 10051 return true; 10052 10053 // Adjust scalar if desired. 10054 if (Scalar) { 10055 if (ScalarCast != CK_NoOp) 10056 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 10057 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 10058 } 10059 return false; 10060 } 10061 10062 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 10063 SourceLocation Loc, bool IsCompAssign, 10064 bool AllowBothBool, 10065 bool AllowBoolConversions) { 10066 if (!IsCompAssign) { 10067 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10068 if (LHS.isInvalid()) 10069 return QualType(); 10070 } 10071 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10072 if (RHS.isInvalid()) 10073 return QualType(); 10074 10075 // For conversion purposes, we ignore any qualifiers. 10076 // For example, "const float" and "float" are equivalent. 10077 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10078 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10079 10080 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10081 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10082 assert(LHSVecType || RHSVecType); 10083 10084 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10085 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10086 return InvalidOperands(Loc, LHS, RHS); 10087 10088 // AltiVec-style "vector bool op vector bool" combinations are allowed 10089 // for some operators but not others. 10090 if (!AllowBothBool && 10091 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10092 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10093 return InvalidOperands(Loc, LHS, RHS); 10094 10095 // If the vector types are identical, return. 10096 if (Context.hasSameType(LHSType, RHSType)) 10097 return LHSType; 10098 10099 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10100 if (LHSVecType && RHSVecType && 10101 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10102 if (isa<ExtVectorType>(LHSVecType)) { 10103 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10104 return LHSType; 10105 } 10106 10107 if (!IsCompAssign) 10108 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10109 return RHSType; 10110 } 10111 10112 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10113 // can be mixed, with the result being the non-bool type. The non-bool 10114 // operand must have integer element type. 10115 if (AllowBoolConversions && LHSVecType && RHSVecType && 10116 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10117 (Context.getTypeSize(LHSVecType->getElementType()) == 10118 Context.getTypeSize(RHSVecType->getElementType()))) { 10119 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10120 LHSVecType->getElementType()->isIntegerType() && 10121 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10122 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10123 return LHSType; 10124 } 10125 if (!IsCompAssign && 10126 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10127 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10128 RHSVecType->getElementType()->isIntegerType()) { 10129 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10130 return RHSType; 10131 } 10132 } 10133 10134 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10135 // since the ambiguity can affect the ABI. 10136 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10137 const VectorType *VecType = SecondType->getAs<VectorType>(); 10138 return FirstType->isSizelessBuiltinType() && VecType && 10139 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10140 VecType->getVectorKind() == 10141 VectorType::SveFixedLengthPredicateVector); 10142 }; 10143 10144 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10145 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10146 return QualType(); 10147 } 10148 10149 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10150 // since the ambiguity can affect the ABI. 10151 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10152 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10153 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10154 10155 if (FirstVecType && SecondVecType) 10156 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10157 (SecondVecType->getVectorKind() == 10158 VectorType::SveFixedLengthDataVector || 10159 SecondVecType->getVectorKind() == 10160 VectorType::SveFixedLengthPredicateVector); 10161 10162 return FirstType->isSizelessBuiltinType() && SecondVecType && 10163 SecondVecType->getVectorKind() == VectorType::GenericVector; 10164 }; 10165 10166 if (IsSveGnuConversion(LHSType, RHSType) || 10167 IsSveGnuConversion(RHSType, LHSType)) { 10168 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10169 return QualType(); 10170 } 10171 10172 // If there's a vector type and a scalar, try to convert the scalar to 10173 // the vector element type and splat. 10174 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10175 if (!RHSVecType) { 10176 if (isa<ExtVectorType>(LHSVecType)) { 10177 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10178 LHSVecType->getElementType(), LHSType, 10179 DiagID)) 10180 return LHSType; 10181 } else { 10182 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10183 return LHSType; 10184 } 10185 } 10186 if (!LHSVecType) { 10187 if (isa<ExtVectorType>(RHSVecType)) { 10188 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10189 LHSType, RHSVecType->getElementType(), 10190 RHSType, DiagID)) 10191 return RHSType; 10192 } else { 10193 if (LHS.get()->isLValue() || 10194 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10195 return RHSType; 10196 } 10197 } 10198 10199 // FIXME: The code below also handles conversion between vectors and 10200 // non-scalars, we should break this down into fine grained specific checks 10201 // and emit proper diagnostics. 10202 QualType VecType = LHSVecType ? LHSType : RHSType; 10203 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10204 QualType OtherType = LHSVecType ? RHSType : LHSType; 10205 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10206 if (isLaxVectorConversion(OtherType, VecType)) { 10207 // If we're allowing lax vector conversions, only the total (data) size 10208 // needs to be the same. For non compound assignment, if one of the types is 10209 // scalar, the result is always the vector type. 10210 if (!IsCompAssign) { 10211 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10212 return VecType; 10213 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10214 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10215 // type. Note that this is already done by non-compound assignments in 10216 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10217 // <1 x T> -> T. The result is also a vector type. 10218 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10219 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10220 ExprResult *RHSExpr = &RHS; 10221 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10222 return VecType; 10223 } 10224 } 10225 10226 // Okay, the expression is invalid. 10227 10228 // If there's a non-vector, non-real operand, diagnose that. 10229 if ((!RHSVecType && !RHSType->isRealType()) || 10230 (!LHSVecType && !LHSType->isRealType())) { 10231 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10232 << LHSType << RHSType 10233 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10234 return QualType(); 10235 } 10236 10237 // OpenCL V1.1 6.2.6.p1: 10238 // If the operands are of more than one vector type, then an error shall 10239 // occur. Implicit conversions between vector types are not permitted, per 10240 // section 6.2.1. 10241 if (getLangOpts().OpenCL && 10242 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10243 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10244 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10245 << RHSType; 10246 return QualType(); 10247 } 10248 10249 10250 // If there is a vector type that is not a ExtVector and a scalar, we reach 10251 // this point if scalar could not be converted to the vector's element type 10252 // without truncation. 10253 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10254 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10255 QualType Scalar = LHSVecType ? RHSType : LHSType; 10256 QualType Vector = LHSVecType ? LHSType : RHSType; 10257 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10258 Diag(Loc, 10259 diag::err_typecheck_vector_not_convertable_implict_truncation) 10260 << ScalarOrVector << Scalar << Vector; 10261 10262 return QualType(); 10263 } 10264 10265 // Otherwise, use the generic diagnostic. 10266 Diag(Loc, DiagID) 10267 << LHSType << RHSType 10268 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10269 return QualType(); 10270 } 10271 10272 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10273 // expression. These are mainly cases where the null pointer is used as an 10274 // integer instead of a pointer. 10275 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10276 SourceLocation Loc, bool IsCompare) { 10277 // The canonical way to check for a GNU null is with isNullPointerConstant, 10278 // but we use a bit of a hack here for speed; this is a relatively 10279 // hot path, and isNullPointerConstant is slow. 10280 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10281 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10282 10283 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10284 10285 // Avoid analyzing cases where the result will either be invalid (and 10286 // diagnosed as such) or entirely valid and not something to warn about. 10287 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10288 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10289 return; 10290 10291 // Comparison operations would not make sense with a null pointer no matter 10292 // what the other expression is. 10293 if (!IsCompare) { 10294 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10295 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10296 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10297 return; 10298 } 10299 10300 // The rest of the operations only make sense with a null pointer 10301 // if the other expression is a pointer. 10302 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10303 NonNullType->canDecayToPointerType()) 10304 return; 10305 10306 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10307 << LHSNull /* LHS is NULL */ << NonNullType 10308 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10309 } 10310 10311 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10312 SourceLocation Loc) { 10313 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10314 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10315 if (!LUE || !RUE) 10316 return; 10317 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10318 RUE->getKind() != UETT_SizeOf) 10319 return; 10320 10321 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10322 QualType LHSTy = LHSArg->getType(); 10323 QualType RHSTy; 10324 10325 if (RUE->isArgumentType()) 10326 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10327 else 10328 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10329 10330 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10331 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10332 return; 10333 10334 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10335 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10336 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10337 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10338 << LHSArgDecl; 10339 } 10340 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10341 QualType ArrayElemTy = ArrayTy->getElementType(); 10342 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10343 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10344 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10345 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10346 return; 10347 S.Diag(Loc, diag::warn_division_sizeof_array) 10348 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10349 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10350 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10351 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10352 << LHSArgDecl; 10353 } 10354 10355 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10356 } 10357 } 10358 10359 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10360 ExprResult &RHS, 10361 SourceLocation Loc, bool IsDiv) { 10362 // Check for division/remainder by zero. 10363 Expr::EvalResult RHSValue; 10364 if (!RHS.get()->isValueDependent() && 10365 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10366 RHSValue.Val.getInt() == 0) 10367 S.DiagRuntimeBehavior(Loc, RHS.get(), 10368 S.PDiag(diag::warn_remainder_division_by_zero) 10369 << IsDiv << RHS.get()->getSourceRange()); 10370 } 10371 10372 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10373 SourceLocation Loc, 10374 bool IsCompAssign, bool IsDiv) { 10375 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10376 10377 QualType LHSTy = LHS.get()->getType(); 10378 QualType RHSTy = RHS.get()->getType(); 10379 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10380 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10381 /*AllowBothBool*/getLangOpts().AltiVec, 10382 /*AllowBoolConversions*/false); 10383 if (!IsDiv && 10384 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10385 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10386 // For division, only matrix-by-scalar is supported. Other combinations with 10387 // matrix types are invalid. 10388 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10389 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10390 10391 QualType compType = UsualArithmeticConversions( 10392 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10393 if (LHS.isInvalid() || RHS.isInvalid()) 10394 return QualType(); 10395 10396 10397 if (compType.isNull() || !compType->isArithmeticType()) 10398 return InvalidOperands(Loc, LHS, RHS); 10399 if (IsDiv) { 10400 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10401 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10402 } 10403 return compType; 10404 } 10405 10406 QualType Sema::CheckRemainderOperands( 10407 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10408 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10409 10410 if (LHS.get()->getType()->isVectorType() || 10411 RHS.get()->getType()->isVectorType()) { 10412 if (LHS.get()->getType()->hasIntegerRepresentation() && 10413 RHS.get()->getType()->hasIntegerRepresentation()) 10414 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10415 /*AllowBothBool*/getLangOpts().AltiVec, 10416 /*AllowBoolConversions*/false); 10417 return InvalidOperands(Loc, LHS, RHS); 10418 } 10419 10420 QualType compType = UsualArithmeticConversions( 10421 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10422 if (LHS.isInvalid() || RHS.isInvalid()) 10423 return QualType(); 10424 10425 if (compType.isNull() || !compType->isIntegerType()) 10426 return InvalidOperands(Loc, LHS, RHS); 10427 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10428 return compType; 10429 } 10430 10431 /// Diagnose invalid arithmetic on two void pointers. 10432 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10433 Expr *LHSExpr, Expr *RHSExpr) { 10434 S.Diag(Loc, S.getLangOpts().CPlusPlus 10435 ? diag::err_typecheck_pointer_arith_void_type 10436 : diag::ext_gnu_void_ptr) 10437 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10438 << RHSExpr->getSourceRange(); 10439 } 10440 10441 /// Diagnose invalid arithmetic on a void pointer. 10442 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10443 Expr *Pointer) { 10444 S.Diag(Loc, S.getLangOpts().CPlusPlus 10445 ? diag::err_typecheck_pointer_arith_void_type 10446 : diag::ext_gnu_void_ptr) 10447 << 0 /* one pointer */ << Pointer->getSourceRange(); 10448 } 10449 10450 /// Diagnose invalid arithmetic on a null pointer. 10451 /// 10452 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10453 /// idiom, which we recognize as a GNU extension. 10454 /// 10455 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10456 Expr *Pointer, bool IsGNUIdiom) { 10457 if (IsGNUIdiom) 10458 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10459 << Pointer->getSourceRange(); 10460 else 10461 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10462 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10463 } 10464 10465 /// Diagnose invalid subraction on a null pointer. 10466 /// 10467 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, 10468 Expr *Pointer, bool BothNull) { 10469 // Null - null is valid in C++ [expr.add]p7 10470 if (BothNull && S.getLangOpts().CPlusPlus) 10471 return; 10472 10473 // Is this s a macro from a system header? 10474 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) 10475 return; 10476 10477 S.Diag(Loc, diag::warn_pointer_sub_null_ptr) 10478 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10479 } 10480 10481 /// Diagnose invalid arithmetic on two function pointers. 10482 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10483 Expr *LHS, Expr *RHS) { 10484 assert(LHS->getType()->isAnyPointerType()); 10485 assert(RHS->getType()->isAnyPointerType()); 10486 S.Diag(Loc, S.getLangOpts().CPlusPlus 10487 ? diag::err_typecheck_pointer_arith_function_type 10488 : diag::ext_gnu_ptr_func_arith) 10489 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10490 // We only show the second type if it differs from the first. 10491 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10492 RHS->getType()) 10493 << RHS->getType()->getPointeeType() 10494 << LHS->getSourceRange() << RHS->getSourceRange(); 10495 } 10496 10497 /// Diagnose invalid arithmetic on a function pointer. 10498 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10499 Expr *Pointer) { 10500 assert(Pointer->getType()->isAnyPointerType()); 10501 S.Diag(Loc, S.getLangOpts().CPlusPlus 10502 ? diag::err_typecheck_pointer_arith_function_type 10503 : diag::ext_gnu_ptr_func_arith) 10504 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10505 << 0 /* one pointer, so only one type */ 10506 << Pointer->getSourceRange(); 10507 } 10508 10509 /// Emit error if Operand is incomplete pointer type 10510 /// 10511 /// \returns True if pointer has incomplete type 10512 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10513 Expr *Operand) { 10514 QualType ResType = Operand->getType(); 10515 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10516 ResType = ResAtomicType->getValueType(); 10517 10518 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10519 QualType PointeeTy = ResType->getPointeeType(); 10520 return S.RequireCompleteSizedType( 10521 Loc, PointeeTy, 10522 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10523 Operand->getSourceRange()); 10524 } 10525 10526 /// Check the validity of an arithmetic pointer operand. 10527 /// 10528 /// If the operand has pointer type, this code will check for pointer types 10529 /// which are invalid in arithmetic operations. These will be diagnosed 10530 /// appropriately, including whether or not the use is supported as an 10531 /// extension. 10532 /// 10533 /// \returns True when the operand is valid to use (even if as an extension). 10534 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10535 Expr *Operand) { 10536 QualType ResType = Operand->getType(); 10537 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10538 ResType = ResAtomicType->getValueType(); 10539 10540 if (!ResType->isAnyPointerType()) return true; 10541 10542 QualType PointeeTy = ResType->getPointeeType(); 10543 if (PointeeTy->isVoidType()) { 10544 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10545 return !S.getLangOpts().CPlusPlus; 10546 } 10547 if (PointeeTy->isFunctionType()) { 10548 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10549 return !S.getLangOpts().CPlusPlus; 10550 } 10551 10552 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10553 10554 return true; 10555 } 10556 10557 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10558 /// operands. 10559 /// 10560 /// This routine will diagnose any invalid arithmetic on pointer operands much 10561 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10562 /// for emitting a single diagnostic even for operations where both LHS and RHS 10563 /// are (potentially problematic) pointers. 10564 /// 10565 /// \returns True when the operand is valid to use (even if as an extension). 10566 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10567 Expr *LHSExpr, Expr *RHSExpr) { 10568 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10569 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10570 if (!isLHSPointer && !isRHSPointer) return true; 10571 10572 QualType LHSPointeeTy, RHSPointeeTy; 10573 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10574 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10575 10576 // if both are pointers check if operation is valid wrt address spaces 10577 if (isLHSPointer && isRHSPointer) { 10578 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10579 S.Diag(Loc, 10580 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10581 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10582 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10583 return false; 10584 } 10585 } 10586 10587 // Check for arithmetic on pointers to incomplete types. 10588 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10589 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10590 if (isLHSVoidPtr || isRHSVoidPtr) { 10591 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10592 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10593 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10594 10595 return !S.getLangOpts().CPlusPlus; 10596 } 10597 10598 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10599 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10600 if (isLHSFuncPtr || isRHSFuncPtr) { 10601 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10602 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10603 RHSExpr); 10604 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10605 10606 return !S.getLangOpts().CPlusPlus; 10607 } 10608 10609 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10610 return false; 10611 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10612 return false; 10613 10614 return true; 10615 } 10616 10617 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10618 /// literal. 10619 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10620 Expr *LHSExpr, Expr *RHSExpr) { 10621 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10622 Expr* IndexExpr = RHSExpr; 10623 if (!StrExpr) { 10624 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10625 IndexExpr = LHSExpr; 10626 } 10627 10628 bool IsStringPlusInt = StrExpr && 10629 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10630 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10631 return; 10632 10633 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10634 Self.Diag(OpLoc, diag::warn_string_plus_int) 10635 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10636 10637 // Only print a fixit for "str" + int, not for int + "str". 10638 if (IndexExpr == RHSExpr) { 10639 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10640 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10641 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10642 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10643 << FixItHint::CreateInsertion(EndLoc, "]"); 10644 } else 10645 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10646 } 10647 10648 /// Emit a warning when adding a char literal to a string. 10649 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10650 Expr *LHSExpr, Expr *RHSExpr) { 10651 const Expr *StringRefExpr = LHSExpr; 10652 const CharacterLiteral *CharExpr = 10653 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10654 10655 if (!CharExpr) { 10656 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10657 StringRefExpr = RHSExpr; 10658 } 10659 10660 if (!CharExpr || !StringRefExpr) 10661 return; 10662 10663 const QualType StringType = StringRefExpr->getType(); 10664 10665 // Return if not a PointerType. 10666 if (!StringType->isAnyPointerType()) 10667 return; 10668 10669 // Return if not a CharacterType. 10670 if (!StringType->getPointeeType()->isAnyCharacterType()) 10671 return; 10672 10673 ASTContext &Ctx = Self.getASTContext(); 10674 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10675 10676 const QualType CharType = CharExpr->getType(); 10677 if (!CharType->isAnyCharacterType() && 10678 CharType->isIntegerType() && 10679 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10680 Self.Diag(OpLoc, diag::warn_string_plus_char) 10681 << DiagRange << Ctx.CharTy; 10682 } else { 10683 Self.Diag(OpLoc, diag::warn_string_plus_char) 10684 << DiagRange << CharExpr->getType(); 10685 } 10686 10687 // Only print a fixit for str + char, not for char + str. 10688 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10689 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10690 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10691 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10692 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10693 << FixItHint::CreateInsertion(EndLoc, "]"); 10694 } else { 10695 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10696 } 10697 } 10698 10699 /// Emit error when two pointers are incompatible. 10700 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10701 Expr *LHSExpr, Expr *RHSExpr) { 10702 assert(LHSExpr->getType()->isAnyPointerType()); 10703 assert(RHSExpr->getType()->isAnyPointerType()); 10704 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10705 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10706 << RHSExpr->getSourceRange(); 10707 } 10708 10709 // C99 6.5.6 10710 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10711 SourceLocation Loc, BinaryOperatorKind Opc, 10712 QualType* CompLHSTy) { 10713 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10714 10715 if (LHS.get()->getType()->isVectorType() || 10716 RHS.get()->getType()->isVectorType()) { 10717 QualType compType = CheckVectorOperands( 10718 LHS, RHS, Loc, CompLHSTy, 10719 /*AllowBothBool*/getLangOpts().AltiVec, 10720 /*AllowBoolConversions*/getLangOpts().ZVector); 10721 if (CompLHSTy) *CompLHSTy = compType; 10722 return compType; 10723 } 10724 10725 if (LHS.get()->getType()->isConstantMatrixType() || 10726 RHS.get()->getType()->isConstantMatrixType()) { 10727 QualType compType = 10728 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10729 if (CompLHSTy) 10730 *CompLHSTy = compType; 10731 return compType; 10732 } 10733 10734 QualType compType = UsualArithmeticConversions( 10735 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10736 if (LHS.isInvalid() || RHS.isInvalid()) 10737 return QualType(); 10738 10739 // Diagnose "string literal" '+' int and string '+' "char literal". 10740 if (Opc == BO_Add) { 10741 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10742 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10743 } 10744 10745 // handle the common case first (both operands are arithmetic). 10746 if (!compType.isNull() && compType->isArithmeticType()) { 10747 if (CompLHSTy) *CompLHSTy = compType; 10748 return compType; 10749 } 10750 10751 // Type-checking. Ultimately the pointer's going to be in PExp; 10752 // note that we bias towards the LHS being the pointer. 10753 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10754 10755 bool isObjCPointer; 10756 if (PExp->getType()->isPointerType()) { 10757 isObjCPointer = false; 10758 } else if (PExp->getType()->isObjCObjectPointerType()) { 10759 isObjCPointer = true; 10760 } else { 10761 std::swap(PExp, IExp); 10762 if (PExp->getType()->isPointerType()) { 10763 isObjCPointer = false; 10764 } else if (PExp->getType()->isObjCObjectPointerType()) { 10765 isObjCPointer = true; 10766 } else { 10767 return InvalidOperands(Loc, LHS, RHS); 10768 } 10769 } 10770 assert(PExp->getType()->isAnyPointerType()); 10771 10772 if (!IExp->getType()->isIntegerType()) 10773 return InvalidOperands(Loc, LHS, RHS); 10774 10775 // Adding to a null pointer results in undefined behavior. 10776 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10777 Context, Expr::NPC_ValueDependentIsNotNull)) { 10778 // In C++ adding zero to a null pointer is defined. 10779 Expr::EvalResult KnownVal; 10780 if (!getLangOpts().CPlusPlus || 10781 (!IExp->isValueDependent() && 10782 (!IExp->EvaluateAsInt(KnownVal, Context) || 10783 KnownVal.Val.getInt() != 0))) { 10784 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10785 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10786 Context, BO_Add, PExp, IExp); 10787 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10788 } 10789 } 10790 10791 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10792 return QualType(); 10793 10794 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10795 return QualType(); 10796 10797 // Check array bounds for pointer arithemtic 10798 CheckArrayAccess(PExp, IExp); 10799 10800 if (CompLHSTy) { 10801 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10802 if (LHSTy.isNull()) { 10803 LHSTy = LHS.get()->getType(); 10804 if (LHSTy->isPromotableIntegerType()) 10805 LHSTy = Context.getPromotedIntegerType(LHSTy); 10806 } 10807 *CompLHSTy = LHSTy; 10808 } 10809 10810 return PExp->getType(); 10811 } 10812 10813 // C99 6.5.6 10814 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10815 SourceLocation Loc, 10816 QualType* CompLHSTy) { 10817 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10818 10819 if (LHS.get()->getType()->isVectorType() || 10820 RHS.get()->getType()->isVectorType()) { 10821 QualType compType = CheckVectorOperands( 10822 LHS, RHS, Loc, CompLHSTy, 10823 /*AllowBothBool*/getLangOpts().AltiVec, 10824 /*AllowBoolConversions*/getLangOpts().ZVector); 10825 if (CompLHSTy) *CompLHSTy = compType; 10826 return compType; 10827 } 10828 10829 if (LHS.get()->getType()->isConstantMatrixType() || 10830 RHS.get()->getType()->isConstantMatrixType()) { 10831 QualType compType = 10832 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10833 if (CompLHSTy) 10834 *CompLHSTy = compType; 10835 return compType; 10836 } 10837 10838 QualType compType = UsualArithmeticConversions( 10839 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10840 if (LHS.isInvalid() || RHS.isInvalid()) 10841 return QualType(); 10842 10843 // Enforce type constraints: C99 6.5.6p3. 10844 10845 // Handle the common case first (both operands are arithmetic). 10846 if (!compType.isNull() && compType->isArithmeticType()) { 10847 if (CompLHSTy) *CompLHSTy = compType; 10848 return compType; 10849 } 10850 10851 // Either ptr - int or ptr - ptr. 10852 if (LHS.get()->getType()->isAnyPointerType()) { 10853 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10854 10855 // Diagnose bad cases where we step over interface counts. 10856 if (LHS.get()->getType()->isObjCObjectPointerType() && 10857 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10858 return QualType(); 10859 10860 // The result type of a pointer-int computation is the pointer type. 10861 if (RHS.get()->getType()->isIntegerType()) { 10862 // Subtracting from a null pointer should produce a warning. 10863 // The last argument to the diagnose call says this doesn't match the 10864 // GNU int-to-pointer idiom. 10865 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10866 Expr::NPC_ValueDependentIsNotNull)) { 10867 // In C++ adding zero to a null pointer is defined. 10868 Expr::EvalResult KnownVal; 10869 if (!getLangOpts().CPlusPlus || 10870 (!RHS.get()->isValueDependent() && 10871 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10872 KnownVal.Val.getInt() != 0))) { 10873 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10874 } 10875 } 10876 10877 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10878 return QualType(); 10879 10880 // Check array bounds for pointer arithemtic 10881 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10882 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10883 10884 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10885 return LHS.get()->getType(); 10886 } 10887 10888 // Handle pointer-pointer subtractions. 10889 if (const PointerType *RHSPTy 10890 = RHS.get()->getType()->getAs<PointerType>()) { 10891 QualType rpointee = RHSPTy->getPointeeType(); 10892 10893 if (getLangOpts().CPlusPlus) { 10894 // Pointee types must be the same: C++ [expr.add] 10895 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10896 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10897 } 10898 } else { 10899 // Pointee types must be compatible C99 6.5.6p3 10900 if (!Context.typesAreCompatible( 10901 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10902 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10903 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10904 return QualType(); 10905 } 10906 } 10907 10908 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10909 LHS.get(), RHS.get())) 10910 return QualType(); 10911 10912 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10913 Context, Expr::NPC_ValueDependentIsNotNull); 10914 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10915 Context, Expr::NPC_ValueDependentIsNotNull); 10916 10917 // Subtracting nullptr or from nullptr is suspect 10918 if (LHSIsNullPtr) 10919 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); 10920 if (RHSIsNullPtr) 10921 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); 10922 10923 // The pointee type may have zero size. As an extension, a structure or 10924 // union may have zero size or an array may have zero length. In this 10925 // case subtraction does not make sense. 10926 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10927 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10928 if (ElementSize.isZero()) { 10929 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10930 << rpointee.getUnqualifiedType() 10931 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10932 } 10933 } 10934 10935 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10936 return Context.getPointerDiffType(); 10937 } 10938 } 10939 10940 return InvalidOperands(Loc, LHS, RHS); 10941 } 10942 10943 static bool isScopedEnumerationType(QualType T) { 10944 if (const EnumType *ET = T->getAs<EnumType>()) 10945 return ET->getDecl()->isScoped(); 10946 return false; 10947 } 10948 10949 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10950 SourceLocation Loc, BinaryOperatorKind Opc, 10951 QualType LHSType) { 10952 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10953 // so skip remaining warnings as we don't want to modify values within Sema. 10954 if (S.getLangOpts().OpenCL) 10955 return; 10956 10957 // Check right/shifter operand 10958 Expr::EvalResult RHSResult; 10959 if (RHS.get()->isValueDependent() || 10960 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10961 return; 10962 llvm::APSInt Right = RHSResult.Val.getInt(); 10963 10964 if (Right.isNegative()) { 10965 S.DiagRuntimeBehavior(Loc, RHS.get(), 10966 S.PDiag(diag::warn_shift_negative) 10967 << RHS.get()->getSourceRange()); 10968 return; 10969 } 10970 10971 QualType LHSExprType = LHS.get()->getType(); 10972 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10973 if (LHSExprType->isExtIntType()) 10974 LeftSize = S.Context.getIntWidth(LHSExprType); 10975 else if (LHSExprType->isFixedPointType()) { 10976 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10977 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10978 } 10979 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10980 if (Right.uge(LeftBits)) { 10981 S.DiagRuntimeBehavior(Loc, RHS.get(), 10982 S.PDiag(diag::warn_shift_gt_typewidth) 10983 << RHS.get()->getSourceRange()); 10984 return; 10985 } 10986 10987 // FIXME: We probably need to handle fixed point types specially here. 10988 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10989 return; 10990 10991 // When left shifting an ICE which is signed, we can check for overflow which 10992 // according to C++ standards prior to C++2a has undefined behavior 10993 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10994 // more than the maximum value representable in the result type, so never 10995 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10996 // expression is still probably a bug.) 10997 Expr::EvalResult LHSResult; 10998 if (LHS.get()->isValueDependent() || 10999 LHSType->hasUnsignedIntegerRepresentation() || 11000 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 11001 return; 11002 llvm::APSInt Left = LHSResult.Val.getInt(); 11003 11004 // If LHS does not have a signed type and non-negative value 11005 // then, the behavior is undefined before C++2a. Warn about it. 11006 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 11007 !S.getLangOpts().CPlusPlus20) { 11008 S.DiagRuntimeBehavior(Loc, LHS.get(), 11009 S.PDiag(diag::warn_shift_lhs_negative) 11010 << LHS.get()->getSourceRange()); 11011 return; 11012 } 11013 11014 llvm::APInt ResultBits = 11015 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 11016 if (LeftBits.uge(ResultBits)) 11017 return; 11018 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 11019 Result = Result.shl(Right); 11020 11021 // Print the bit representation of the signed integer as an unsigned 11022 // hexadecimal number. 11023 SmallString<40> HexResult; 11024 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 11025 11026 // If we are only missing a sign bit, this is less likely to result in actual 11027 // bugs -- if the result is cast back to an unsigned type, it will have the 11028 // expected value. Thus we place this behind a different warning that can be 11029 // turned off separately if needed. 11030 if (LeftBits == ResultBits - 1) { 11031 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 11032 << HexResult << LHSType 11033 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11034 return; 11035 } 11036 11037 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 11038 << HexResult.str() << Result.getMinSignedBits() << LHSType 11039 << Left.getBitWidth() << LHS.get()->getSourceRange() 11040 << RHS.get()->getSourceRange(); 11041 } 11042 11043 /// Return the resulting type when a vector is shifted 11044 /// by a scalar or vector shift amount. 11045 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 11046 SourceLocation Loc, bool IsCompAssign) { 11047 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 11048 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 11049 !LHS.get()->getType()->isVectorType()) { 11050 S.Diag(Loc, diag::err_shift_rhs_only_vector) 11051 << RHS.get()->getType() << LHS.get()->getType() 11052 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11053 return QualType(); 11054 } 11055 11056 if (!IsCompAssign) { 11057 LHS = S.UsualUnaryConversions(LHS.get()); 11058 if (LHS.isInvalid()) return QualType(); 11059 } 11060 11061 RHS = S.UsualUnaryConversions(RHS.get()); 11062 if (RHS.isInvalid()) return QualType(); 11063 11064 QualType LHSType = LHS.get()->getType(); 11065 // Note that LHS might be a scalar because the routine calls not only in 11066 // OpenCL case. 11067 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 11068 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 11069 11070 // Note that RHS might not be a vector. 11071 QualType RHSType = RHS.get()->getType(); 11072 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 11073 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 11074 11075 // The operands need to be integers. 11076 if (!LHSEleType->isIntegerType()) { 11077 S.Diag(Loc, diag::err_typecheck_expect_int) 11078 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11079 return QualType(); 11080 } 11081 11082 if (!RHSEleType->isIntegerType()) { 11083 S.Diag(Loc, diag::err_typecheck_expect_int) 11084 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11085 return QualType(); 11086 } 11087 11088 if (!LHSVecTy) { 11089 assert(RHSVecTy); 11090 if (IsCompAssign) 11091 return RHSType; 11092 if (LHSEleType != RHSEleType) { 11093 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 11094 LHSEleType = RHSEleType; 11095 } 11096 QualType VecTy = 11097 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11098 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11099 LHSType = VecTy; 11100 } else if (RHSVecTy) { 11101 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11102 // are applied component-wise. So if RHS is a vector, then ensure 11103 // that the number of elements is the same as LHS... 11104 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11105 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11106 << LHS.get()->getType() << RHS.get()->getType() 11107 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11108 return QualType(); 11109 } 11110 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11111 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11112 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11113 if (LHSBT != RHSBT && 11114 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11115 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11116 << LHS.get()->getType() << RHS.get()->getType() 11117 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11118 } 11119 } 11120 } else { 11121 // ...else expand RHS to match the number of elements in LHS. 11122 QualType VecTy = 11123 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11124 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11125 } 11126 11127 return LHSType; 11128 } 11129 11130 // C99 6.5.7 11131 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11132 SourceLocation Loc, BinaryOperatorKind Opc, 11133 bool IsCompAssign) { 11134 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11135 11136 // Vector shifts promote their scalar inputs to vector type. 11137 if (LHS.get()->getType()->isVectorType() || 11138 RHS.get()->getType()->isVectorType()) { 11139 if (LangOpts.ZVector) { 11140 // The shift operators for the z vector extensions work basically 11141 // like general shifts, except that neither the LHS nor the RHS is 11142 // allowed to be a "vector bool". 11143 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11144 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11145 return InvalidOperands(Loc, LHS, RHS); 11146 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11147 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11148 return InvalidOperands(Loc, LHS, RHS); 11149 } 11150 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11151 } 11152 11153 // Shifts don't perform usual arithmetic conversions, they just do integer 11154 // promotions on each operand. C99 6.5.7p3 11155 11156 // For the LHS, do usual unary conversions, but then reset them away 11157 // if this is a compound assignment. 11158 ExprResult OldLHS = LHS; 11159 LHS = UsualUnaryConversions(LHS.get()); 11160 if (LHS.isInvalid()) 11161 return QualType(); 11162 QualType LHSType = LHS.get()->getType(); 11163 if (IsCompAssign) LHS = OldLHS; 11164 11165 // The RHS is simpler. 11166 RHS = UsualUnaryConversions(RHS.get()); 11167 if (RHS.isInvalid()) 11168 return QualType(); 11169 QualType RHSType = RHS.get()->getType(); 11170 11171 // C99 6.5.7p2: Each of the operands shall have integer type. 11172 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11173 if ((!LHSType->isFixedPointOrIntegerType() && 11174 !LHSType->hasIntegerRepresentation()) || 11175 !RHSType->hasIntegerRepresentation()) 11176 return InvalidOperands(Loc, LHS, RHS); 11177 11178 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11179 // hasIntegerRepresentation() above instead of this. 11180 if (isScopedEnumerationType(LHSType) || 11181 isScopedEnumerationType(RHSType)) { 11182 return InvalidOperands(Loc, LHS, RHS); 11183 } 11184 // Sanity-check shift operands 11185 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11186 11187 // "The type of the result is that of the promoted left operand." 11188 return LHSType; 11189 } 11190 11191 /// Diagnose bad pointer comparisons. 11192 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11193 ExprResult &LHS, ExprResult &RHS, 11194 bool IsError) { 11195 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11196 : diag::ext_typecheck_comparison_of_distinct_pointers) 11197 << LHS.get()->getType() << RHS.get()->getType() 11198 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11199 } 11200 11201 /// Returns false if the pointers are converted to a composite type, 11202 /// true otherwise. 11203 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11204 ExprResult &LHS, ExprResult &RHS) { 11205 // C++ [expr.rel]p2: 11206 // [...] Pointer conversions (4.10) and qualification 11207 // conversions (4.4) are performed on pointer operands (or on 11208 // a pointer operand and a null pointer constant) to bring 11209 // them to their composite pointer type. [...] 11210 // 11211 // C++ [expr.eq]p1 uses the same notion for (in)equality 11212 // comparisons of pointers. 11213 11214 QualType LHSType = LHS.get()->getType(); 11215 QualType RHSType = RHS.get()->getType(); 11216 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11217 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11218 11219 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11220 if (T.isNull()) { 11221 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11222 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11223 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11224 else 11225 S.InvalidOperands(Loc, LHS, RHS); 11226 return true; 11227 } 11228 11229 return false; 11230 } 11231 11232 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11233 ExprResult &LHS, 11234 ExprResult &RHS, 11235 bool IsError) { 11236 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11237 : diag::ext_typecheck_comparison_of_fptr_to_void) 11238 << LHS.get()->getType() << RHS.get()->getType() 11239 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11240 } 11241 11242 static bool isObjCObjectLiteral(ExprResult &E) { 11243 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11244 case Stmt::ObjCArrayLiteralClass: 11245 case Stmt::ObjCDictionaryLiteralClass: 11246 case Stmt::ObjCStringLiteralClass: 11247 case Stmt::ObjCBoxedExprClass: 11248 return true; 11249 default: 11250 // Note that ObjCBoolLiteral is NOT an object literal! 11251 return false; 11252 } 11253 } 11254 11255 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11256 const ObjCObjectPointerType *Type = 11257 LHS->getType()->getAs<ObjCObjectPointerType>(); 11258 11259 // If this is not actually an Objective-C object, bail out. 11260 if (!Type) 11261 return false; 11262 11263 // Get the LHS object's interface type. 11264 QualType InterfaceType = Type->getPointeeType(); 11265 11266 // If the RHS isn't an Objective-C object, bail out. 11267 if (!RHS->getType()->isObjCObjectPointerType()) 11268 return false; 11269 11270 // Try to find the -isEqual: method. 11271 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11272 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11273 InterfaceType, 11274 /*IsInstance=*/true); 11275 if (!Method) { 11276 if (Type->isObjCIdType()) { 11277 // For 'id', just check the global pool. 11278 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11279 /*receiverId=*/true); 11280 } else { 11281 // Check protocols. 11282 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11283 /*IsInstance=*/true); 11284 } 11285 } 11286 11287 if (!Method) 11288 return false; 11289 11290 QualType T = Method->parameters()[0]->getType(); 11291 if (!T->isObjCObjectPointerType()) 11292 return false; 11293 11294 QualType R = Method->getReturnType(); 11295 if (!R->isScalarType()) 11296 return false; 11297 11298 return true; 11299 } 11300 11301 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11302 FromE = FromE->IgnoreParenImpCasts(); 11303 switch (FromE->getStmtClass()) { 11304 default: 11305 break; 11306 case Stmt::ObjCStringLiteralClass: 11307 // "string literal" 11308 return LK_String; 11309 case Stmt::ObjCArrayLiteralClass: 11310 // "array literal" 11311 return LK_Array; 11312 case Stmt::ObjCDictionaryLiteralClass: 11313 // "dictionary literal" 11314 return LK_Dictionary; 11315 case Stmt::BlockExprClass: 11316 return LK_Block; 11317 case Stmt::ObjCBoxedExprClass: { 11318 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11319 switch (Inner->getStmtClass()) { 11320 case Stmt::IntegerLiteralClass: 11321 case Stmt::FloatingLiteralClass: 11322 case Stmt::CharacterLiteralClass: 11323 case Stmt::ObjCBoolLiteralExprClass: 11324 case Stmt::CXXBoolLiteralExprClass: 11325 // "numeric literal" 11326 return LK_Numeric; 11327 case Stmt::ImplicitCastExprClass: { 11328 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11329 // Boolean literals can be represented by implicit casts. 11330 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11331 return LK_Numeric; 11332 break; 11333 } 11334 default: 11335 break; 11336 } 11337 return LK_Boxed; 11338 } 11339 } 11340 return LK_None; 11341 } 11342 11343 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11344 ExprResult &LHS, ExprResult &RHS, 11345 BinaryOperator::Opcode Opc){ 11346 Expr *Literal; 11347 Expr *Other; 11348 if (isObjCObjectLiteral(LHS)) { 11349 Literal = LHS.get(); 11350 Other = RHS.get(); 11351 } else { 11352 Literal = RHS.get(); 11353 Other = LHS.get(); 11354 } 11355 11356 // Don't warn on comparisons against nil. 11357 Other = Other->IgnoreParenCasts(); 11358 if (Other->isNullPointerConstant(S.getASTContext(), 11359 Expr::NPC_ValueDependentIsNotNull)) 11360 return; 11361 11362 // This should be kept in sync with warn_objc_literal_comparison. 11363 // LK_String should always be after the other literals, since it has its own 11364 // warning flag. 11365 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11366 assert(LiteralKind != Sema::LK_Block); 11367 if (LiteralKind == Sema::LK_None) { 11368 llvm_unreachable("Unknown Objective-C object literal kind"); 11369 } 11370 11371 if (LiteralKind == Sema::LK_String) 11372 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11373 << Literal->getSourceRange(); 11374 else 11375 S.Diag(Loc, diag::warn_objc_literal_comparison) 11376 << LiteralKind << Literal->getSourceRange(); 11377 11378 if (BinaryOperator::isEqualityOp(Opc) && 11379 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11380 SourceLocation Start = LHS.get()->getBeginLoc(); 11381 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11382 CharSourceRange OpRange = 11383 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11384 11385 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11386 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11387 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11388 << FixItHint::CreateInsertion(End, "]"); 11389 } 11390 } 11391 11392 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11393 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11394 ExprResult &RHS, SourceLocation Loc, 11395 BinaryOperatorKind Opc) { 11396 // Check that left hand side is !something. 11397 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11398 if (!UO || UO->getOpcode() != UO_LNot) return; 11399 11400 // Only check if the right hand side is non-bool arithmetic type. 11401 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11402 11403 // Make sure that the something in !something is not bool. 11404 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11405 if (SubExpr->isKnownToHaveBooleanValue()) return; 11406 11407 // Emit warning. 11408 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11409 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11410 << Loc << IsBitwiseOp; 11411 11412 // First note suggest !(x < y) 11413 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11414 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11415 FirstClose = S.getLocForEndOfToken(FirstClose); 11416 if (FirstClose.isInvalid()) 11417 FirstOpen = SourceLocation(); 11418 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11419 << IsBitwiseOp 11420 << FixItHint::CreateInsertion(FirstOpen, "(") 11421 << FixItHint::CreateInsertion(FirstClose, ")"); 11422 11423 // Second note suggests (!x) < y 11424 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11425 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11426 SecondClose = S.getLocForEndOfToken(SecondClose); 11427 if (SecondClose.isInvalid()) 11428 SecondOpen = SourceLocation(); 11429 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11430 << FixItHint::CreateInsertion(SecondOpen, "(") 11431 << FixItHint::CreateInsertion(SecondClose, ")"); 11432 } 11433 11434 // Returns true if E refers to a non-weak array. 11435 static bool checkForArray(const Expr *E) { 11436 const ValueDecl *D = nullptr; 11437 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11438 D = DR->getDecl(); 11439 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11440 if (Mem->isImplicitAccess()) 11441 D = Mem->getMemberDecl(); 11442 } 11443 if (!D) 11444 return false; 11445 return D->getType()->isArrayType() && !D->isWeak(); 11446 } 11447 11448 /// Diagnose some forms of syntactically-obvious tautological comparison. 11449 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11450 Expr *LHS, Expr *RHS, 11451 BinaryOperatorKind Opc) { 11452 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11453 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11454 11455 QualType LHSType = LHS->getType(); 11456 QualType RHSType = RHS->getType(); 11457 if (LHSType->hasFloatingRepresentation() || 11458 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11459 S.inTemplateInstantiation()) 11460 return; 11461 11462 // Comparisons between two array types are ill-formed for operator<=>, so 11463 // we shouldn't emit any additional warnings about it. 11464 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11465 return; 11466 11467 // For non-floating point types, check for self-comparisons of the form 11468 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11469 // often indicate logic errors in the program. 11470 // 11471 // NOTE: Don't warn about comparison expressions resulting from macro 11472 // expansion. Also don't warn about comparisons which are only self 11473 // comparisons within a template instantiation. The warnings should catch 11474 // obvious cases in the definition of the template anyways. The idea is to 11475 // warn when the typed comparison operator will always evaluate to the same 11476 // result. 11477 11478 // Used for indexing into %select in warn_comparison_always 11479 enum { 11480 AlwaysConstant, 11481 AlwaysTrue, 11482 AlwaysFalse, 11483 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11484 }; 11485 11486 // C++2a [depr.array.comp]: 11487 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11488 // operands of array type are deprecated. 11489 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11490 RHSStripped->getType()->isArrayType()) { 11491 S.Diag(Loc, diag::warn_depr_array_comparison) 11492 << LHS->getSourceRange() << RHS->getSourceRange() 11493 << LHSStripped->getType() << RHSStripped->getType(); 11494 // Carry on to produce the tautological comparison warning, if this 11495 // expression is potentially-evaluated, we can resolve the array to a 11496 // non-weak declaration, and so on. 11497 } 11498 11499 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11500 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11501 unsigned Result; 11502 switch (Opc) { 11503 case BO_EQ: 11504 case BO_LE: 11505 case BO_GE: 11506 Result = AlwaysTrue; 11507 break; 11508 case BO_NE: 11509 case BO_LT: 11510 case BO_GT: 11511 Result = AlwaysFalse; 11512 break; 11513 case BO_Cmp: 11514 Result = AlwaysEqual; 11515 break; 11516 default: 11517 Result = AlwaysConstant; 11518 break; 11519 } 11520 S.DiagRuntimeBehavior(Loc, nullptr, 11521 S.PDiag(diag::warn_comparison_always) 11522 << 0 /*self-comparison*/ 11523 << Result); 11524 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11525 // What is it always going to evaluate to? 11526 unsigned Result; 11527 switch (Opc) { 11528 case BO_EQ: // e.g. array1 == array2 11529 Result = AlwaysFalse; 11530 break; 11531 case BO_NE: // e.g. array1 != array2 11532 Result = AlwaysTrue; 11533 break; 11534 default: // e.g. array1 <= array2 11535 // The best we can say is 'a constant' 11536 Result = AlwaysConstant; 11537 break; 11538 } 11539 S.DiagRuntimeBehavior(Loc, nullptr, 11540 S.PDiag(diag::warn_comparison_always) 11541 << 1 /*array comparison*/ 11542 << Result); 11543 } 11544 } 11545 11546 if (isa<CastExpr>(LHSStripped)) 11547 LHSStripped = LHSStripped->IgnoreParenCasts(); 11548 if (isa<CastExpr>(RHSStripped)) 11549 RHSStripped = RHSStripped->IgnoreParenCasts(); 11550 11551 // Warn about comparisons against a string constant (unless the other 11552 // operand is null); the user probably wants string comparison function. 11553 Expr *LiteralString = nullptr; 11554 Expr *LiteralStringStripped = nullptr; 11555 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11556 !RHSStripped->isNullPointerConstant(S.Context, 11557 Expr::NPC_ValueDependentIsNull)) { 11558 LiteralString = LHS; 11559 LiteralStringStripped = LHSStripped; 11560 } else if ((isa<StringLiteral>(RHSStripped) || 11561 isa<ObjCEncodeExpr>(RHSStripped)) && 11562 !LHSStripped->isNullPointerConstant(S.Context, 11563 Expr::NPC_ValueDependentIsNull)) { 11564 LiteralString = RHS; 11565 LiteralStringStripped = RHSStripped; 11566 } 11567 11568 if (LiteralString) { 11569 S.DiagRuntimeBehavior(Loc, nullptr, 11570 S.PDiag(diag::warn_stringcompare) 11571 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11572 << LiteralString->getSourceRange()); 11573 } 11574 } 11575 11576 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11577 switch (CK) { 11578 default: { 11579 #ifndef NDEBUG 11580 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11581 << "\n"; 11582 #endif 11583 llvm_unreachable("unhandled cast kind"); 11584 } 11585 case CK_UserDefinedConversion: 11586 return ICK_Identity; 11587 case CK_LValueToRValue: 11588 return ICK_Lvalue_To_Rvalue; 11589 case CK_ArrayToPointerDecay: 11590 return ICK_Array_To_Pointer; 11591 case CK_FunctionToPointerDecay: 11592 return ICK_Function_To_Pointer; 11593 case CK_IntegralCast: 11594 return ICK_Integral_Conversion; 11595 case CK_FloatingCast: 11596 return ICK_Floating_Conversion; 11597 case CK_IntegralToFloating: 11598 case CK_FloatingToIntegral: 11599 return ICK_Floating_Integral; 11600 case CK_IntegralComplexCast: 11601 case CK_FloatingComplexCast: 11602 case CK_FloatingComplexToIntegralComplex: 11603 case CK_IntegralComplexToFloatingComplex: 11604 return ICK_Complex_Conversion; 11605 case CK_FloatingComplexToReal: 11606 case CK_FloatingRealToComplex: 11607 case CK_IntegralComplexToReal: 11608 case CK_IntegralRealToComplex: 11609 return ICK_Complex_Real; 11610 } 11611 } 11612 11613 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11614 QualType FromType, 11615 SourceLocation Loc) { 11616 // Check for a narrowing implicit conversion. 11617 StandardConversionSequence SCS; 11618 SCS.setAsIdentityConversion(); 11619 SCS.setToType(0, FromType); 11620 SCS.setToType(1, ToType); 11621 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11622 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11623 11624 APValue PreNarrowingValue; 11625 QualType PreNarrowingType; 11626 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11627 PreNarrowingType, 11628 /*IgnoreFloatToIntegralConversion*/ true)) { 11629 case NK_Dependent_Narrowing: 11630 // Implicit conversion to a narrower type, but the expression is 11631 // value-dependent so we can't tell whether it's actually narrowing. 11632 case NK_Not_Narrowing: 11633 return false; 11634 11635 case NK_Constant_Narrowing: 11636 // Implicit conversion to a narrower type, and the value is not a constant 11637 // expression. 11638 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11639 << /*Constant*/ 1 11640 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11641 return true; 11642 11643 case NK_Variable_Narrowing: 11644 // Implicit conversion to a narrower type, and the value is not a constant 11645 // expression. 11646 case NK_Type_Narrowing: 11647 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11648 << /*Constant*/ 0 << FromType << ToType; 11649 // TODO: It's not a constant expression, but what if the user intended it 11650 // to be? Can we produce notes to help them figure out why it isn't? 11651 return true; 11652 } 11653 llvm_unreachable("unhandled case in switch"); 11654 } 11655 11656 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11657 ExprResult &LHS, 11658 ExprResult &RHS, 11659 SourceLocation Loc) { 11660 QualType LHSType = LHS.get()->getType(); 11661 QualType RHSType = RHS.get()->getType(); 11662 // Dig out the original argument type and expression before implicit casts 11663 // were applied. These are the types/expressions we need to check the 11664 // [expr.spaceship] requirements against. 11665 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11666 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11667 QualType LHSStrippedType = LHSStripped.get()->getType(); 11668 QualType RHSStrippedType = RHSStripped.get()->getType(); 11669 11670 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11671 // other is not, the program is ill-formed. 11672 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11673 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11674 return QualType(); 11675 } 11676 11677 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11678 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11679 RHSStrippedType->isEnumeralType(); 11680 if (NumEnumArgs == 1) { 11681 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11682 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11683 if (OtherTy->hasFloatingRepresentation()) { 11684 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11685 return QualType(); 11686 } 11687 } 11688 if (NumEnumArgs == 2) { 11689 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11690 // type E, the operator yields the result of converting the operands 11691 // to the underlying type of E and applying <=> to the converted operands. 11692 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11693 S.InvalidOperands(Loc, LHS, RHS); 11694 return QualType(); 11695 } 11696 QualType IntType = 11697 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11698 assert(IntType->isArithmeticType()); 11699 11700 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11701 // promote the boolean type, and all other promotable integer types, to 11702 // avoid this. 11703 if (IntType->isPromotableIntegerType()) 11704 IntType = S.Context.getPromotedIntegerType(IntType); 11705 11706 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11707 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11708 LHSType = RHSType = IntType; 11709 } 11710 11711 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11712 // usual arithmetic conversions are applied to the operands. 11713 QualType Type = 11714 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11715 if (LHS.isInvalid() || RHS.isInvalid()) 11716 return QualType(); 11717 if (Type.isNull()) 11718 return S.InvalidOperands(Loc, LHS, RHS); 11719 11720 Optional<ComparisonCategoryType> CCT = 11721 getComparisonCategoryForBuiltinCmp(Type); 11722 if (!CCT) 11723 return S.InvalidOperands(Loc, LHS, RHS); 11724 11725 bool HasNarrowing = checkThreeWayNarrowingConversion( 11726 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11727 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11728 RHS.get()->getBeginLoc()); 11729 if (HasNarrowing) 11730 return QualType(); 11731 11732 assert(!Type.isNull() && "composite type for <=> has not been set"); 11733 11734 return S.CheckComparisonCategoryType( 11735 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11736 } 11737 11738 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11739 ExprResult &RHS, 11740 SourceLocation Loc, 11741 BinaryOperatorKind Opc) { 11742 if (Opc == BO_Cmp) 11743 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11744 11745 // C99 6.5.8p3 / C99 6.5.9p4 11746 QualType Type = 11747 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11748 if (LHS.isInvalid() || RHS.isInvalid()) 11749 return QualType(); 11750 if (Type.isNull()) 11751 return S.InvalidOperands(Loc, LHS, RHS); 11752 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11753 11754 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11755 return S.InvalidOperands(Loc, LHS, RHS); 11756 11757 // Check for comparisons of floating point operands using != and ==. 11758 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11759 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11760 11761 // The result of comparisons is 'bool' in C++, 'int' in C. 11762 return S.Context.getLogicalOperationType(); 11763 } 11764 11765 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11766 if (!NullE.get()->getType()->isAnyPointerType()) 11767 return; 11768 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11769 if (!E.get()->getType()->isAnyPointerType() && 11770 E.get()->isNullPointerConstant(Context, 11771 Expr::NPC_ValueDependentIsNotNull) == 11772 Expr::NPCK_ZeroExpression) { 11773 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11774 if (CL->getValue() == 0) 11775 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11776 << NullValue 11777 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11778 NullValue ? "NULL" : "(void *)0"); 11779 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11780 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11781 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11782 if (T == Context.CharTy) 11783 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11784 << NullValue 11785 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11786 NullValue ? "NULL" : "(void *)0"); 11787 } 11788 } 11789 } 11790 11791 // C99 6.5.8, C++ [expr.rel] 11792 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11793 SourceLocation Loc, 11794 BinaryOperatorKind Opc) { 11795 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11796 bool IsThreeWay = Opc == BO_Cmp; 11797 bool IsOrdered = IsRelational || IsThreeWay; 11798 auto IsAnyPointerType = [](ExprResult E) { 11799 QualType Ty = E.get()->getType(); 11800 return Ty->isPointerType() || Ty->isMemberPointerType(); 11801 }; 11802 11803 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11804 // type, array-to-pointer, ..., conversions are performed on both operands to 11805 // bring them to their composite type. 11806 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11807 // any type-related checks. 11808 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11809 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11810 if (LHS.isInvalid()) 11811 return QualType(); 11812 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11813 if (RHS.isInvalid()) 11814 return QualType(); 11815 } else { 11816 LHS = DefaultLvalueConversion(LHS.get()); 11817 if (LHS.isInvalid()) 11818 return QualType(); 11819 RHS = DefaultLvalueConversion(RHS.get()); 11820 if (RHS.isInvalid()) 11821 return QualType(); 11822 } 11823 11824 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11825 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11826 CheckPtrComparisonWithNullChar(LHS, RHS); 11827 CheckPtrComparisonWithNullChar(RHS, LHS); 11828 } 11829 11830 // Handle vector comparisons separately. 11831 if (LHS.get()->getType()->isVectorType() || 11832 RHS.get()->getType()->isVectorType()) 11833 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11834 11835 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11836 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11837 11838 QualType LHSType = LHS.get()->getType(); 11839 QualType RHSType = RHS.get()->getType(); 11840 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11841 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11842 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11843 11844 const Expr::NullPointerConstantKind LHSNullKind = 11845 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11846 const Expr::NullPointerConstantKind RHSNullKind = 11847 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11848 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11849 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11850 11851 auto computeResultTy = [&]() { 11852 if (Opc != BO_Cmp) 11853 return Context.getLogicalOperationType(); 11854 assert(getLangOpts().CPlusPlus); 11855 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11856 11857 QualType CompositeTy = LHS.get()->getType(); 11858 assert(!CompositeTy->isReferenceType()); 11859 11860 Optional<ComparisonCategoryType> CCT = 11861 getComparisonCategoryForBuiltinCmp(CompositeTy); 11862 if (!CCT) 11863 return InvalidOperands(Loc, LHS, RHS); 11864 11865 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11866 // P0946R0: Comparisons between a null pointer constant and an object 11867 // pointer result in std::strong_equality, which is ill-formed under 11868 // P1959R0. 11869 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11870 << (LHSIsNull ? LHS.get()->getSourceRange() 11871 : RHS.get()->getSourceRange()); 11872 return QualType(); 11873 } 11874 11875 return CheckComparisonCategoryType( 11876 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11877 }; 11878 11879 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11880 bool IsEquality = Opc == BO_EQ; 11881 if (RHSIsNull) 11882 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11883 RHS.get()->getSourceRange()); 11884 else 11885 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11886 LHS.get()->getSourceRange()); 11887 } 11888 11889 if (IsOrdered && LHSType->isFunctionPointerType() && 11890 RHSType->isFunctionPointerType()) { 11891 // Valid unless a relational comparison of function pointers 11892 bool IsError = Opc == BO_Cmp; 11893 auto DiagID = 11894 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 11895 : getLangOpts().CPlusPlus 11896 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 11897 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 11898 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 11899 << RHS.get()->getSourceRange(); 11900 if (IsError) 11901 return QualType(); 11902 } 11903 11904 if ((LHSType->isIntegerType() && !LHSIsNull) || 11905 (RHSType->isIntegerType() && !RHSIsNull)) { 11906 // Skip normal pointer conversion checks in this case; we have better 11907 // diagnostics for this below. 11908 } else if (getLangOpts().CPlusPlus) { 11909 // Equality comparison of a function pointer to a void pointer is invalid, 11910 // but we allow it as an extension. 11911 // FIXME: If we really want to allow this, should it be part of composite 11912 // pointer type computation so it works in conditionals too? 11913 if (!IsOrdered && 11914 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11915 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11916 // This is a gcc extension compatibility comparison. 11917 // In a SFINAE context, we treat this as a hard error to maintain 11918 // conformance with the C++ standard. 11919 diagnoseFunctionPointerToVoidComparison( 11920 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11921 11922 if (isSFINAEContext()) 11923 return QualType(); 11924 11925 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11926 return computeResultTy(); 11927 } 11928 11929 // C++ [expr.eq]p2: 11930 // If at least one operand is a pointer [...] bring them to their 11931 // composite pointer type. 11932 // C++ [expr.spaceship]p6 11933 // If at least one of the operands is of pointer type, [...] bring them 11934 // to their composite pointer type. 11935 // C++ [expr.rel]p2: 11936 // If both operands are pointers, [...] bring them to their composite 11937 // pointer type. 11938 // For <=>, the only valid non-pointer types are arrays and functions, and 11939 // we already decayed those, so this is really the same as the relational 11940 // comparison rule. 11941 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11942 (IsOrdered ? 2 : 1) && 11943 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11944 RHSType->isObjCObjectPointerType()))) { 11945 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11946 return QualType(); 11947 return computeResultTy(); 11948 } 11949 } else if (LHSType->isPointerType() && 11950 RHSType->isPointerType()) { // C99 6.5.8p2 11951 // All of the following pointer-related warnings are GCC extensions, except 11952 // when handling null pointer constants. 11953 QualType LCanPointeeTy = 11954 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11955 QualType RCanPointeeTy = 11956 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11957 11958 // C99 6.5.9p2 and C99 6.5.8p2 11959 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11960 RCanPointeeTy.getUnqualifiedType())) { 11961 if (IsRelational) { 11962 // Pointers both need to point to complete or incomplete types 11963 if ((LCanPointeeTy->isIncompleteType() != 11964 RCanPointeeTy->isIncompleteType()) && 11965 !getLangOpts().C11) { 11966 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11967 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11968 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11969 << RCanPointeeTy->isIncompleteType(); 11970 } 11971 } 11972 } else if (!IsRelational && 11973 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11974 // Valid unless comparison between non-null pointer and function pointer 11975 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11976 && !LHSIsNull && !RHSIsNull) 11977 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11978 /*isError*/false); 11979 } else { 11980 // Invalid 11981 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11982 } 11983 if (LCanPointeeTy != RCanPointeeTy) { 11984 // Treat NULL constant as a special case in OpenCL. 11985 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11986 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11987 Diag(Loc, 11988 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11989 << LHSType << RHSType << 0 /* comparison */ 11990 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11991 } 11992 } 11993 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11994 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11995 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11996 : CK_BitCast; 11997 if (LHSIsNull && !RHSIsNull) 11998 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11999 else 12000 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 12001 } 12002 return computeResultTy(); 12003 } 12004 12005 if (getLangOpts().CPlusPlus) { 12006 // C++ [expr.eq]p4: 12007 // Two operands of type std::nullptr_t or one operand of type 12008 // std::nullptr_t and the other a null pointer constant compare equal. 12009 if (!IsOrdered && LHSIsNull && RHSIsNull) { 12010 if (LHSType->isNullPtrType()) { 12011 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12012 return computeResultTy(); 12013 } 12014 if (RHSType->isNullPtrType()) { 12015 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12016 return computeResultTy(); 12017 } 12018 } 12019 12020 // Comparison of Objective-C pointers and block pointers against nullptr_t. 12021 // These aren't covered by the composite pointer type rules. 12022 if (!IsOrdered && RHSType->isNullPtrType() && 12023 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 12024 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12025 return computeResultTy(); 12026 } 12027 if (!IsOrdered && LHSType->isNullPtrType() && 12028 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 12029 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12030 return computeResultTy(); 12031 } 12032 12033 if (IsRelational && 12034 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 12035 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 12036 // HACK: Relational comparison of nullptr_t against a pointer type is 12037 // invalid per DR583, but we allow it within std::less<> and friends, 12038 // since otherwise common uses of it break. 12039 // FIXME: Consider removing this hack once LWG fixes std::less<> and 12040 // friends to have std::nullptr_t overload candidates. 12041 DeclContext *DC = CurContext; 12042 if (isa<FunctionDecl>(DC)) 12043 DC = DC->getParent(); 12044 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 12045 if (CTSD->isInStdNamespace() && 12046 llvm::StringSwitch<bool>(CTSD->getName()) 12047 .Cases("less", "less_equal", "greater", "greater_equal", true) 12048 .Default(false)) { 12049 if (RHSType->isNullPtrType()) 12050 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12051 else 12052 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12053 return computeResultTy(); 12054 } 12055 } 12056 } 12057 12058 // C++ [expr.eq]p2: 12059 // If at least one operand is a pointer to member, [...] bring them to 12060 // their composite pointer type. 12061 if (!IsOrdered && 12062 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 12063 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12064 return QualType(); 12065 else 12066 return computeResultTy(); 12067 } 12068 } 12069 12070 // Handle block pointer types. 12071 if (!IsOrdered && LHSType->isBlockPointerType() && 12072 RHSType->isBlockPointerType()) { 12073 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 12074 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 12075 12076 if (!LHSIsNull && !RHSIsNull && 12077 !Context.typesAreCompatible(lpointee, rpointee)) { 12078 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12079 << LHSType << RHSType << LHS.get()->getSourceRange() 12080 << RHS.get()->getSourceRange(); 12081 } 12082 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12083 return computeResultTy(); 12084 } 12085 12086 // Allow block pointers to be compared with null pointer constants. 12087 if (!IsOrdered 12088 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 12089 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 12090 if (!LHSIsNull && !RHSIsNull) { 12091 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 12092 ->getPointeeType()->isVoidType()) 12093 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12094 ->getPointeeType()->isVoidType()))) 12095 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12096 << LHSType << RHSType << LHS.get()->getSourceRange() 12097 << RHS.get()->getSourceRange(); 12098 } 12099 if (LHSIsNull && !RHSIsNull) 12100 LHS = ImpCastExprToType(LHS.get(), RHSType, 12101 RHSType->isPointerType() ? CK_BitCast 12102 : CK_AnyPointerToBlockPointerCast); 12103 else 12104 RHS = ImpCastExprToType(RHS.get(), LHSType, 12105 LHSType->isPointerType() ? CK_BitCast 12106 : CK_AnyPointerToBlockPointerCast); 12107 return computeResultTy(); 12108 } 12109 12110 if (LHSType->isObjCObjectPointerType() || 12111 RHSType->isObjCObjectPointerType()) { 12112 const PointerType *LPT = LHSType->getAs<PointerType>(); 12113 const PointerType *RPT = RHSType->getAs<PointerType>(); 12114 if (LPT || RPT) { 12115 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12116 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12117 12118 if (!LPtrToVoid && !RPtrToVoid && 12119 !Context.typesAreCompatible(LHSType, RHSType)) { 12120 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12121 /*isError*/false); 12122 } 12123 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12124 // the RHS, but we have test coverage for this behavior. 12125 // FIXME: Consider using convertPointersToCompositeType in C++. 12126 if (LHSIsNull && !RHSIsNull) { 12127 Expr *E = LHS.get(); 12128 if (getLangOpts().ObjCAutoRefCount) 12129 CheckObjCConversion(SourceRange(), RHSType, E, 12130 CCK_ImplicitConversion); 12131 LHS = ImpCastExprToType(E, RHSType, 12132 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12133 } 12134 else { 12135 Expr *E = RHS.get(); 12136 if (getLangOpts().ObjCAutoRefCount) 12137 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12138 /*Diagnose=*/true, 12139 /*DiagnoseCFAudited=*/false, Opc); 12140 RHS = ImpCastExprToType(E, LHSType, 12141 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12142 } 12143 return computeResultTy(); 12144 } 12145 if (LHSType->isObjCObjectPointerType() && 12146 RHSType->isObjCObjectPointerType()) { 12147 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12148 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12149 /*isError*/false); 12150 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12151 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12152 12153 if (LHSIsNull && !RHSIsNull) 12154 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12155 else 12156 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12157 return computeResultTy(); 12158 } 12159 12160 if (!IsOrdered && LHSType->isBlockPointerType() && 12161 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12162 LHS = ImpCastExprToType(LHS.get(), RHSType, 12163 CK_BlockPointerToObjCPointerCast); 12164 return computeResultTy(); 12165 } else if (!IsOrdered && 12166 LHSType->isBlockCompatibleObjCPointerType(Context) && 12167 RHSType->isBlockPointerType()) { 12168 RHS = ImpCastExprToType(RHS.get(), LHSType, 12169 CK_BlockPointerToObjCPointerCast); 12170 return computeResultTy(); 12171 } 12172 } 12173 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12174 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12175 unsigned DiagID = 0; 12176 bool isError = false; 12177 if (LangOpts.DebuggerSupport) { 12178 // Under a debugger, allow the comparison of pointers to integers, 12179 // since users tend to want to compare addresses. 12180 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12181 (RHSIsNull && RHSType->isIntegerType())) { 12182 if (IsOrdered) { 12183 isError = getLangOpts().CPlusPlus; 12184 DiagID = 12185 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12186 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12187 } 12188 } else if (getLangOpts().CPlusPlus) { 12189 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12190 isError = true; 12191 } else if (IsOrdered) 12192 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12193 else 12194 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12195 12196 if (DiagID) { 12197 Diag(Loc, DiagID) 12198 << LHSType << RHSType << LHS.get()->getSourceRange() 12199 << RHS.get()->getSourceRange(); 12200 if (isError) 12201 return QualType(); 12202 } 12203 12204 if (LHSType->isIntegerType()) 12205 LHS = ImpCastExprToType(LHS.get(), RHSType, 12206 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12207 else 12208 RHS = ImpCastExprToType(RHS.get(), LHSType, 12209 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12210 return computeResultTy(); 12211 } 12212 12213 // Handle block pointers. 12214 if (!IsOrdered && RHSIsNull 12215 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12216 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12217 return computeResultTy(); 12218 } 12219 if (!IsOrdered && LHSIsNull 12220 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12221 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12222 return computeResultTy(); 12223 } 12224 12225 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 12226 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12227 return computeResultTy(); 12228 } 12229 12230 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12231 return computeResultTy(); 12232 } 12233 12234 if (LHSIsNull && RHSType->isQueueT()) { 12235 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12236 return computeResultTy(); 12237 } 12238 12239 if (LHSType->isQueueT() && RHSIsNull) { 12240 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12241 return computeResultTy(); 12242 } 12243 } 12244 12245 return InvalidOperands(Loc, LHS, RHS); 12246 } 12247 12248 // Return a signed ext_vector_type that is of identical size and number of 12249 // elements. For floating point vectors, return an integer type of identical 12250 // size and number of elements. In the non ext_vector_type case, search from 12251 // the largest type to the smallest type to avoid cases where long long == long, 12252 // where long gets picked over long long. 12253 QualType Sema::GetSignedVectorType(QualType V) { 12254 const VectorType *VTy = V->castAs<VectorType>(); 12255 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12256 12257 if (isa<ExtVectorType>(VTy)) { 12258 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12259 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12260 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12261 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12262 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12263 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12264 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12265 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12266 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12267 "Unhandled vector element size in vector compare"); 12268 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12269 } 12270 12271 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12272 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12273 VectorType::GenericVector); 12274 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12275 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12276 VectorType::GenericVector); 12277 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12278 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12279 VectorType::GenericVector); 12280 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12281 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12282 VectorType::GenericVector); 12283 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12284 "Unhandled vector element size in vector compare"); 12285 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12286 VectorType::GenericVector); 12287 } 12288 12289 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12290 /// operates on extended vector types. Instead of producing an IntTy result, 12291 /// like a scalar comparison, a vector comparison produces a vector of integer 12292 /// types. 12293 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12294 SourceLocation Loc, 12295 BinaryOperatorKind Opc) { 12296 if (Opc == BO_Cmp) { 12297 Diag(Loc, diag::err_three_way_vector_comparison); 12298 return QualType(); 12299 } 12300 12301 // Check to make sure we're operating on vectors of the same type and width, 12302 // Allowing one side to be a scalar of element type. 12303 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12304 /*AllowBothBool*/true, 12305 /*AllowBoolConversions*/getLangOpts().ZVector); 12306 if (vType.isNull()) 12307 return vType; 12308 12309 QualType LHSType = LHS.get()->getType(); 12310 12311 // Determine the return type of a vector compare. By default clang will return 12312 // a scalar for all vector compares except vector bool and vector pixel. 12313 // With the gcc compiler we will always return a vector type and with the xl 12314 // compiler we will always return a scalar type. This switch allows choosing 12315 // which behavior is prefered. 12316 if (getLangOpts().AltiVec) { 12317 switch (getLangOpts().getAltivecSrcCompat()) { 12318 case LangOptions::AltivecSrcCompatKind::Mixed: 12319 // If AltiVec, the comparison results in a numeric type, i.e. 12320 // bool for C++, int for C 12321 if (vType->castAs<VectorType>()->getVectorKind() == 12322 VectorType::AltiVecVector) 12323 return Context.getLogicalOperationType(); 12324 else 12325 Diag(Loc, diag::warn_deprecated_altivec_src_compat); 12326 break; 12327 case LangOptions::AltivecSrcCompatKind::GCC: 12328 // For GCC we always return the vector type. 12329 break; 12330 case LangOptions::AltivecSrcCompatKind::XL: 12331 return Context.getLogicalOperationType(); 12332 break; 12333 } 12334 } 12335 12336 // For non-floating point types, check for self-comparisons of the form 12337 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12338 // often indicate logic errors in the program. 12339 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12340 12341 // Check for comparisons of floating point operands using != and ==. 12342 if (BinaryOperator::isEqualityOp(Opc) && 12343 LHSType->hasFloatingRepresentation()) { 12344 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12345 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12346 } 12347 12348 // Return a signed type for the vector. 12349 return GetSignedVectorType(vType); 12350 } 12351 12352 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12353 const ExprResult &XorRHS, 12354 const SourceLocation Loc) { 12355 // Do not diagnose macros. 12356 if (Loc.isMacroID()) 12357 return; 12358 12359 // Do not diagnose if both LHS and RHS are macros. 12360 if (XorLHS.get()->getExprLoc().isMacroID() && 12361 XorRHS.get()->getExprLoc().isMacroID()) 12362 return; 12363 12364 bool Negative = false; 12365 bool ExplicitPlus = false; 12366 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12367 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12368 12369 if (!LHSInt) 12370 return; 12371 if (!RHSInt) { 12372 // Check negative literals. 12373 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12374 UnaryOperatorKind Opc = UO->getOpcode(); 12375 if (Opc != UO_Minus && Opc != UO_Plus) 12376 return; 12377 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12378 if (!RHSInt) 12379 return; 12380 Negative = (Opc == UO_Minus); 12381 ExplicitPlus = !Negative; 12382 } else { 12383 return; 12384 } 12385 } 12386 12387 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12388 llvm::APInt RightSideValue = RHSInt->getValue(); 12389 if (LeftSideValue != 2 && LeftSideValue != 10) 12390 return; 12391 12392 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12393 return; 12394 12395 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12396 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12397 llvm::StringRef ExprStr = 12398 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12399 12400 CharSourceRange XorRange = 12401 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12402 llvm::StringRef XorStr = 12403 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12404 // Do not diagnose if xor keyword/macro is used. 12405 if (XorStr == "xor") 12406 return; 12407 12408 std::string LHSStr = std::string(Lexer::getSourceText( 12409 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12410 S.getSourceManager(), S.getLangOpts())); 12411 std::string RHSStr = std::string(Lexer::getSourceText( 12412 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12413 S.getSourceManager(), S.getLangOpts())); 12414 12415 if (Negative) { 12416 RightSideValue = -RightSideValue; 12417 RHSStr = "-" + RHSStr; 12418 } else if (ExplicitPlus) { 12419 RHSStr = "+" + RHSStr; 12420 } 12421 12422 StringRef LHSStrRef = LHSStr; 12423 StringRef RHSStrRef = RHSStr; 12424 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12425 // literals. 12426 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12427 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12428 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12429 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12430 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12431 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12432 LHSStrRef.find('\'') != StringRef::npos || 12433 RHSStrRef.find('\'') != StringRef::npos) 12434 return; 12435 12436 bool SuggestXor = 12437 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12438 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12439 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12440 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12441 std::string SuggestedExpr = "1 << " + RHSStr; 12442 bool Overflow = false; 12443 llvm::APInt One = (LeftSideValue - 1); 12444 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12445 if (Overflow) { 12446 if (RightSideIntValue < 64) 12447 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12448 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 12449 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12450 else if (RightSideIntValue == 64) 12451 S.Diag(Loc, diag::warn_xor_used_as_pow) 12452 << ExprStr << toString(XorValue, 10, true); 12453 else 12454 return; 12455 } else { 12456 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12457 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 12458 << toString(PowValue, 10, true) 12459 << FixItHint::CreateReplacement( 12460 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12461 } 12462 12463 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12464 << ("0x2 ^ " + RHSStr) << SuggestXor; 12465 } else if (LeftSideValue == 10) { 12466 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12467 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12468 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 12469 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12470 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12471 << ("0xA ^ " + RHSStr) << SuggestXor; 12472 } 12473 } 12474 12475 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12476 SourceLocation Loc) { 12477 // Ensure that either both operands are of the same vector type, or 12478 // one operand is of a vector type and the other is of its element type. 12479 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12480 /*AllowBothBool*/true, 12481 /*AllowBoolConversions*/false); 12482 if (vType.isNull()) 12483 return InvalidOperands(Loc, LHS, RHS); 12484 if (getLangOpts().OpenCL && 12485 getLangOpts().getOpenCLCompatibleVersion() < 120 && 12486 vType->hasFloatingRepresentation()) 12487 return InvalidOperands(Loc, LHS, RHS); 12488 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12489 // usage of the logical operators && and || with vectors in C. This 12490 // check could be notionally dropped. 12491 if (!getLangOpts().CPlusPlus && 12492 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12493 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12494 12495 return GetSignedVectorType(LHS.get()->getType()); 12496 } 12497 12498 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12499 SourceLocation Loc, 12500 bool IsCompAssign) { 12501 if (!IsCompAssign) { 12502 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12503 if (LHS.isInvalid()) 12504 return QualType(); 12505 } 12506 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12507 if (RHS.isInvalid()) 12508 return QualType(); 12509 12510 // For conversion purposes, we ignore any qualifiers. 12511 // For example, "const float" and "float" are equivalent. 12512 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12513 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12514 12515 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12516 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12517 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12518 12519 if (Context.hasSameType(LHSType, RHSType)) 12520 return LHSType; 12521 12522 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12523 // case we have to return InvalidOperands. 12524 ExprResult OriginalLHS = LHS; 12525 ExprResult OriginalRHS = RHS; 12526 if (LHSMatType && !RHSMatType) { 12527 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12528 if (!RHS.isInvalid()) 12529 return LHSType; 12530 12531 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12532 } 12533 12534 if (!LHSMatType && RHSMatType) { 12535 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12536 if (!LHS.isInvalid()) 12537 return RHSType; 12538 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12539 } 12540 12541 return InvalidOperands(Loc, LHS, RHS); 12542 } 12543 12544 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12545 SourceLocation Loc, 12546 bool IsCompAssign) { 12547 if (!IsCompAssign) { 12548 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12549 if (LHS.isInvalid()) 12550 return QualType(); 12551 } 12552 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12553 if (RHS.isInvalid()) 12554 return QualType(); 12555 12556 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12557 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12558 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12559 12560 if (LHSMatType && RHSMatType) { 12561 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12562 return InvalidOperands(Loc, LHS, RHS); 12563 12564 if (!Context.hasSameType(LHSMatType->getElementType(), 12565 RHSMatType->getElementType())) 12566 return InvalidOperands(Loc, LHS, RHS); 12567 12568 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12569 LHSMatType->getNumRows(), 12570 RHSMatType->getNumColumns()); 12571 } 12572 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12573 } 12574 12575 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12576 SourceLocation Loc, 12577 BinaryOperatorKind Opc) { 12578 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12579 12580 bool IsCompAssign = 12581 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12582 12583 if (LHS.get()->getType()->isVectorType() || 12584 RHS.get()->getType()->isVectorType()) { 12585 if (LHS.get()->getType()->hasIntegerRepresentation() && 12586 RHS.get()->getType()->hasIntegerRepresentation()) 12587 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12588 /*AllowBothBool*/true, 12589 /*AllowBoolConversions*/getLangOpts().ZVector); 12590 return InvalidOperands(Loc, LHS, RHS); 12591 } 12592 12593 if (Opc == BO_And) 12594 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12595 12596 if (LHS.get()->getType()->hasFloatingRepresentation() || 12597 RHS.get()->getType()->hasFloatingRepresentation()) 12598 return InvalidOperands(Loc, LHS, RHS); 12599 12600 ExprResult LHSResult = LHS, RHSResult = RHS; 12601 QualType compType = UsualArithmeticConversions( 12602 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12603 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12604 return QualType(); 12605 LHS = LHSResult.get(); 12606 RHS = RHSResult.get(); 12607 12608 if (Opc == BO_Xor) 12609 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12610 12611 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12612 return compType; 12613 return InvalidOperands(Loc, LHS, RHS); 12614 } 12615 12616 // C99 6.5.[13,14] 12617 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12618 SourceLocation Loc, 12619 BinaryOperatorKind Opc) { 12620 // Check vector operands differently. 12621 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12622 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12623 12624 bool EnumConstantInBoolContext = false; 12625 for (const ExprResult &HS : {LHS, RHS}) { 12626 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12627 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12628 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12629 EnumConstantInBoolContext = true; 12630 } 12631 } 12632 12633 if (EnumConstantInBoolContext) 12634 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12635 12636 // Diagnose cases where the user write a logical and/or but probably meant a 12637 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12638 // is a constant. 12639 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12640 !LHS.get()->getType()->isBooleanType() && 12641 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12642 // Don't warn in macros or template instantiations. 12643 !Loc.isMacroID() && !inTemplateInstantiation()) { 12644 // If the RHS can be constant folded, and if it constant folds to something 12645 // that isn't 0 or 1 (which indicate a potential logical operation that 12646 // happened to fold to true/false) then warn. 12647 // Parens on the RHS are ignored. 12648 Expr::EvalResult EVResult; 12649 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12650 llvm::APSInt Result = EVResult.Val.getInt(); 12651 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12652 !RHS.get()->getExprLoc().isMacroID()) || 12653 (Result != 0 && Result != 1)) { 12654 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12655 << RHS.get()->getSourceRange() 12656 << (Opc == BO_LAnd ? "&&" : "||"); 12657 // Suggest replacing the logical operator with the bitwise version 12658 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12659 << (Opc == BO_LAnd ? "&" : "|") 12660 << FixItHint::CreateReplacement(SourceRange( 12661 Loc, getLocForEndOfToken(Loc)), 12662 Opc == BO_LAnd ? "&" : "|"); 12663 if (Opc == BO_LAnd) 12664 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12665 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12666 << FixItHint::CreateRemoval( 12667 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12668 RHS.get()->getEndLoc())); 12669 } 12670 } 12671 } 12672 12673 if (!Context.getLangOpts().CPlusPlus) { 12674 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12675 // not operate on the built-in scalar and vector float types. 12676 if (Context.getLangOpts().OpenCL && 12677 Context.getLangOpts().OpenCLVersion < 120) { 12678 if (LHS.get()->getType()->isFloatingType() || 12679 RHS.get()->getType()->isFloatingType()) 12680 return InvalidOperands(Loc, LHS, RHS); 12681 } 12682 12683 LHS = UsualUnaryConversions(LHS.get()); 12684 if (LHS.isInvalid()) 12685 return QualType(); 12686 12687 RHS = UsualUnaryConversions(RHS.get()); 12688 if (RHS.isInvalid()) 12689 return QualType(); 12690 12691 if (!LHS.get()->getType()->isScalarType() || 12692 !RHS.get()->getType()->isScalarType()) 12693 return InvalidOperands(Loc, LHS, RHS); 12694 12695 return Context.IntTy; 12696 } 12697 12698 // The following is safe because we only use this method for 12699 // non-overloadable operands. 12700 12701 // C++ [expr.log.and]p1 12702 // C++ [expr.log.or]p1 12703 // The operands are both contextually converted to type bool. 12704 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12705 if (LHSRes.isInvalid()) 12706 return InvalidOperands(Loc, LHS, RHS); 12707 LHS = LHSRes; 12708 12709 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12710 if (RHSRes.isInvalid()) 12711 return InvalidOperands(Loc, LHS, RHS); 12712 RHS = RHSRes; 12713 12714 // C++ [expr.log.and]p2 12715 // C++ [expr.log.or]p2 12716 // The result is a bool. 12717 return Context.BoolTy; 12718 } 12719 12720 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12721 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12722 if (!ME) return false; 12723 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12724 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12725 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12726 if (!Base) return false; 12727 return Base->getMethodDecl() != nullptr; 12728 } 12729 12730 /// Is the given expression (which must be 'const') a reference to a 12731 /// variable which was originally non-const, but which has become 12732 /// 'const' due to being captured within a block? 12733 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12734 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12735 assert(E->isLValue() && E->getType().isConstQualified()); 12736 E = E->IgnoreParens(); 12737 12738 // Must be a reference to a declaration from an enclosing scope. 12739 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12740 if (!DRE) return NCCK_None; 12741 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12742 12743 // The declaration must be a variable which is not declared 'const'. 12744 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12745 if (!var) return NCCK_None; 12746 if (var->getType().isConstQualified()) return NCCK_None; 12747 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12748 12749 // Decide whether the first capture was for a block or a lambda. 12750 DeclContext *DC = S.CurContext, *Prev = nullptr; 12751 // Decide whether the first capture was for a block or a lambda. 12752 while (DC) { 12753 // For init-capture, it is possible that the variable belongs to the 12754 // template pattern of the current context. 12755 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12756 if (var->isInitCapture() && 12757 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12758 break; 12759 if (DC == var->getDeclContext()) 12760 break; 12761 Prev = DC; 12762 DC = DC->getParent(); 12763 } 12764 // Unless we have an init-capture, we've gone one step too far. 12765 if (!var->isInitCapture()) 12766 DC = Prev; 12767 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12768 } 12769 12770 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12771 Ty = Ty.getNonReferenceType(); 12772 if (IsDereference && Ty->isPointerType()) 12773 Ty = Ty->getPointeeType(); 12774 return !Ty.isConstQualified(); 12775 } 12776 12777 // Update err_typecheck_assign_const and note_typecheck_assign_const 12778 // when this enum is changed. 12779 enum { 12780 ConstFunction, 12781 ConstVariable, 12782 ConstMember, 12783 ConstMethod, 12784 NestedConstMember, 12785 ConstUnknown, // Keep as last element 12786 }; 12787 12788 /// Emit the "read-only variable not assignable" error and print notes to give 12789 /// more information about why the variable is not assignable, such as pointing 12790 /// to the declaration of a const variable, showing that a method is const, or 12791 /// that the function is returning a const reference. 12792 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12793 SourceLocation Loc) { 12794 SourceRange ExprRange = E->getSourceRange(); 12795 12796 // Only emit one error on the first const found. All other consts will emit 12797 // a note to the error. 12798 bool DiagnosticEmitted = false; 12799 12800 // Track if the current expression is the result of a dereference, and if the 12801 // next checked expression is the result of a dereference. 12802 bool IsDereference = false; 12803 bool NextIsDereference = false; 12804 12805 // Loop to process MemberExpr chains. 12806 while (true) { 12807 IsDereference = NextIsDereference; 12808 12809 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12810 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12811 NextIsDereference = ME->isArrow(); 12812 const ValueDecl *VD = ME->getMemberDecl(); 12813 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12814 // Mutable fields can be modified even if the class is const. 12815 if (Field->isMutable()) { 12816 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12817 break; 12818 } 12819 12820 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12821 if (!DiagnosticEmitted) { 12822 S.Diag(Loc, diag::err_typecheck_assign_const) 12823 << ExprRange << ConstMember << false /*static*/ << Field 12824 << Field->getType(); 12825 DiagnosticEmitted = true; 12826 } 12827 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12828 << ConstMember << false /*static*/ << Field << Field->getType() 12829 << Field->getSourceRange(); 12830 } 12831 E = ME->getBase(); 12832 continue; 12833 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12834 if (VDecl->getType().isConstQualified()) { 12835 if (!DiagnosticEmitted) { 12836 S.Diag(Loc, diag::err_typecheck_assign_const) 12837 << ExprRange << ConstMember << true /*static*/ << VDecl 12838 << VDecl->getType(); 12839 DiagnosticEmitted = true; 12840 } 12841 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12842 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12843 << VDecl->getSourceRange(); 12844 } 12845 // Static fields do not inherit constness from parents. 12846 break; 12847 } 12848 break; // End MemberExpr 12849 } else if (const ArraySubscriptExpr *ASE = 12850 dyn_cast<ArraySubscriptExpr>(E)) { 12851 E = ASE->getBase()->IgnoreParenImpCasts(); 12852 continue; 12853 } else if (const ExtVectorElementExpr *EVE = 12854 dyn_cast<ExtVectorElementExpr>(E)) { 12855 E = EVE->getBase()->IgnoreParenImpCasts(); 12856 continue; 12857 } 12858 break; 12859 } 12860 12861 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12862 // Function calls 12863 const FunctionDecl *FD = CE->getDirectCallee(); 12864 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12865 if (!DiagnosticEmitted) { 12866 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12867 << ConstFunction << FD; 12868 DiagnosticEmitted = true; 12869 } 12870 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12871 diag::note_typecheck_assign_const) 12872 << ConstFunction << FD << FD->getReturnType() 12873 << FD->getReturnTypeSourceRange(); 12874 } 12875 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12876 // Point to variable declaration. 12877 if (const ValueDecl *VD = DRE->getDecl()) { 12878 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12879 if (!DiagnosticEmitted) { 12880 S.Diag(Loc, diag::err_typecheck_assign_const) 12881 << ExprRange << ConstVariable << VD << VD->getType(); 12882 DiagnosticEmitted = true; 12883 } 12884 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12885 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12886 } 12887 } 12888 } else if (isa<CXXThisExpr>(E)) { 12889 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12890 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12891 if (MD->isConst()) { 12892 if (!DiagnosticEmitted) { 12893 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12894 << ConstMethod << MD; 12895 DiagnosticEmitted = true; 12896 } 12897 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12898 << ConstMethod << MD << MD->getSourceRange(); 12899 } 12900 } 12901 } 12902 } 12903 12904 if (DiagnosticEmitted) 12905 return; 12906 12907 // Can't determine a more specific message, so display the generic error. 12908 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12909 } 12910 12911 enum OriginalExprKind { 12912 OEK_Variable, 12913 OEK_Member, 12914 OEK_LValue 12915 }; 12916 12917 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12918 const RecordType *Ty, 12919 SourceLocation Loc, SourceRange Range, 12920 OriginalExprKind OEK, 12921 bool &DiagnosticEmitted) { 12922 std::vector<const RecordType *> RecordTypeList; 12923 RecordTypeList.push_back(Ty); 12924 unsigned NextToCheckIndex = 0; 12925 // We walk the record hierarchy breadth-first to ensure that we print 12926 // diagnostics in field nesting order. 12927 while (RecordTypeList.size() > NextToCheckIndex) { 12928 bool IsNested = NextToCheckIndex > 0; 12929 for (const FieldDecl *Field : 12930 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12931 // First, check every field for constness. 12932 QualType FieldTy = Field->getType(); 12933 if (FieldTy.isConstQualified()) { 12934 if (!DiagnosticEmitted) { 12935 S.Diag(Loc, diag::err_typecheck_assign_const) 12936 << Range << NestedConstMember << OEK << VD 12937 << IsNested << Field; 12938 DiagnosticEmitted = true; 12939 } 12940 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12941 << NestedConstMember << IsNested << Field 12942 << FieldTy << Field->getSourceRange(); 12943 } 12944 12945 // Then we append it to the list to check next in order. 12946 FieldTy = FieldTy.getCanonicalType(); 12947 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12948 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12949 RecordTypeList.push_back(FieldRecTy); 12950 } 12951 } 12952 ++NextToCheckIndex; 12953 } 12954 } 12955 12956 /// Emit an error for the case where a record we are trying to assign to has a 12957 /// const-qualified field somewhere in its hierarchy. 12958 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12959 SourceLocation Loc) { 12960 QualType Ty = E->getType(); 12961 assert(Ty->isRecordType() && "lvalue was not record?"); 12962 SourceRange Range = E->getSourceRange(); 12963 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12964 bool DiagEmitted = false; 12965 12966 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12967 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12968 Range, OEK_Member, DiagEmitted); 12969 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12970 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12971 Range, OEK_Variable, DiagEmitted); 12972 else 12973 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12974 Range, OEK_LValue, DiagEmitted); 12975 if (!DiagEmitted) 12976 DiagnoseConstAssignment(S, E, Loc); 12977 } 12978 12979 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12980 /// emit an error and return true. If so, return false. 12981 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12982 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12983 12984 S.CheckShadowingDeclModification(E, Loc); 12985 12986 SourceLocation OrigLoc = Loc; 12987 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12988 &Loc); 12989 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12990 IsLV = Expr::MLV_InvalidMessageExpression; 12991 if (IsLV == Expr::MLV_Valid) 12992 return false; 12993 12994 unsigned DiagID = 0; 12995 bool NeedType = false; 12996 switch (IsLV) { // C99 6.5.16p2 12997 case Expr::MLV_ConstQualified: 12998 // Use a specialized diagnostic when we're assigning to an object 12999 // from an enclosing function or block. 13000 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 13001 if (NCCK == NCCK_Block) 13002 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 13003 else 13004 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 13005 break; 13006 } 13007 13008 // In ARC, use some specialized diagnostics for occasions where we 13009 // infer 'const'. These are always pseudo-strong variables. 13010 if (S.getLangOpts().ObjCAutoRefCount) { 13011 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 13012 if (declRef && isa<VarDecl>(declRef->getDecl())) { 13013 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 13014 13015 // Use the normal diagnostic if it's pseudo-__strong but the 13016 // user actually wrote 'const'. 13017 if (var->isARCPseudoStrong() && 13018 (!var->getTypeSourceInfo() || 13019 !var->getTypeSourceInfo()->getType().isConstQualified())) { 13020 // There are three pseudo-strong cases: 13021 // - self 13022 ObjCMethodDecl *method = S.getCurMethodDecl(); 13023 if (method && var == method->getSelfDecl()) { 13024 DiagID = method->isClassMethod() 13025 ? diag::err_typecheck_arc_assign_self_class_method 13026 : diag::err_typecheck_arc_assign_self; 13027 13028 // - Objective-C externally_retained attribute. 13029 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 13030 isa<ParmVarDecl>(var)) { 13031 DiagID = diag::err_typecheck_arc_assign_externally_retained; 13032 13033 // - fast enumeration variables 13034 } else { 13035 DiagID = diag::err_typecheck_arr_assign_enumeration; 13036 } 13037 13038 SourceRange Assign; 13039 if (Loc != OrigLoc) 13040 Assign = SourceRange(OrigLoc, OrigLoc); 13041 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13042 // We need to preserve the AST regardless, so migration tool 13043 // can do its job. 13044 return false; 13045 } 13046 } 13047 } 13048 13049 // If none of the special cases above are triggered, then this is a 13050 // simple const assignment. 13051 if (DiagID == 0) { 13052 DiagnoseConstAssignment(S, E, Loc); 13053 return true; 13054 } 13055 13056 break; 13057 case Expr::MLV_ConstAddrSpace: 13058 DiagnoseConstAssignment(S, E, Loc); 13059 return true; 13060 case Expr::MLV_ConstQualifiedField: 13061 DiagnoseRecursiveConstFields(S, E, Loc); 13062 return true; 13063 case Expr::MLV_ArrayType: 13064 case Expr::MLV_ArrayTemporary: 13065 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 13066 NeedType = true; 13067 break; 13068 case Expr::MLV_NotObjectType: 13069 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 13070 NeedType = true; 13071 break; 13072 case Expr::MLV_LValueCast: 13073 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 13074 break; 13075 case Expr::MLV_Valid: 13076 llvm_unreachable("did not take early return for MLV_Valid"); 13077 case Expr::MLV_InvalidExpression: 13078 case Expr::MLV_MemberFunction: 13079 case Expr::MLV_ClassTemporary: 13080 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 13081 break; 13082 case Expr::MLV_IncompleteType: 13083 case Expr::MLV_IncompleteVoidType: 13084 return S.RequireCompleteType(Loc, E->getType(), 13085 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 13086 case Expr::MLV_DuplicateVectorComponents: 13087 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 13088 break; 13089 case Expr::MLV_NoSetterProperty: 13090 llvm_unreachable("readonly properties should be processed differently"); 13091 case Expr::MLV_InvalidMessageExpression: 13092 DiagID = diag::err_readonly_message_assignment; 13093 break; 13094 case Expr::MLV_SubObjCPropertySetting: 13095 DiagID = diag::err_no_subobject_property_setting; 13096 break; 13097 } 13098 13099 SourceRange Assign; 13100 if (Loc != OrigLoc) 13101 Assign = SourceRange(OrigLoc, OrigLoc); 13102 if (NeedType) 13103 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 13104 else 13105 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13106 return true; 13107 } 13108 13109 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 13110 SourceLocation Loc, 13111 Sema &Sema) { 13112 if (Sema.inTemplateInstantiation()) 13113 return; 13114 if (Sema.isUnevaluatedContext()) 13115 return; 13116 if (Loc.isInvalid() || Loc.isMacroID()) 13117 return; 13118 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 13119 return; 13120 13121 // C / C++ fields 13122 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 13123 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 13124 if (ML && MR) { 13125 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 13126 return; 13127 const ValueDecl *LHSDecl = 13128 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 13129 const ValueDecl *RHSDecl = 13130 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13131 if (LHSDecl != RHSDecl) 13132 return; 13133 if (LHSDecl->getType().isVolatileQualified()) 13134 return; 13135 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13136 if (RefTy->getPointeeType().isVolatileQualified()) 13137 return; 13138 13139 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13140 } 13141 13142 // Objective-C instance variables 13143 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13144 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13145 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13146 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13147 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13148 if (RL && RR && RL->getDecl() == RR->getDecl()) 13149 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13150 } 13151 } 13152 13153 // C99 6.5.16.1 13154 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13155 SourceLocation Loc, 13156 QualType CompoundType) { 13157 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13158 13159 // Verify that LHS is a modifiable lvalue, and emit error if not. 13160 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13161 return QualType(); 13162 13163 QualType LHSType = LHSExpr->getType(); 13164 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13165 CompoundType; 13166 // OpenCL v1.2 s6.1.1.1 p2: 13167 // The half data type can only be used to declare a pointer to a buffer that 13168 // contains half values 13169 if (getLangOpts().OpenCL && 13170 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13171 LHSType->isHalfType()) { 13172 Diag(Loc, diag::err_opencl_half_load_store) << 1 13173 << LHSType.getUnqualifiedType(); 13174 return QualType(); 13175 } 13176 13177 AssignConvertType ConvTy; 13178 if (CompoundType.isNull()) { 13179 Expr *RHSCheck = RHS.get(); 13180 13181 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13182 13183 QualType LHSTy(LHSType); 13184 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13185 if (RHS.isInvalid()) 13186 return QualType(); 13187 // Special case of NSObject attributes on c-style pointer types. 13188 if (ConvTy == IncompatiblePointer && 13189 ((Context.isObjCNSObjectType(LHSType) && 13190 RHSType->isObjCObjectPointerType()) || 13191 (Context.isObjCNSObjectType(RHSType) && 13192 LHSType->isObjCObjectPointerType()))) 13193 ConvTy = Compatible; 13194 13195 if (ConvTy == Compatible && 13196 LHSType->isObjCObjectType()) 13197 Diag(Loc, diag::err_objc_object_assignment) 13198 << LHSType; 13199 13200 // If the RHS is a unary plus or minus, check to see if they = and + are 13201 // right next to each other. If so, the user may have typo'd "x =+ 4" 13202 // instead of "x += 4". 13203 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13204 RHSCheck = ICE->getSubExpr(); 13205 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13206 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13207 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13208 // Only if the two operators are exactly adjacent. 13209 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13210 // And there is a space or other character before the subexpr of the 13211 // unary +/-. We don't want to warn on "x=-1". 13212 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13213 UO->getSubExpr()->getBeginLoc().isFileID()) { 13214 Diag(Loc, diag::warn_not_compound_assign) 13215 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13216 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13217 } 13218 } 13219 13220 if (ConvTy == Compatible) { 13221 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13222 // Warn about retain cycles where a block captures the LHS, but 13223 // not if the LHS is a simple variable into which the block is 13224 // being stored...unless that variable can be captured by reference! 13225 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13226 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13227 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13228 checkRetainCycles(LHSExpr, RHS.get()); 13229 } 13230 13231 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13232 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13233 // It is safe to assign a weak reference into a strong variable. 13234 // Although this code can still have problems: 13235 // id x = self.weakProp; 13236 // id y = self.weakProp; 13237 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13238 // paths through the function. This should be revisited if 13239 // -Wrepeated-use-of-weak is made flow-sensitive. 13240 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13241 // variable, which will be valid for the current autorelease scope. 13242 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13243 RHS.get()->getBeginLoc())) 13244 getCurFunction()->markSafeWeakUse(RHS.get()); 13245 13246 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13247 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13248 } 13249 } 13250 } else { 13251 // Compound assignment "x += y" 13252 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13253 } 13254 13255 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13256 RHS.get(), AA_Assigning)) 13257 return QualType(); 13258 13259 CheckForNullPointerDereference(*this, LHSExpr); 13260 13261 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13262 if (CompoundType.isNull()) { 13263 // C++2a [expr.ass]p5: 13264 // A simple-assignment whose left operand is of a volatile-qualified 13265 // type is deprecated unless the assignment is either a discarded-value 13266 // expression or an unevaluated operand 13267 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13268 } else { 13269 // C++2a [expr.ass]p6: 13270 // [Compound-assignment] expressions are deprecated if E1 has 13271 // volatile-qualified type 13272 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13273 } 13274 } 13275 13276 // C99 6.5.16p3: The type of an assignment expression is the type of the 13277 // left operand unless the left operand has qualified type, in which case 13278 // it is the unqualified version of the type of the left operand. 13279 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13280 // is converted to the type of the assignment expression (above). 13281 // C++ 5.17p1: the type of the assignment expression is that of its left 13282 // operand. 13283 return (getLangOpts().CPlusPlus 13284 ? LHSType : LHSType.getUnqualifiedType()); 13285 } 13286 13287 // Only ignore explicit casts to void. 13288 static bool IgnoreCommaOperand(const Expr *E) { 13289 E = E->IgnoreParens(); 13290 13291 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13292 if (CE->getCastKind() == CK_ToVoid) { 13293 return true; 13294 } 13295 13296 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13297 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13298 CE->getSubExpr()->getType()->isDependentType()) { 13299 return true; 13300 } 13301 } 13302 13303 return false; 13304 } 13305 13306 // Look for instances where it is likely the comma operator is confused with 13307 // another operator. There is an explicit list of acceptable expressions for 13308 // the left hand side of the comma operator, otherwise emit a warning. 13309 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13310 // No warnings in macros 13311 if (Loc.isMacroID()) 13312 return; 13313 13314 // Don't warn in template instantiations. 13315 if (inTemplateInstantiation()) 13316 return; 13317 13318 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13319 // instead, skip more than needed, then call back into here with the 13320 // CommaVisitor in SemaStmt.cpp. 13321 // The listed locations are the initialization and increment portions 13322 // of a for loop. The additional checks are on the condition of 13323 // if statements, do/while loops, and for loops. 13324 // Differences in scope flags for C89 mode requires the extra logic. 13325 const unsigned ForIncrementFlags = 13326 getLangOpts().C99 || getLangOpts().CPlusPlus 13327 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13328 : Scope::ContinueScope | Scope::BreakScope; 13329 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13330 const unsigned ScopeFlags = getCurScope()->getFlags(); 13331 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13332 (ScopeFlags & ForInitFlags) == ForInitFlags) 13333 return; 13334 13335 // If there are multiple comma operators used together, get the RHS of the 13336 // of the comma operator as the LHS. 13337 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13338 if (BO->getOpcode() != BO_Comma) 13339 break; 13340 LHS = BO->getRHS(); 13341 } 13342 13343 // Only allow some expressions on LHS to not warn. 13344 if (IgnoreCommaOperand(LHS)) 13345 return; 13346 13347 Diag(Loc, diag::warn_comma_operator); 13348 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13349 << LHS->getSourceRange() 13350 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13351 LangOpts.CPlusPlus ? "static_cast<void>(" 13352 : "(void)(") 13353 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13354 ")"); 13355 } 13356 13357 // C99 6.5.17 13358 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13359 SourceLocation Loc) { 13360 LHS = S.CheckPlaceholderExpr(LHS.get()); 13361 RHS = S.CheckPlaceholderExpr(RHS.get()); 13362 if (LHS.isInvalid() || RHS.isInvalid()) 13363 return QualType(); 13364 13365 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13366 // operands, but not unary promotions. 13367 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13368 13369 // So we treat the LHS as a ignored value, and in C++ we allow the 13370 // containing site to determine what should be done with the RHS. 13371 LHS = S.IgnoredValueConversions(LHS.get()); 13372 if (LHS.isInvalid()) 13373 return QualType(); 13374 13375 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand); 13376 13377 if (!S.getLangOpts().CPlusPlus) { 13378 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13379 if (RHS.isInvalid()) 13380 return QualType(); 13381 if (!RHS.get()->getType()->isVoidType()) 13382 S.RequireCompleteType(Loc, RHS.get()->getType(), 13383 diag::err_incomplete_type); 13384 } 13385 13386 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13387 S.DiagnoseCommaOperator(LHS.get(), Loc); 13388 13389 return RHS.get()->getType(); 13390 } 13391 13392 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13393 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13394 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13395 ExprValueKind &VK, 13396 ExprObjectKind &OK, 13397 SourceLocation OpLoc, 13398 bool IsInc, bool IsPrefix) { 13399 if (Op->isTypeDependent()) 13400 return S.Context.DependentTy; 13401 13402 QualType ResType = Op->getType(); 13403 // Atomic types can be used for increment / decrement where the non-atomic 13404 // versions can, so ignore the _Atomic() specifier for the purpose of 13405 // checking. 13406 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13407 ResType = ResAtomicType->getValueType(); 13408 13409 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13410 13411 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13412 // Decrement of bool is not allowed. 13413 if (!IsInc) { 13414 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13415 return QualType(); 13416 } 13417 // Increment of bool sets it to true, but is deprecated. 13418 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13419 : diag::warn_increment_bool) 13420 << Op->getSourceRange(); 13421 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13422 // Error on enum increments and decrements in C++ mode 13423 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13424 return QualType(); 13425 } else if (ResType->isRealType()) { 13426 // OK! 13427 } else if (ResType->isPointerType()) { 13428 // C99 6.5.2.4p2, 6.5.6p2 13429 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13430 return QualType(); 13431 } else if (ResType->isObjCObjectPointerType()) { 13432 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13433 // Otherwise, we just need a complete type. 13434 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13435 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13436 return QualType(); 13437 } else if (ResType->isAnyComplexType()) { 13438 // C99 does not support ++/-- on complex types, we allow as an extension. 13439 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13440 << ResType << Op->getSourceRange(); 13441 } else if (ResType->isPlaceholderType()) { 13442 ExprResult PR = S.CheckPlaceholderExpr(Op); 13443 if (PR.isInvalid()) return QualType(); 13444 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13445 IsInc, IsPrefix); 13446 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13447 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13448 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13449 (ResType->castAs<VectorType>()->getVectorKind() != 13450 VectorType::AltiVecBool)) { 13451 // The z vector extensions allow ++ and -- for non-bool vectors. 13452 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13453 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13454 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13455 } else { 13456 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13457 << ResType << int(IsInc) << Op->getSourceRange(); 13458 return QualType(); 13459 } 13460 // At this point, we know we have a real, complex or pointer type. 13461 // Now make sure the operand is a modifiable lvalue. 13462 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13463 return QualType(); 13464 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13465 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13466 // An operand with volatile-qualified type is deprecated 13467 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13468 << IsInc << ResType; 13469 } 13470 // In C++, a prefix increment is the same type as the operand. Otherwise 13471 // (in C or with postfix), the increment is the unqualified type of the 13472 // operand. 13473 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13474 VK = VK_LValue; 13475 OK = Op->getObjectKind(); 13476 return ResType; 13477 } else { 13478 VK = VK_PRValue; 13479 return ResType.getUnqualifiedType(); 13480 } 13481 } 13482 13483 13484 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13485 /// This routine allows us to typecheck complex/recursive expressions 13486 /// where the declaration is needed for type checking. We only need to 13487 /// handle cases when the expression references a function designator 13488 /// or is an lvalue. Here are some examples: 13489 /// - &(x) => x 13490 /// - &*****f => f for f a function designator. 13491 /// - &s.xx => s 13492 /// - &s.zz[1].yy -> s, if zz is an array 13493 /// - *(x + 1) -> x, if x is an array 13494 /// - &"123"[2] -> 0 13495 /// - & __real__ x -> x 13496 /// 13497 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13498 /// members. 13499 static ValueDecl *getPrimaryDecl(Expr *E) { 13500 switch (E->getStmtClass()) { 13501 case Stmt::DeclRefExprClass: 13502 return cast<DeclRefExpr>(E)->getDecl(); 13503 case Stmt::MemberExprClass: 13504 // If this is an arrow operator, the address is an offset from 13505 // the base's value, so the object the base refers to is 13506 // irrelevant. 13507 if (cast<MemberExpr>(E)->isArrow()) 13508 return nullptr; 13509 // Otherwise, the expression refers to a part of the base 13510 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13511 case Stmt::ArraySubscriptExprClass: { 13512 // FIXME: This code shouldn't be necessary! We should catch the implicit 13513 // promotion of register arrays earlier. 13514 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13515 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13516 if (ICE->getSubExpr()->getType()->isArrayType()) 13517 return getPrimaryDecl(ICE->getSubExpr()); 13518 } 13519 return nullptr; 13520 } 13521 case Stmt::UnaryOperatorClass: { 13522 UnaryOperator *UO = cast<UnaryOperator>(E); 13523 13524 switch(UO->getOpcode()) { 13525 case UO_Real: 13526 case UO_Imag: 13527 case UO_Extension: 13528 return getPrimaryDecl(UO->getSubExpr()); 13529 default: 13530 return nullptr; 13531 } 13532 } 13533 case Stmt::ParenExprClass: 13534 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13535 case Stmt::ImplicitCastExprClass: 13536 // If the result of an implicit cast is an l-value, we care about 13537 // the sub-expression; otherwise, the result here doesn't matter. 13538 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13539 case Stmt::CXXUuidofExprClass: 13540 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13541 default: 13542 return nullptr; 13543 } 13544 } 13545 13546 namespace { 13547 enum { 13548 AO_Bit_Field = 0, 13549 AO_Vector_Element = 1, 13550 AO_Property_Expansion = 2, 13551 AO_Register_Variable = 3, 13552 AO_Matrix_Element = 4, 13553 AO_No_Error = 5 13554 }; 13555 } 13556 /// Diagnose invalid operand for address of operations. 13557 /// 13558 /// \param Type The type of operand which cannot have its address taken. 13559 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13560 Expr *E, unsigned Type) { 13561 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13562 } 13563 13564 /// CheckAddressOfOperand - The operand of & must be either a function 13565 /// designator or an lvalue designating an object. If it is an lvalue, the 13566 /// object cannot be declared with storage class register or be a bit field. 13567 /// Note: The usual conversions are *not* applied to the operand of the & 13568 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13569 /// In C++, the operand might be an overloaded function name, in which case 13570 /// we allow the '&' but retain the overloaded-function type. 13571 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13572 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13573 if (PTy->getKind() == BuiltinType::Overload) { 13574 Expr *E = OrigOp.get()->IgnoreParens(); 13575 if (!isa<OverloadExpr>(E)) { 13576 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13577 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13578 << OrigOp.get()->getSourceRange(); 13579 return QualType(); 13580 } 13581 13582 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13583 if (isa<UnresolvedMemberExpr>(Ovl)) 13584 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13585 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13586 << OrigOp.get()->getSourceRange(); 13587 return QualType(); 13588 } 13589 13590 return Context.OverloadTy; 13591 } 13592 13593 if (PTy->getKind() == BuiltinType::UnknownAny) 13594 return Context.UnknownAnyTy; 13595 13596 if (PTy->getKind() == BuiltinType::BoundMember) { 13597 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13598 << OrigOp.get()->getSourceRange(); 13599 return QualType(); 13600 } 13601 13602 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13603 if (OrigOp.isInvalid()) return QualType(); 13604 } 13605 13606 if (OrigOp.get()->isTypeDependent()) 13607 return Context.DependentTy; 13608 13609 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13610 13611 // Make sure to ignore parentheses in subsequent checks 13612 Expr *op = OrigOp.get()->IgnoreParens(); 13613 13614 // In OpenCL captures for blocks called as lambda functions 13615 // are located in the private address space. Blocks used in 13616 // enqueue_kernel can be located in a different address space 13617 // depending on a vendor implementation. Thus preventing 13618 // taking an address of the capture to avoid invalid AS casts. 13619 if (LangOpts.OpenCL) { 13620 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13621 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13622 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13623 return QualType(); 13624 } 13625 } 13626 13627 if (getLangOpts().C99) { 13628 // Implement C99-only parts of addressof rules. 13629 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13630 if (uOp->getOpcode() == UO_Deref) 13631 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13632 // (assuming the deref expression is valid). 13633 return uOp->getSubExpr()->getType(); 13634 } 13635 // Technically, there should be a check for array subscript 13636 // expressions here, but the result of one is always an lvalue anyway. 13637 } 13638 ValueDecl *dcl = getPrimaryDecl(op); 13639 13640 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13641 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13642 op->getBeginLoc())) 13643 return QualType(); 13644 13645 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13646 unsigned AddressOfError = AO_No_Error; 13647 13648 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13649 bool sfinae = (bool)isSFINAEContext(); 13650 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13651 : diag::ext_typecheck_addrof_temporary) 13652 << op->getType() << op->getSourceRange(); 13653 if (sfinae) 13654 return QualType(); 13655 // Materialize the temporary as an lvalue so that we can take its address. 13656 OrigOp = op = 13657 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13658 } else if (isa<ObjCSelectorExpr>(op)) { 13659 return Context.getPointerType(op->getType()); 13660 } else if (lval == Expr::LV_MemberFunction) { 13661 // If it's an instance method, make a member pointer. 13662 // The expression must have exactly the form &A::foo. 13663 13664 // If the underlying expression isn't a decl ref, give up. 13665 if (!isa<DeclRefExpr>(op)) { 13666 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13667 << OrigOp.get()->getSourceRange(); 13668 return QualType(); 13669 } 13670 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13671 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13672 13673 // The id-expression was parenthesized. 13674 if (OrigOp.get() != DRE) { 13675 Diag(OpLoc, diag::err_parens_pointer_member_function) 13676 << OrigOp.get()->getSourceRange(); 13677 13678 // The method was named without a qualifier. 13679 } else if (!DRE->getQualifier()) { 13680 if (MD->getParent()->getName().empty()) 13681 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13682 << op->getSourceRange(); 13683 else { 13684 SmallString<32> Str; 13685 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13686 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13687 << op->getSourceRange() 13688 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13689 } 13690 } 13691 13692 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13693 if (isa<CXXDestructorDecl>(MD)) 13694 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13695 13696 QualType MPTy = Context.getMemberPointerType( 13697 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13698 // Under the MS ABI, lock down the inheritance model now. 13699 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13700 (void)isCompleteType(OpLoc, MPTy); 13701 return MPTy; 13702 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13703 // C99 6.5.3.2p1 13704 // The operand must be either an l-value or a function designator 13705 if (!op->getType()->isFunctionType()) { 13706 // Use a special diagnostic for loads from property references. 13707 if (isa<PseudoObjectExpr>(op)) { 13708 AddressOfError = AO_Property_Expansion; 13709 } else { 13710 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13711 << op->getType() << op->getSourceRange(); 13712 return QualType(); 13713 } 13714 } 13715 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13716 // The operand cannot be a bit-field 13717 AddressOfError = AO_Bit_Field; 13718 } else if (op->getObjectKind() == OK_VectorComponent) { 13719 // The operand cannot be an element of a vector 13720 AddressOfError = AO_Vector_Element; 13721 } else if (op->getObjectKind() == OK_MatrixComponent) { 13722 // The operand cannot be an element of a matrix. 13723 AddressOfError = AO_Matrix_Element; 13724 } else if (dcl) { // C99 6.5.3.2p1 13725 // We have an lvalue with a decl. Make sure the decl is not declared 13726 // with the register storage-class specifier. 13727 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13728 // in C++ it is not error to take address of a register 13729 // variable (c++03 7.1.1P3) 13730 if (vd->getStorageClass() == SC_Register && 13731 !getLangOpts().CPlusPlus) { 13732 AddressOfError = AO_Register_Variable; 13733 } 13734 } else if (isa<MSPropertyDecl>(dcl)) { 13735 AddressOfError = AO_Property_Expansion; 13736 } else if (isa<FunctionTemplateDecl>(dcl)) { 13737 return Context.OverloadTy; 13738 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13739 // Okay: we can take the address of a field. 13740 // Could be a pointer to member, though, if there is an explicit 13741 // scope qualifier for the class. 13742 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13743 DeclContext *Ctx = dcl->getDeclContext(); 13744 if (Ctx && Ctx->isRecord()) { 13745 if (dcl->getType()->isReferenceType()) { 13746 Diag(OpLoc, 13747 diag::err_cannot_form_pointer_to_member_of_reference_type) 13748 << dcl->getDeclName() << dcl->getType(); 13749 return QualType(); 13750 } 13751 13752 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13753 Ctx = Ctx->getParent(); 13754 13755 QualType MPTy = Context.getMemberPointerType( 13756 op->getType(), 13757 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13758 // Under the MS ABI, lock down the inheritance model now. 13759 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13760 (void)isCompleteType(OpLoc, MPTy); 13761 return MPTy; 13762 } 13763 } 13764 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13765 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13766 llvm_unreachable("Unknown/unexpected decl type"); 13767 } 13768 13769 if (AddressOfError != AO_No_Error) { 13770 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13771 return QualType(); 13772 } 13773 13774 if (lval == Expr::LV_IncompleteVoidType) { 13775 // Taking the address of a void variable is technically illegal, but we 13776 // allow it in cases which are otherwise valid. 13777 // Example: "extern void x; void* y = &x;". 13778 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13779 } 13780 13781 // If the operand has type "type", the result has type "pointer to type". 13782 if (op->getType()->isObjCObjectType()) 13783 return Context.getObjCObjectPointerType(op->getType()); 13784 13785 CheckAddressOfPackedMember(op); 13786 13787 return Context.getPointerType(op->getType()); 13788 } 13789 13790 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13791 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13792 if (!DRE) 13793 return; 13794 const Decl *D = DRE->getDecl(); 13795 if (!D) 13796 return; 13797 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13798 if (!Param) 13799 return; 13800 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13801 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13802 return; 13803 if (FunctionScopeInfo *FD = S.getCurFunction()) 13804 if (!FD->ModifiedNonNullParams.count(Param)) 13805 FD->ModifiedNonNullParams.insert(Param); 13806 } 13807 13808 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13809 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13810 SourceLocation OpLoc) { 13811 if (Op->isTypeDependent()) 13812 return S.Context.DependentTy; 13813 13814 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13815 if (ConvResult.isInvalid()) 13816 return QualType(); 13817 Op = ConvResult.get(); 13818 QualType OpTy = Op->getType(); 13819 QualType Result; 13820 13821 if (isa<CXXReinterpretCastExpr>(Op)) { 13822 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13823 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13824 Op->getSourceRange()); 13825 } 13826 13827 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13828 { 13829 Result = PT->getPointeeType(); 13830 } 13831 else if (const ObjCObjectPointerType *OPT = 13832 OpTy->getAs<ObjCObjectPointerType>()) 13833 Result = OPT->getPointeeType(); 13834 else { 13835 ExprResult PR = S.CheckPlaceholderExpr(Op); 13836 if (PR.isInvalid()) return QualType(); 13837 if (PR.get() != Op) 13838 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13839 } 13840 13841 if (Result.isNull()) { 13842 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13843 << OpTy << Op->getSourceRange(); 13844 return QualType(); 13845 } 13846 13847 // Note that per both C89 and C99, indirection is always legal, even if Result 13848 // is an incomplete type or void. It would be possible to warn about 13849 // dereferencing a void pointer, but it's completely well-defined, and such a 13850 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13851 // for pointers to 'void' but is fine for any other pointer type: 13852 // 13853 // C++ [expr.unary.op]p1: 13854 // [...] the expression to which [the unary * operator] is applied shall 13855 // be a pointer to an object type, or a pointer to a function type 13856 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13857 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13858 << OpTy << Op->getSourceRange(); 13859 13860 // Dereferences are usually l-values... 13861 VK = VK_LValue; 13862 13863 // ...except that certain expressions are never l-values in C. 13864 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13865 VK = VK_PRValue; 13866 13867 return Result; 13868 } 13869 13870 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13871 BinaryOperatorKind Opc; 13872 switch (Kind) { 13873 default: llvm_unreachable("Unknown binop!"); 13874 case tok::periodstar: Opc = BO_PtrMemD; break; 13875 case tok::arrowstar: Opc = BO_PtrMemI; break; 13876 case tok::star: Opc = BO_Mul; break; 13877 case tok::slash: Opc = BO_Div; break; 13878 case tok::percent: Opc = BO_Rem; break; 13879 case tok::plus: Opc = BO_Add; break; 13880 case tok::minus: Opc = BO_Sub; break; 13881 case tok::lessless: Opc = BO_Shl; break; 13882 case tok::greatergreater: Opc = BO_Shr; break; 13883 case tok::lessequal: Opc = BO_LE; break; 13884 case tok::less: Opc = BO_LT; break; 13885 case tok::greaterequal: Opc = BO_GE; break; 13886 case tok::greater: Opc = BO_GT; break; 13887 case tok::exclaimequal: Opc = BO_NE; break; 13888 case tok::equalequal: Opc = BO_EQ; break; 13889 case tok::spaceship: Opc = BO_Cmp; break; 13890 case tok::amp: Opc = BO_And; break; 13891 case tok::caret: Opc = BO_Xor; break; 13892 case tok::pipe: Opc = BO_Or; break; 13893 case tok::ampamp: Opc = BO_LAnd; break; 13894 case tok::pipepipe: Opc = BO_LOr; break; 13895 case tok::equal: Opc = BO_Assign; break; 13896 case tok::starequal: Opc = BO_MulAssign; break; 13897 case tok::slashequal: Opc = BO_DivAssign; break; 13898 case tok::percentequal: Opc = BO_RemAssign; break; 13899 case tok::plusequal: Opc = BO_AddAssign; break; 13900 case tok::minusequal: Opc = BO_SubAssign; break; 13901 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13902 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13903 case tok::ampequal: Opc = BO_AndAssign; break; 13904 case tok::caretequal: Opc = BO_XorAssign; break; 13905 case tok::pipeequal: Opc = BO_OrAssign; break; 13906 case tok::comma: Opc = BO_Comma; break; 13907 } 13908 return Opc; 13909 } 13910 13911 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13912 tok::TokenKind Kind) { 13913 UnaryOperatorKind Opc; 13914 switch (Kind) { 13915 default: llvm_unreachable("Unknown unary op!"); 13916 case tok::plusplus: Opc = UO_PreInc; break; 13917 case tok::minusminus: Opc = UO_PreDec; break; 13918 case tok::amp: Opc = UO_AddrOf; break; 13919 case tok::star: Opc = UO_Deref; break; 13920 case tok::plus: Opc = UO_Plus; break; 13921 case tok::minus: Opc = UO_Minus; break; 13922 case tok::tilde: Opc = UO_Not; break; 13923 case tok::exclaim: Opc = UO_LNot; break; 13924 case tok::kw___real: Opc = UO_Real; break; 13925 case tok::kw___imag: Opc = UO_Imag; break; 13926 case tok::kw___extension__: Opc = UO_Extension; break; 13927 } 13928 return Opc; 13929 } 13930 13931 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13932 /// This warning suppressed in the event of macro expansions. 13933 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13934 SourceLocation OpLoc, bool IsBuiltin) { 13935 if (S.inTemplateInstantiation()) 13936 return; 13937 if (S.isUnevaluatedContext()) 13938 return; 13939 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13940 return; 13941 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13942 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13943 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13944 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13945 if (!LHSDeclRef || !RHSDeclRef || 13946 LHSDeclRef->getLocation().isMacroID() || 13947 RHSDeclRef->getLocation().isMacroID()) 13948 return; 13949 const ValueDecl *LHSDecl = 13950 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13951 const ValueDecl *RHSDecl = 13952 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13953 if (LHSDecl != RHSDecl) 13954 return; 13955 if (LHSDecl->getType().isVolatileQualified()) 13956 return; 13957 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13958 if (RefTy->getPointeeType().isVolatileQualified()) 13959 return; 13960 13961 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13962 : diag::warn_self_assignment_overloaded) 13963 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13964 << RHSExpr->getSourceRange(); 13965 } 13966 13967 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13968 /// is usually indicative of introspection within the Objective-C pointer. 13969 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13970 SourceLocation OpLoc) { 13971 if (!S.getLangOpts().ObjC) 13972 return; 13973 13974 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13975 const Expr *LHS = L.get(); 13976 const Expr *RHS = R.get(); 13977 13978 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13979 ObjCPointerExpr = LHS; 13980 OtherExpr = RHS; 13981 } 13982 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13983 ObjCPointerExpr = RHS; 13984 OtherExpr = LHS; 13985 } 13986 13987 // This warning is deliberately made very specific to reduce false 13988 // positives with logic that uses '&' for hashing. This logic mainly 13989 // looks for code trying to introspect into tagged pointers, which 13990 // code should generally never do. 13991 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13992 unsigned Diag = diag::warn_objc_pointer_masking; 13993 // Determine if we are introspecting the result of performSelectorXXX. 13994 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13995 // Special case messages to -performSelector and friends, which 13996 // can return non-pointer values boxed in a pointer value. 13997 // Some clients may wish to silence warnings in this subcase. 13998 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13999 Selector S = ME->getSelector(); 14000 StringRef SelArg0 = S.getNameForSlot(0); 14001 if (SelArg0.startswith("performSelector")) 14002 Diag = diag::warn_objc_pointer_masking_performSelector; 14003 } 14004 14005 S.Diag(OpLoc, Diag) 14006 << ObjCPointerExpr->getSourceRange(); 14007 } 14008 } 14009 14010 static NamedDecl *getDeclFromExpr(Expr *E) { 14011 if (!E) 14012 return nullptr; 14013 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 14014 return DRE->getDecl(); 14015 if (auto *ME = dyn_cast<MemberExpr>(E)) 14016 return ME->getMemberDecl(); 14017 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 14018 return IRE->getDecl(); 14019 return nullptr; 14020 } 14021 14022 // This helper function promotes a binary operator's operands (which are of a 14023 // half vector type) to a vector of floats and then truncates the result to 14024 // a vector of either half or short. 14025 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 14026 BinaryOperatorKind Opc, QualType ResultTy, 14027 ExprValueKind VK, ExprObjectKind OK, 14028 bool IsCompAssign, SourceLocation OpLoc, 14029 FPOptionsOverride FPFeatures) { 14030 auto &Context = S.getASTContext(); 14031 assert((isVector(ResultTy, Context.HalfTy) || 14032 isVector(ResultTy, Context.ShortTy)) && 14033 "Result must be a vector of half or short"); 14034 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 14035 isVector(RHS.get()->getType(), Context.HalfTy) && 14036 "both operands expected to be a half vector"); 14037 14038 RHS = convertVector(RHS.get(), Context.FloatTy, S); 14039 QualType BinOpResTy = RHS.get()->getType(); 14040 14041 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 14042 // change BinOpResTy to a vector of ints. 14043 if (isVector(ResultTy, Context.ShortTy)) 14044 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 14045 14046 if (IsCompAssign) 14047 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14048 ResultTy, VK, OK, OpLoc, FPFeatures, 14049 BinOpResTy, BinOpResTy); 14050 14051 LHS = convertVector(LHS.get(), Context.FloatTy, S); 14052 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14053 BinOpResTy, VK, OK, OpLoc, FPFeatures); 14054 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 14055 } 14056 14057 static std::pair<ExprResult, ExprResult> 14058 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 14059 Expr *RHSExpr) { 14060 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14061 if (!S.Context.isDependenceAllowed()) { 14062 // C cannot handle TypoExpr nodes on either side of a binop because it 14063 // doesn't handle dependent types properly, so make sure any TypoExprs have 14064 // been dealt with before checking the operands. 14065 LHS = S.CorrectDelayedTyposInExpr(LHS); 14066 RHS = S.CorrectDelayedTyposInExpr( 14067 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 14068 [Opc, LHS](Expr *E) { 14069 if (Opc != BO_Assign) 14070 return ExprResult(E); 14071 // Avoid correcting the RHS to the same Expr as the LHS. 14072 Decl *D = getDeclFromExpr(E); 14073 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 14074 }); 14075 } 14076 return std::make_pair(LHS, RHS); 14077 } 14078 14079 /// Returns true if conversion between vectors of halfs and vectors of floats 14080 /// is needed. 14081 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 14082 Expr *E0, Expr *E1 = nullptr) { 14083 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 14084 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 14085 return false; 14086 14087 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 14088 QualType Ty = E->IgnoreImplicit()->getType(); 14089 14090 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 14091 // to vectors of floats. Although the element type of the vectors is __fp16, 14092 // the vectors shouldn't be treated as storage-only types. See the 14093 // discussion here: https://reviews.llvm.org/rG825235c140e7 14094 if (const VectorType *VT = Ty->getAs<VectorType>()) { 14095 if (VT->getVectorKind() == VectorType::NeonVector) 14096 return false; 14097 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 14098 } 14099 return false; 14100 }; 14101 14102 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 14103 } 14104 14105 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 14106 /// operator @p Opc at location @c TokLoc. This routine only supports 14107 /// built-in operations; ActOnBinOp handles overloaded operators. 14108 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 14109 BinaryOperatorKind Opc, 14110 Expr *LHSExpr, Expr *RHSExpr) { 14111 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 14112 // The syntax only allows initializer lists on the RHS of assignment, 14113 // so we don't need to worry about accepting invalid code for 14114 // non-assignment operators. 14115 // C++11 5.17p9: 14116 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 14117 // of x = {} is x = T(). 14118 InitializationKind Kind = InitializationKind::CreateDirectList( 14119 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14120 InitializedEntity Entity = 14121 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 14122 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 14123 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 14124 if (Init.isInvalid()) 14125 return Init; 14126 RHSExpr = Init.get(); 14127 } 14128 14129 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14130 QualType ResultTy; // Result type of the binary operator. 14131 // The following two variables are used for compound assignment operators 14132 QualType CompLHSTy; // Type of LHS after promotions for computation 14133 QualType CompResultTy; // Type of computation result 14134 ExprValueKind VK = VK_PRValue; 14135 ExprObjectKind OK = OK_Ordinary; 14136 bool ConvertHalfVec = false; 14137 14138 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14139 if (!LHS.isUsable() || !RHS.isUsable()) 14140 return ExprError(); 14141 14142 if (getLangOpts().OpenCL) { 14143 QualType LHSTy = LHSExpr->getType(); 14144 QualType RHSTy = RHSExpr->getType(); 14145 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14146 // the ATOMIC_VAR_INIT macro. 14147 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14148 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14149 if (BO_Assign == Opc) 14150 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14151 else 14152 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14153 return ExprError(); 14154 } 14155 14156 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14157 // only with a builtin functions and therefore should be disallowed here. 14158 if (LHSTy->isImageType() || RHSTy->isImageType() || 14159 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14160 LHSTy->isPipeType() || RHSTy->isPipeType() || 14161 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14162 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14163 return ExprError(); 14164 } 14165 } 14166 14167 switch (Opc) { 14168 case BO_Assign: 14169 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14170 if (getLangOpts().CPlusPlus && 14171 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14172 VK = LHS.get()->getValueKind(); 14173 OK = LHS.get()->getObjectKind(); 14174 } 14175 if (!ResultTy.isNull()) { 14176 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14177 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14178 14179 // Avoid copying a block to the heap if the block is assigned to a local 14180 // auto variable that is declared in the same scope as the block. This 14181 // optimization is unsafe if the local variable is declared in an outer 14182 // scope. For example: 14183 // 14184 // BlockTy b; 14185 // { 14186 // b = ^{...}; 14187 // } 14188 // // It is unsafe to invoke the block here if it wasn't copied to the 14189 // // heap. 14190 // b(); 14191 14192 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14193 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14194 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14195 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14196 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14197 14198 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14199 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14200 NTCUC_Assignment, NTCUK_Copy); 14201 } 14202 RecordModifiableNonNullParam(*this, LHS.get()); 14203 break; 14204 case BO_PtrMemD: 14205 case BO_PtrMemI: 14206 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14207 Opc == BO_PtrMemI); 14208 break; 14209 case BO_Mul: 14210 case BO_Div: 14211 ConvertHalfVec = true; 14212 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14213 Opc == BO_Div); 14214 break; 14215 case BO_Rem: 14216 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14217 break; 14218 case BO_Add: 14219 ConvertHalfVec = true; 14220 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14221 break; 14222 case BO_Sub: 14223 ConvertHalfVec = true; 14224 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14225 break; 14226 case BO_Shl: 14227 case BO_Shr: 14228 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14229 break; 14230 case BO_LE: 14231 case BO_LT: 14232 case BO_GE: 14233 case BO_GT: 14234 ConvertHalfVec = true; 14235 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14236 break; 14237 case BO_EQ: 14238 case BO_NE: 14239 ConvertHalfVec = true; 14240 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14241 break; 14242 case BO_Cmp: 14243 ConvertHalfVec = true; 14244 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14245 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14246 break; 14247 case BO_And: 14248 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14249 LLVM_FALLTHROUGH; 14250 case BO_Xor: 14251 case BO_Or: 14252 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14253 break; 14254 case BO_LAnd: 14255 case BO_LOr: 14256 ConvertHalfVec = true; 14257 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14258 break; 14259 case BO_MulAssign: 14260 case BO_DivAssign: 14261 ConvertHalfVec = true; 14262 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14263 Opc == BO_DivAssign); 14264 CompLHSTy = CompResultTy; 14265 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14266 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14267 break; 14268 case BO_RemAssign: 14269 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14270 CompLHSTy = CompResultTy; 14271 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14272 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14273 break; 14274 case BO_AddAssign: 14275 ConvertHalfVec = true; 14276 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14277 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14278 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14279 break; 14280 case BO_SubAssign: 14281 ConvertHalfVec = true; 14282 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14283 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14284 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14285 break; 14286 case BO_ShlAssign: 14287 case BO_ShrAssign: 14288 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14289 CompLHSTy = CompResultTy; 14290 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14291 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14292 break; 14293 case BO_AndAssign: 14294 case BO_OrAssign: // fallthrough 14295 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14296 LLVM_FALLTHROUGH; 14297 case BO_XorAssign: 14298 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14299 CompLHSTy = CompResultTy; 14300 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14301 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14302 break; 14303 case BO_Comma: 14304 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14305 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14306 VK = RHS.get()->getValueKind(); 14307 OK = RHS.get()->getObjectKind(); 14308 } 14309 break; 14310 } 14311 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14312 return ExprError(); 14313 14314 // Some of the binary operations require promoting operands of half vector to 14315 // float vectors and truncating the result back to half vector. For now, we do 14316 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14317 // arm64). 14318 assert( 14319 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14320 isVector(LHS.get()->getType(), Context.HalfTy)) && 14321 "both sides are half vectors or neither sides are"); 14322 ConvertHalfVec = 14323 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14324 14325 // Check for array bounds violations for both sides of the BinaryOperator 14326 CheckArrayAccess(LHS.get()); 14327 CheckArrayAccess(RHS.get()); 14328 14329 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14330 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14331 &Context.Idents.get("object_setClass"), 14332 SourceLocation(), LookupOrdinaryName); 14333 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14334 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14335 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14336 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14337 "object_setClass(") 14338 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14339 ",") 14340 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14341 } 14342 else 14343 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14344 } 14345 else if (const ObjCIvarRefExpr *OIRE = 14346 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14347 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14348 14349 // Opc is not a compound assignment if CompResultTy is null. 14350 if (CompResultTy.isNull()) { 14351 if (ConvertHalfVec) 14352 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14353 OpLoc, CurFPFeatureOverrides()); 14354 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14355 VK, OK, OpLoc, CurFPFeatureOverrides()); 14356 } 14357 14358 // Handle compound assignments. 14359 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14360 OK_ObjCProperty) { 14361 VK = VK_LValue; 14362 OK = LHS.get()->getObjectKind(); 14363 } 14364 14365 // The LHS is not converted to the result type for fixed-point compound 14366 // assignment as the common type is computed on demand. Reset the CompLHSTy 14367 // to the LHS type we would have gotten after unary conversions. 14368 if (CompResultTy->isFixedPointType()) 14369 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14370 14371 if (ConvertHalfVec) 14372 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14373 OpLoc, CurFPFeatureOverrides()); 14374 14375 return CompoundAssignOperator::Create( 14376 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14377 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14378 } 14379 14380 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14381 /// operators are mixed in a way that suggests that the programmer forgot that 14382 /// comparison operators have higher precedence. The most typical example of 14383 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14384 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14385 SourceLocation OpLoc, Expr *LHSExpr, 14386 Expr *RHSExpr) { 14387 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14388 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14389 14390 // Check that one of the sides is a comparison operator and the other isn't. 14391 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14392 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14393 if (isLeftComp == isRightComp) 14394 return; 14395 14396 // Bitwise operations are sometimes used as eager logical ops. 14397 // Don't diagnose this. 14398 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14399 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14400 if (isLeftBitwise || isRightBitwise) 14401 return; 14402 14403 SourceRange DiagRange = isLeftComp 14404 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14405 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14406 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14407 SourceRange ParensRange = 14408 isLeftComp 14409 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14410 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14411 14412 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14413 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14414 SuggestParentheses(Self, OpLoc, 14415 Self.PDiag(diag::note_precedence_silence) << OpStr, 14416 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14417 SuggestParentheses(Self, OpLoc, 14418 Self.PDiag(diag::note_precedence_bitwise_first) 14419 << BinaryOperator::getOpcodeStr(Opc), 14420 ParensRange); 14421 } 14422 14423 /// It accepts a '&&' expr that is inside a '||' one. 14424 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14425 /// in parentheses. 14426 static void 14427 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14428 BinaryOperator *Bop) { 14429 assert(Bop->getOpcode() == BO_LAnd); 14430 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14431 << Bop->getSourceRange() << OpLoc; 14432 SuggestParentheses(Self, Bop->getOperatorLoc(), 14433 Self.PDiag(diag::note_precedence_silence) 14434 << Bop->getOpcodeStr(), 14435 Bop->getSourceRange()); 14436 } 14437 14438 /// Returns true if the given expression can be evaluated as a constant 14439 /// 'true'. 14440 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14441 bool Res; 14442 return !E->isValueDependent() && 14443 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14444 } 14445 14446 /// Returns true if the given expression can be evaluated as a constant 14447 /// 'false'. 14448 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14449 bool Res; 14450 return !E->isValueDependent() && 14451 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14452 } 14453 14454 /// Look for '&&' in the left hand of a '||' expr. 14455 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14456 Expr *LHSExpr, Expr *RHSExpr) { 14457 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14458 if (Bop->getOpcode() == BO_LAnd) { 14459 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14460 if (EvaluatesAsFalse(S, RHSExpr)) 14461 return; 14462 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14463 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14464 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14465 } else if (Bop->getOpcode() == BO_LOr) { 14466 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14467 // If it's "a || b && 1 || c" we didn't warn earlier for 14468 // "a || b && 1", but warn now. 14469 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14470 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14471 } 14472 } 14473 } 14474 } 14475 14476 /// Look for '&&' in the right hand of a '||' expr. 14477 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14478 Expr *LHSExpr, Expr *RHSExpr) { 14479 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14480 if (Bop->getOpcode() == BO_LAnd) { 14481 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14482 if (EvaluatesAsFalse(S, LHSExpr)) 14483 return; 14484 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14485 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14486 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14487 } 14488 } 14489 } 14490 14491 /// Look for bitwise op in the left or right hand of a bitwise op with 14492 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14493 /// the '&' expression in parentheses. 14494 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14495 SourceLocation OpLoc, Expr *SubExpr) { 14496 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14497 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14498 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14499 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14500 << Bop->getSourceRange() << OpLoc; 14501 SuggestParentheses(S, Bop->getOperatorLoc(), 14502 S.PDiag(diag::note_precedence_silence) 14503 << Bop->getOpcodeStr(), 14504 Bop->getSourceRange()); 14505 } 14506 } 14507 } 14508 14509 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14510 Expr *SubExpr, StringRef Shift) { 14511 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14512 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14513 StringRef Op = Bop->getOpcodeStr(); 14514 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14515 << Bop->getSourceRange() << OpLoc << Shift << Op; 14516 SuggestParentheses(S, Bop->getOperatorLoc(), 14517 S.PDiag(diag::note_precedence_silence) << Op, 14518 Bop->getSourceRange()); 14519 } 14520 } 14521 } 14522 14523 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14524 Expr *LHSExpr, Expr *RHSExpr) { 14525 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14526 if (!OCE) 14527 return; 14528 14529 FunctionDecl *FD = OCE->getDirectCallee(); 14530 if (!FD || !FD->isOverloadedOperator()) 14531 return; 14532 14533 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14534 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14535 return; 14536 14537 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14538 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14539 << (Kind == OO_LessLess); 14540 SuggestParentheses(S, OCE->getOperatorLoc(), 14541 S.PDiag(diag::note_precedence_silence) 14542 << (Kind == OO_LessLess ? "<<" : ">>"), 14543 OCE->getSourceRange()); 14544 SuggestParentheses( 14545 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14546 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14547 } 14548 14549 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14550 /// precedence. 14551 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14552 SourceLocation OpLoc, Expr *LHSExpr, 14553 Expr *RHSExpr){ 14554 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14555 if (BinaryOperator::isBitwiseOp(Opc)) 14556 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14557 14558 // Diagnose "arg1 & arg2 | arg3" 14559 if ((Opc == BO_Or || Opc == BO_Xor) && 14560 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14561 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14562 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14563 } 14564 14565 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14566 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14567 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14568 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14569 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14570 } 14571 14572 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14573 || Opc == BO_Shr) { 14574 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14575 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14576 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14577 } 14578 14579 // Warn on overloaded shift operators and comparisons, such as: 14580 // cout << 5 == 4; 14581 if (BinaryOperator::isComparisonOp(Opc)) 14582 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14583 } 14584 14585 // Binary Operators. 'Tok' is the token for the operator. 14586 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14587 tok::TokenKind Kind, 14588 Expr *LHSExpr, Expr *RHSExpr) { 14589 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14590 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14591 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14592 14593 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14594 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14595 14596 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14597 } 14598 14599 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14600 UnresolvedSetImpl &Functions) { 14601 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14602 if (OverOp != OO_None && OverOp != OO_Equal) 14603 LookupOverloadedOperatorName(OverOp, S, Functions); 14604 14605 // In C++20 onwards, we may have a second operator to look up. 14606 if (getLangOpts().CPlusPlus20) { 14607 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14608 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14609 } 14610 } 14611 14612 /// Build an overloaded binary operator expression in the given scope. 14613 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14614 BinaryOperatorKind Opc, 14615 Expr *LHS, Expr *RHS) { 14616 switch (Opc) { 14617 case BO_Assign: 14618 case BO_DivAssign: 14619 case BO_RemAssign: 14620 case BO_SubAssign: 14621 case BO_AndAssign: 14622 case BO_OrAssign: 14623 case BO_XorAssign: 14624 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14625 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14626 break; 14627 default: 14628 break; 14629 } 14630 14631 // Find all of the overloaded operators visible from this point. 14632 UnresolvedSet<16> Functions; 14633 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14634 14635 // Build the (potentially-overloaded, potentially-dependent) 14636 // binary operation. 14637 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14638 } 14639 14640 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14641 BinaryOperatorKind Opc, 14642 Expr *LHSExpr, Expr *RHSExpr) { 14643 ExprResult LHS, RHS; 14644 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14645 if (!LHS.isUsable() || !RHS.isUsable()) 14646 return ExprError(); 14647 LHSExpr = LHS.get(); 14648 RHSExpr = RHS.get(); 14649 14650 // We want to end up calling one of checkPseudoObjectAssignment 14651 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14652 // both expressions are overloadable or either is type-dependent), 14653 // or CreateBuiltinBinOp (in any other case). We also want to get 14654 // any placeholder types out of the way. 14655 14656 // Handle pseudo-objects in the LHS. 14657 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14658 // Assignments with a pseudo-object l-value need special analysis. 14659 if (pty->getKind() == BuiltinType::PseudoObject && 14660 BinaryOperator::isAssignmentOp(Opc)) 14661 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14662 14663 // Don't resolve overloads if the other type is overloadable. 14664 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14665 // We can't actually test that if we still have a placeholder, 14666 // though. Fortunately, none of the exceptions we see in that 14667 // code below are valid when the LHS is an overload set. Note 14668 // that an overload set can be dependently-typed, but it never 14669 // instantiates to having an overloadable type. 14670 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14671 if (resolvedRHS.isInvalid()) return ExprError(); 14672 RHSExpr = resolvedRHS.get(); 14673 14674 if (RHSExpr->isTypeDependent() || 14675 RHSExpr->getType()->isOverloadableType()) 14676 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14677 } 14678 14679 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14680 // template, diagnose the missing 'template' keyword instead of diagnosing 14681 // an invalid use of a bound member function. 14682 // 14683 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14684 // to C++1z [over.over]/1.4, but we already checked for that case above. 14685 if (Opc == BO_LT && inTemplateInstantiation() && 14686 (pty->getKind() == BuiltinType::BoundMember || 14687 pty->getKind() == BuiltinType::Overload)) { 14688 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14689 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14690 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14691 return isa<FunctionTemplateDecl>(ND); 14692 })) { 14693 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14694 : OE->getNameLoc(), 14695 diag::err_template_kw_missing) 14696 << OE->getName().getAsString() << ""; 14697 return ExprError(); 14698 } 14699 } 14700 14701 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14702 if (LHS.isInvalid()) return ExprError(); 14703 LHSExpr = LHS.get(); 14704 } 14705 14706 // Handle pseudo-objects in the RHS. 14707 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14708 // An overload in the RHS can potentially be resolved by the type 14709 // being assigned to. 14710 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14711 if (getLangOpts().CPlusPlus && 14712 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14713 LHSExpr->getType()->isOverloadableType())) 14714 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14715 14716 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14717 } 14718 14719 // Don't resolve overloads if the other type is overloadable. 14720 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14721 LHSExpr->getType()->isOverloadableType()) 14722 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14723 14724 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14725 if (!resolvedRHS.isUsable()) return ExprError(); 14726 RHSExpr = resolvedRHS.get(); 14727 } 14728 14729 if (getLangOpts().CPlusPlus) { 14730 // If either expression is type-dependent, always build an 14731 // overloaded op. 14732 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14733 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14734 14735 // Otherwise, build an overloaded op if either expression has an 14736 // overloadable type. 14737 if (LHSExpr->getType()->isOverloadableType() || 14738 RHSExpr->getType()->isOverloadableType()) 14739 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14740 } 14741 14742 if (getLangOpts().RecoveryAST && 14743 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14744 assert(!getLangOpts().CPlusPlus); 14745 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14746 "Should only occur in error-recovery path."); 14747 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14748 // C [6.15.16] p3: 14749 // An assignment expression has the value of the left operand after the 14750 // assignment, but is not an lvalue. 14751 return CompoundAssignOperator::Create( 14752 Context, LHSExpr, RHSExpr, Opc, 14753 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 14754 OpLoc, CurFPFeatureOverrides()); 14755 QualType ResultType; 14756 switch (Opc) { 14757 case BO_Assign: 14758 ResultType = LHSExpr->getType().getUnqualifiedType(); 14759 break; 14760 case BO_LT: 14761 case BO_GT: 14762 case BO_LE: 14763 case BO_GE: 14764 case BO_EQ: 14765 case BO_NE: 14766 case BO_LAnd: 14767 case BO_LOr: 14768 // These operators have a fixed result type regardless of operands. 14769 ResultType = Context.IntTy; 14770 break; 14771 case BO_Comma: 14772 ResultType = RHSExpr->getType(); 14773 break; 14774 default: 14775 ResultType = Context.DependentTy; 14776 break; 14777 } 14778 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14779 VK_PRValue, OK_Ordinary, OpLoc, 14780 CurFPFeatureOverrides()); 14781 } 14782 14783 // Build a built-in binary operation. 14784 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14785 } 14786 14787 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14788 if (T.isNull() || T->isDependentType()) 14789 return false; 14790 14791 if (!T->isPromotableIntegerType()) 14792 return true; 14793 14794 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14795 } 14796 14797 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14798 UnaryOperatorKind Opc, 14799 Expr *InputExpr) { 14800 ExprResult Input = InputExpr; 14801 ExprValueKind VK = VK_PRValue; 14802 ExprObjectKind OK = OK_Ordinary; 14803 QualType resultType; 14804 bool CanOverflow = false; 14805 14806 bool ConvertHalfVec = false; 14807 if (getLangOpts().OpenCL) { 14808 QualType Ty = InputExpr->getType(); 14809 // The only legal unary operation for atomics is '&'. 14810 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14811 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14812 // only with a builtin functions and therefore should be disallowed here. 14813 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14814 || Ty->isBlockPointerType())) { 14815 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14816 << InputExpr->getType() 14817 << Input.get()->getSourceRange()); 14818 } 14819 } 14820 14821 switch (Opc) { 14822 case UO_PreInc: 14823 case UO_PreDec: 14824 case UO_PostInc: 14825 case UO_PostDec: 14826 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14827 OpLoc, 14828 Opc == UO_PreInc || 14829 Opc == UO_PostInc, 14830 Opc == UO_PreInc || 14831 Opc == UO_PreDec); 14832 CanOverflow = isOverflowingIntegerType(Context, resultType); 14833 break; 14834 case UO_AddrOf: 14835 resultType = CheckAddressOfOperand(Input, OpLoc); 14836 CheckAddressOfNoDeref(InputExpr); 14837 RecordModifiableNonNullParam(*this, InputExpr); 14838 break; 14839 case UO_Deref: { 14840 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14841 if (Input.isInvalid()) return ExprError(); 14842 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14843 break; 14844 } 14845 case UO_Plus: 14846 case UO_Minus: 14847 CanOverflow = Opc == UO_Minus && 14848 isOverflowingIntegerType(Context, Input.get()->getType()); 14849 Input = UsualUnaryConversions(Input.get()); 14850 if (Input.isInvalid()) return ExprError(); 14851 // Unary plus and minus require promoting an operand of half vector to a 14852 // float vector and truncating the result back to a half vector. For now, we 14853 // do this only when HalfArgsAndReturns is set (that is, when the target is 14854 // arm or arm64). 14855 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14856 14857 // If the operand is a half vector, promote it to a float vector. 14858 if (ConvertHalfVec) 14859 Input = convertVector(Input.get(), Context.FloatTy, *this); 14860 resultType = Input.get()->getType(); 14861 if (resultType->isDependentType()) 14862 break; 14863 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14864 break; 14865 else if (resultType->isVectorType() && 14866 // The z vector extensions don't allow + or - with bool vectors. 14867 (!Context.getLangOpts().ZVector || 14868 resultType->castAs<VectorType>()->getVectorKind() != 14869 VectorType::AltiVecBool)) 14870 break; 14871 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14872 Opc == UO_Plus && 14873 resultType->isPointerType()) 14874 break; 14875 14876 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14877 << resultType << Input.get()->getSourceRange()); 14878 14879 case UO_Not: // bitwise complement 14880 Input = UsualUnaryConversions(Input.get()); 14881 if (Input.isInvalid()) 14882 return ExprError(); 14883 resultType = Input.get()->getType(); 14884 if (resultType->isDependentType()) 14885 break; 14886 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14887 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14888 // C99 does not support '~' for complex conjugation. 14889 Diag(OpLoc, diag::ext_integer_complement_complex) 14890 << resultType << Input.get()->getSourceRange(); 14891 else if (resultType->hasIntegerRepresentation()) 14892 break; 14893 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14894 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14895 // on vector float types. 14896 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14897 if (!T->isIntegerType()) 14898 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14899 << resultType << Input.get()->getSourceRange()); 14900 } else { 14901 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14902 << resultType << Input.get()->getSourceRange()); 14903 } 14904 break; 14905 14906 case UO_LNot: // logical negation 14907 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14908 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14909 if (Input.isInvalid()) return ExprError(); 14910 resultType = Input.get()->getType(); 14911 14912 // Though we still have to promote half FP to float... 14913 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14914 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14915 resultType = Context.FloatTy; 14916 } 14917 14918 if (resultType->isDependentType()) 14919 break; 14920 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14921 // C99 6.5.3.3p1: ok, fallthrough; 14922 if (Context.getLangOpts().CPlusPlus) { 14923 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14924 // operand contextually converted to bool. 14925 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14926 ScalarTypeToBooleanCastKind(resultType)); 14927 } else if (Context.getLangOpts().OpenCL && 14928 Context.getLangOpts().OpenCLVersion < 120) { 14929 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14930 // operate on scalar float types. 14931 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14932 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14933 << resultType << Input.get()->getSourceRange()); 14934 } 14935 } else if (resultType->isExtVectorType()) { 14936 if (Context.getLangOpts().OpenCL && 14937 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { 14938 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14939 // operate on vector float types. 14940 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14941 if (!T->isIntegerType()) 14942 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14943 << resultType << Input.get()->getSourceRange()); 14944 } 14945 // Vector logical not returns the signed variant of the operand type. 14946 resultType = GetSignedVectorType(resultType); 14947 break; 14948 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14949 const VectorType *VTy = resultType->castAs<VectorType>(); 14950 if (VTy->getVectorKind() != VectorType::GenericVector) 14951 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14952 << resultType << Input.get()->getSourceRange()); 14953 14954 // Vector logical not returns the signed variant of the operand type. 14955 resultType = GetSignedVectorType(resultType); 14956 break; 14957 } else { 14958 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14959 << resultType << Input.get()->getSourceRange()); 14960 } 14961 14962 // LNot always has type int. C99 6.5.3.3p5. 14963 // In C++, it's bool. C++ 5.3.1p8 14964 resultType = Context.getLogicalOperationType(); 14965 break; 14966 case UO_Real: 14967 case UO_Imag: 14968 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14969 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14970 // complex l-values to ordinary l-values and all other values to r-values. 14971 if (Input.isInvalid()) return ExprError(); 14972 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14973 if (Input.get()->isGLValue() && 14974 Input.get()->getObjectKind() == OK_Ordinary) 14975 VK = Input.get()->getValueKind(); 14976 } else if (!getLangOpts().CPlusPlus) { 14977 // In C, a volatile scalar is read by __imag. In C++, it is not. 14978 Input = DefaultLvalueConversion(Input.get()); 14979 } 14980 break; 14981 case UO_Extension: 14982 resultType = Input.get()->getType(); 14983 VK = Input.get()->getValueKind(); 14984 OK = Input.get()->getObjectKind(); 14985 break; 14986 case UO_Coawait: 14987 // It's unnecessary to represent the pass-through operator co_await in the 14988 // AST; just return the input expression instead. 14989 assert(!Input.get()->getType()->isDependentType() && 14990 "the co_await expression must be non-dependant before " 14991 "building operator co_await"); 14992 return Input; 14993 } 14994 if (resultType.isNull() || Input.isInvalid()) 14995 return ExprError(); 14996 14997 // Check for array bounds violations in the operand of the UnaryOperator, 14998 // except for the '*' and '&' operators that have to be handled specially 14999 // by CheckArrayAccess (as there are special cases like &array[arraysize] 15000 // that are explicitly defined as valid by the standard). 15001 if (Opc != UO_AddrOf && Opc != UO_Deref) 15002 CheckArrayAccess(Input.get()); 15003 15004 auto *UO = 15005 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 15006 OpLoc, CanOverflow, CurFPFeatureOverrides()); 15007 15008 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 15009 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 15010 !isUnevaluatedContext()) 15011 ExprEvalContexts.back().PossibleDerefs.insert(UO); 15012 15013 // Convert the result back to a half vector. 15014 if (ConvertHalfVec) 15015 return convertVector(UO, Context.HalfTy, *this); 15016 return UO; 15017 } 15018 15019 /// Determine whether the given expression is a qualified member 15020 /// access expression, of a form that could be turned into a pointer to member 15021 /// with the address-of operator. 15022 bool Sema::isQualifiedMemberAccess(Expr *E) { 15023 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15024 if (!DRE->getQualifier()) 15025 return false; 15026 15027 ValueDecl *VD = DRE->getDecl(); 15028 if (!VD->isCXXClassMember()) 15029 return false; 15030 15031 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 15032 return true; 15033 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 15034 return Method->isInstance(); 15035 15036 return false; 15037 } 15038 15039 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15040 if (!ULE->getQualifier()) 15041 return false; 15042 15043 for (NamedDecl *D : ULE->decls()) { 15044 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 15045 if (Method->isInstance()) 15046 return true; 15047 } else { 15048 // Overload set does not contain methods. 15049 break; 15050 } 15051 } 15052 15053 return false; 15054 } 15055 15056 return false; 15057 } 15058 15059 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 15060 UnaryOperatorKind Opc, Expr *Input) { 15061 // First things first: handle placeholders so that the 15062 // overloaded-operator check considers the right type. 15063 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 15064 // Increment and decrement of pseudo-object references. 15065 if (pty->getKind() == BuiltinType::PseudoObject && 15066 UnaryOperator::isIncrementDecrementOp(Opc)) 15067 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 15068 15069 // extension is always a builtin operator. 15070 if (Opc == UO_Extension) 15071 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15072 15073 // & gets special logic for several kinds of placeholder. 15074 // The builtin code knows what to do. 15075 if (Opc == UO_AddrOf && 15076 (pty->getKind() == BuiltinType::Overload || 15077 pty->getKind() == BuiltinType::UnknownAny || 15078 pty->getKind() == BuiltinType::BoundMember)) 15079 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15080 15081 // Anything else needs to be handled now. 15082 ExprResult Result = CheckPlaceholderExpr(Input); 15083 if (Result.isInvalid()) return ExprError(); 15084 Input = Result.get(); 15085 } 15086 15087 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 15088 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 15089 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 15090 // Find all of the overloaded operators visible from this point. 15091 UnresolvedSet<16> Functions; 15092 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 15093 if (S && OverOp != OO_None) 15094 LookupOverloadedOperatorName(OverOp, S, Functions); 15095 15096 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 15097 } 15098 15099 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15100 } 15101 15102 // Unary Operators. 'Tok' is the token for the operator. 15103 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 15104 tok::TokenKind Op, Expr *Input) { 15105 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 15106 } 15107 15108 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 15109 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 15110 LabelDecl *TheDecl) { 15111 TheDecl->markUsed(Context); 15112 // Create the AST node. The address of a label always has type 'void*'. 15113 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 15114 Context.getPointerType(Context.VoidTy)); 15115 } 15116 15117 void Sema::ActOnStartStmtExpr() { 15118 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15119 } 15120 15121 void Sema::ActOnStmtExprError() { 15122 // Note that function is also called by TreeTransform when leaving a 15123 // StmtExpr scope without rebuilding anything. 15124 15125 DiscardCleanupsInEvaluationContext(); 15126 PopExpressionEvaluationContext(); 15127 } 15128 15129 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15130 SourceLocation RPLoc) { 15131 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15132 } 15133 15134 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15135 SourceLocation RPLoc, unsigned TemplateDepth) { 15136 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15137 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15138 15139 if (hasAnyUnrecoverableErrorsInThisFunction()) 15140 DiscardCleanupsInEvaluationContext(); 15141 assert(!Cleanup.exprNeedsCleanups() && 15142 "cleanups within StmtExpr not correctly bound!"); 15143 PopExpressionEvaluationContext(); 15144 15145 // FIXME: there are a variety of strange constraints to enforce here, for 15146 // example, it is not possible to goto into a stmt expression apparently. 15147 // More semantic analysis is needed. 15148 15149 // If there are sub-stmts in the compound stmt, take the type of the last one 15150 // as the type of the stmtexpr. 15151 QualType Ty = Context.VoidTy; 15152 bool StmtExprMayBindToTemp = false; 15153 if (!Compound->body_empty()) { 15154 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15155 if (const auto *LastStmt = 15156 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15157 if (const Expr *Value = LastStmt->getExprStmt()) { 15158 StmtExprMayBindToTemp = true; 15159 Ty = Value->getType(); 15160 } 15161 } 15162 } 15163 15164 // FIXME: Check that expression type is complete/non-abstract; statement 15165 // expressions are not lvalues. 15166 Expr *ResStmtExpr = 15167 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15168 if (StmtExprMayBindToTemp) 15169 return MaybeBindToTemporary(ResStmtExpr); 15170 return ResStmtExpr; 15171 } 15172 15173 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15174 if (ER.isInvalid()) 15175 return ExprError(); 15176 15177 // Do function/array conversion on the last expression, but not 15178 // lvalue-to-rvalue. However, initialize an unqualified type. 15179 ER = DefaultFunctionArrayConversion(ER.get()); 15180 if (ER.isInvalid()) 15181 return ExprError(); 15182 Expr *E = ER.get(); 15183 15184 if (E->isTypeDependent()) 15185 return E; 15186 15187 // In ARC, if the final expression ends in a consume, splice 15188 // the consume out and bind it later. In the alternate case 15189 // (when dealing with a retainable type), the result 15190 // initialization will create a produce. In both cases the 15191 // result will be +1, and we'll need to balance that out with 15192 // a bind. 15193 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15194 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15195 return Cast->getSubExpr(); 15196 15197 // FIXME: Provide a better location for the initialization. 15198 return PerformCopyInitialization( 15199 InitializedEntity::InitializeStmtExprResult( 15200 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15201 SourceLocation(), E); 15202 } 15203 15204 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15205 TypeSourceInfo *TInfo, 15206 ArrayRef<OffsetOfComponent> Components, 15207 SourceLocation RParenLoc) { 15208 QualType ArgTy = TInfo->getType(); 15209 bool Dependent = ArgTy->isDependentType(); 15210 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15211 15212 // We must have at least one component that refers to the type, and the first 15213 // one is known to be a field designator. Verify that the ArgTy represents 15214 // a struct/union/class. 15215 if (!Dependent && !ArgTy->isRecordType()) 15216 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15217 << ArgTy << TypeRange); 15218 15219 // Type must be complete per C99 7.17p3 because a declaring a variable 15220 // with an incomplete type would be ill-formed. 15221 if (!Dependent 15222 && RequireCompleteType(BuiltinLoc, ArgTy, 15223 diag::err_offsetof_incomplete_type, TypeRange)) 15224 return ExprError(); 15225 15226 bool DidWarnAboutNonPOD = false; 15227 QualType CurrentType = ArgTy; 15228 SmallVector<OffsetOfNode, 4> Comps; 15229 SmallVector<Expr*, 4> Exprs; 15230 for (const OffsetOfComponent &OC : Components) { 15231 if (OC.isBrackets) { 15232 // Offset of an array sub-field. TODO: Should we allow vector elements? 15233 if (!CurrentType->isDependentType()) { 15234 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15235 if(!AT) 15236 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15237 << CurrentType); 15238 CurrentType = AT->getElementType(); 15239 } else 15240 CurrentType = Context.DependentTy; 15241 15242 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15243 if (IdxRval.isInvalid()) 15244 return ExprError(); 15245 Expr *Idx = IdxRval.get(); 15246 15247 // The expression must be an integral expression. 15248 // FIXME: An integral constant expression? 15249 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15250 !Idx->getType()->isIntegerType()) 15251 return ExprError( 15252 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15253 << Idx->getSourceRange()); 15254 15255 // Record this array index. 15256 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15257 Exprs.push_back(Idx); 15258 continue; 15259 } 15260 15261 // Offset of a field. 15262 if (CurrentType->isDependentType()) { 15263 // We have the offset of a field, but we can't look into the dependent 15264 // type. Just record the identifier of the field. 15265 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15266 CurrentType = Context.DependentTy; 15267 continue; 15268 } 15269 15270 // We need to have a complete type to look into. 15271 if (RequireCompleteType(OC.LocStart, CurrentType, 15272 diag::err_offsetof_incomplete_type)) 15273 return ExprError(); 15274 15275 // Look for the designated field. 15276 const RecordType *RC = CurrentType->getAs<RecordType>(); 15277 if (!RC) 15278 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15279 << CurrentType); 15280 RecordDecl *RD = RC->getDecl(); 15281 15282 // C++ [lib.support.types]p5: 15283 // The macro offsetof accepts a restricted set of type arguments in this 15284 // International Standard. type shall be a POD structure or a POD union 15285 // (clause 9). 15286 // C++11 [support.types]p4: 15287 // If type is not a standard-layout class (Clause 9), the results are 15288 // undefined. 15289 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15290 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15291 unsigned DiagID = 15292 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15293 : diag::ext_offsetof_non_pod_type; 15294 15295 if (!IsSafe && !DidWarnAboutNonPOD && 15296 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15297 PDiag(DiagID) 15298 << SourceRange(Components[0].LocStart, OC.LocEnd) 15299 << CurrentType)) 15300 DidWarnAboutNonPOD = true; 15301 } 15302 15303 // Look for the field. 15304 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15305 LookupQualifiedName(R, RD); 15306 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15307 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15308 if (!MemberDecl) { 15309 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15310 MemberDecl = IndirectMemberDecl->getAnonField(); 15311 } 15312 15313 if (!MemberDecl) 15314 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15315 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15316 OC.LocEnd)); 15317 15318 // C99 7.17p3: 15319 // (If the specified member is a bit-field, the behavior is undefined.) 15320 // 15321 // We diagnose this as an error. 15322 if (MemberDecl->isBitField()) { 15323 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15324 << MemberDecl->getDeclName() 15325 << SourceRange(BuiltinLoc, RParenLoc); 15326 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15327 return ExprError(); 15328 } 15329 15330 RecordDecl *Parent = MemberDecl->getParent(); 15331 if (IndirectMemberDecl) 15332 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15333 15334 // If the member was found in a base class, introduce OffsetOfNodes for 15335 // the base class indirections. 15336 CXXBasePaths Paths; 15337 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15338 Paths)) { 15339 if (Paths.getDetectedVirtual()) { 15340 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15341 << MemberDecl->getDeclName() 15342 << SourceRange(BuiltinLoc, RParenLoc); 15343 return ExprError(); 15344 } 15345 15346 CXXBasePath &Path = Paths.front(); 15347 for (const CXXBasePathElement &B : Path) 15348 Comps.push_back(OffsetOfNode(B.Base)); 15349 } 15350 15351 if (IndirectMemberDecl) { 15352 for (auto *FI : IndirectMemberDecl->chain()) { 15353 assert(isa<FieldDecl>(FI)); 15354 Comps.push_back(OffsetOfNode(OC.LocStart, 15355 cast<FieldDecl>(FI), OC.LocEnd)); 15356 } 15357 } else 15358 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15359 15360 CurrentType = MemberDecl->getType().getNonReferenceType(); 15361 } 15362 15363 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15364 Comps, Exprs, RParenLoc); 15365 } 15366 15367 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15368 SourceLocation BuiltinLoc, 15369 SourceLocation TypeLoc, 15370 ParsedType ParsedArgTy, 15371 ArrayRef<OffsetOfComponent> Components, 15372 SourceLocation RParenLoc) { 15373 15374 TypeSourceInfo *ArgTInfo; 15375 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15376 if (ArgTy.isNull()) 15377 return ExprError(); 15378 15379 if (!ArgTInfo) 15380 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15381 15382 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15383 } 15384 15385 15386 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15387 Expr *CondExpr, 15388 Expr *LHSExpr, Expr *RHSExpr, 15389 SourceLocation RPLoc) { 15390 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15391 15392 ExprValueKind VK = VK_PRValue; 15393 ExprObjectKind OK = OK_Ordinary; 15394 QualType resType; 15395 bool CondIsTrue = false; 15396 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15397 resType = Context.DependentTy; 15398 } else { 15399 // The conditional expression is required to be a constant expression. 15400 llvm::APSInt condEval(32); 15401 ExprResult CondICE = VerifyIntegerConstantExpression( 15402 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15403 if (CondICE.isInvalid()) 15404 return ExprError(); 15405 CondExpr = CondICE.get(); 15406 CondIsTrue = condEval.getZExtValue(); 15407 15408 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15409 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15410 15411 resType = ActiveExpr->getType(); 15412 VK = ActiveExpr->getValueKind(); 15413 OK = ActiveExpr->getObjectKind(); 15414 } 15415 15416 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15417 resType, VK, OK, RPLoc, CondIsTrue); 15418 } 15419 15420 //===----------------------------------------------------------------------===// 15421 // Clang Extensions. 15422 //===----------------------------------------------------------------------===// 15423 15424 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15425 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15426 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15427 15428 if (LangOpts.CPlusPlus) { 15429 MangleNumberingContext *MCtx; 15430 Decl *ManglingContextDecl; 15431 std::tie(MCtx, ManglingContextDecl) = 15432 getCurrentMangleNumberContext(Block->getDeclContext()); 15433 if (MCtx) { 15434 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15435 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15436 } 15437 } 15438 15439 PushBlockScope(CurScope, Block); 15440 CurContext->addDecl(Block); 15441 if (CurScope) 15442 PushDeclContext(CurScope, Block); 15443 else 15444 CurContext = Block; 15445 15446 getCurBlock()->HasImplicitReturnType = true; 15447 15448 // Enter a new evaluation context to insulate the block from any 15449 // cleanups from the enclosing full-expression. 15450 PushExpressionEvaluationContext( 15451 ExpressionEvaluationContext::PotentiallyEvaluated); 15452 } 15453 15454 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15455 Scope *CurScope) { 15456 assert(ParamInfo.getIdentifier() == nullptr && 15457 "block-id should have no identifier!"); 15458 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15459 BlockScopeInfo *CurBlock = getCurBlock(); 15460 15461 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15462 QualType T = Sig->getType(); 15463 15464 // FIXME: We should allow unexpanded parameter packs here, but that would, 15465 // in turn, make the block expression contain unexpanded parameter packs. 15466 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15467 // Drop the parameters. 15468 FunctionProtoType::ExtProtoInfo EPI; 15469 EPI.HasTrailingReturn = false; 15470 EPI.TypeQuals.addConst(); 15471 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15472 Sig = Context.getTrivialTypeSourceInfo(T); 15473 } 15474 15475 // GetTypeForDeclarator always produces a function type for a block 15476 // literal signature. Furthermore, it is always a FunctionProtoType 15477 // unless the function was written with a typedef. 15478 assert(T->isFunctionType() && 15479 "GetTypeForDeclarator made a non-function block signature"); 15480 15481 // Look for an explicit signature in that function type. 15482 FunctionProtoTypeLoc ExplicitSignature; 15483 15484 if ((ExplicitSignature = Sig->getTypeLoc() 15485 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15486 15487 // Check whether that explicit signature was synthesized by 15488 // GetTypeForDeclarator. If so, don't save that as part of the 15489 // written signature. 15490 if (ExplicitSignature.getLocalRangeBegin() == 15491 ExplicitSignature.getLocalRangeEnd()) { 15492 // This would be much cheaper if we stored TypeLocs instead of 15493 // TypeSourceInfos. 15494 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15495 unsigned Size = Result.getFullDataSize(); 15496 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15497 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15498 15499 ExplicitSignature = FunctionProtoTypeLoc(); 15500 } 15501 } 15502 15503 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15504 CurBlock->FunctionType = T; 15505 15506 const auto *Fn = T->castAs<FunctionType>(); 15507 QualType RetTy = Fn->getReturnType(); 15508 bool isVariadic = 15509 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15510 15511 CurBlock->TheDecl->setIsVariadic(isVariadic); 15512 15513 // Context.DependentTy is used as a placeholder for a missing block 15514 // return type. TODO: what should we do with declarators like: 15515 // ^ * { ... } 15516 // If the answer is "apply template argument deduction".... 15517 if (RetTy != Context.DependentTy) { 15518 CurBlock->ReturnType = RetTy; 15519 CurBlock->TheDecl->setBlockMissingReturnType(false); 15520 CurBlock->HasImplicitReturnType = false; 15521 } 15522 15523 // Push block parameters from the declarator if we had them. 15524 SmallVector<ParmVarDecl*, 8> Params; 15525 if (ExplicitSignature) { 15526 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15527 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15528 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15529 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15530 // Diagnose this as an extension in C17 and earlier. 15531 if (!getLangOpts().C2x) 15532 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15533 } 15534 Params.push_back(Param); 15535 } 15536 15537 // Fake up parameter variables if we have a typedef, like 15538 // ^ fntype { ... } 15539 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15540 for (const auto &I : Fn->param_types()) { 15541 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15542 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15543 Params.push_back(Param); 15544 } 15545 } 15546 15547 // Set the parameters on the block decl. 15548 if (!Params.empty()) { 15549 CurBlock->TheDecl->setParams(Params); 15550 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15551 /*CheckParameterNames=*/false); 15552 } 15553 15554 // Finally we can process decl attributes. 15555 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15556 15557 // Put the parameter variables in scope. 15558 for (auto AI : CurBlock->TheDecl->parameters()) { 15559 AI->setOwningFunction(CurBlock->TheDecl); 15560 15561 // If this has an identifier, add it to the scope stack. 15562 if (AI->getIdentifier()) { 15563 CheckShadow(CurBlock->TheScope, AI); 15564 15565 PushOnScopeChains(AI, CurBlock->TheScope); 15566 } 15567 } 15568 } 15569 15570 /// ActOnBlockError - If there is an error parsing a block, this callback 15571 /// is invoked to pop the information about the block from the action impl. 15572 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15573 // Leave the expression-evaluation context. 15574 DiscardCleanupsInEvaluationContext(); 15575 PopExpressionEvaluationContext(); 15576 15577 // Pop off CurBlock, handle nested blocks. 15578 PopDeclContext(); 15579 PopFunctionScopeInfo(); 15580 } 15581 15582 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15583 /// literal was successfully completed. ^(int x){...} 15584 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15585 Stmt *Body, Scope *CurScope) { 15586 // If blocks are disabled, emit an error. 15587 if (!LangOpts.Blocks) 15588 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15589 15590 // Leave the expression-evaluation context. 15591 if (hasAnyUnrecoverableErrorsInThisFunction()) 15592 DiscardCleanupsInEvaluationContext(); 15593 assert(!Cleanup.exprNeedsCleanups() && 15594 "cleanups within block not correctly bound!"); 15595 PopExpressionEvaluationContext(); 15596 15597 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15598 BlockDecl *BD = BSI->TheDecl; 15599 15600 if (BSI->HasImplicitReturnType) 15601 deduceClosureReturnType(*BSI); 15602 15603 QualType RetTy = Context.VoidTy; 15604 if (!BSI->ReturnType.isNull()) 15605 RetTy = BSI->ReturnType; 15606 15607 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15608 QualType BlockTy; 15609 15610 // If the user wrote a function type in some form, try to use that. 15611 if (!BSI->FunctionType.isNull()) { 15612 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15613 15614 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15615 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15616 15617 // Turn protoless block types into nullary block types. 15618 if (isa<FunctionNoProtoType>(FTy)) { 15619 FunctionProtoType::ExtProtoInfo EPI; 15620 EPI.ExtInfo = Ext; 15621 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15622 15623 // Otherwise, if we don't need to change anything about the function type, 15624 // preserve its sugar structure. 15625 } else if (FTy->getReturnType() == RetTy && 15626 (!NoReturn || FTy->getNoReturnAttr())) { 15627 BlockTy = BSI->FunctionType; 15628 15629 // Otherwise, make the minimal modifications to the function type. 15630 } else { 15631 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15632 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15633 EPI.TypeQuals = Qualifiers(); 15634 EPI.ExtInfo = Ext; 15635 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15636 } 15637 15638 // If we don't have a function type, just build one from nothing. 15639 } else { 15640 FunctionProtoType::ExtProtoInfo EPI; 15641 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15642 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15643 } 15644 15645 DiagnoseUnusedParameters(BD->parameters()); 15646 BlockTy = Context.getBlockPointerType(BlockTy); 15647 15648 // If needed, diagnose invalid gotos and switches in the block. 15649 if (getCurFunction()->NeedsScopeChecking() && 15650 !PP.isCodeCompletionEnabled()) 15651 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15652 15653 BD->setBody(cast<CompoundStmt>(Body)); 15654 15655 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15656 DiagnoseUnguardedAvailabilityViolations(BD); 15657 15658 // Try to apply the named return value optimization. We have to check again 15659 // if we can do this, though, because blocks keep return statements around 15660 // to deduce an implicit return type. 15661 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15662 !BD->isDependentContext()) 15663 computeNRVO(Body, BSI); 15664 15665 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15666 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15667 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15668 NTCUK_Destruct|NTCUK_Copy); 15669 15670 PopDeclContext(); 15671 15672 // Set the captured variables on the block. 15673 SmallVector<BlockDecl::Capture, 4> Captures; 15674 for (Capture &Cap : BSI->Captures) { 15675 if (Cap.isInvalid() || Cap.isThisCapture()) 15676 continue; 15677 15678 VarDecl *Var = Cap.getVariable(); 15679 Expr *CopyExpr = nullptr; 15680 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15681 if (const RecordType *Record = 15682 Cap.getCaptureType()->getAs<RecordType>()) { 15683 // The capture logic needs the destructor, so make sure we mark it. 15684 // Usually this is unnecessary because most local variables have 15685 // their destructors marked at declaration time, but parameters are 15686 // an exception because it's technically only the call site that 15687 // actually requires the destructor. 15688 if (isa<ParmVarDecl>(Var)) 15689 FinalizeVarWithDestructor(Var, Record); 15690 15691 // Enter a separate potentially-evaluated context while building block 15692 // initializers to isolate their cleanups from those of the block 15693 // itself. 15694 // FIXME: Is this appropriate even when the block itself occurs in an 15695 // unevaluated operand? 15696 EnterExpressionEvaluationContext EvalContext( 15697 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15698 15699 SourceLocation Loc = Cap.getLocation(); 15700 15701 ExprResult Result = BuildDeclarationNameExpr( 15702 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15703 15704 // According to the blocks spec, the capture of a variable from 15705 // the stack requires a const copy constructor. This is not true 15706 // of the copy/move done to move a __block variable to the heap. 15707 if (!Result.isInvalid() && 15708 !Result.get()->getType().isConstQualified()) { 15709 Result = ImpCastExprToType(Result.get(), 15710 Result.get()->getType().withConst(), 15711 CK_NoOp, VK_LValue); 15712 } 15713 15714 if (!Result.isInvalid()) { 15715 Result = PerformCopyInitialization( 15716 InitializedEntity::InitializeBlock(Var->getLocation(), 15717 Cap.getCaptureType()), 15718 Loc, Result.get()); 15719 } 15720 15721 // Build a full-expression copy expression if initialization 15722 // succeeded and used a non-trivial constructor. Recover from 15723 // errors by pretending that the copy isn't necessary. 15724 if (!Result.isInvalid() && 15725 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15726 ->isTrivial()) { 15727 Result = MaybeCreateExprWithCleanups(Result); 15728 CopyExpr = Result.get(); 15729 } 15730 } 15731 } 15732 15733 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15734 CopyExpr); 15735 Captures.push_back(NewCap); 15736 } 15737 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15738 15739 // Pop the block scope now but keep it alive to the end of this function. 15740 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15741 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15742 15743 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15744 15745 // If the block isn't obviously global, i.e. it captures anything at 15746 // all, then we need to do a few things in the surrounding context: 15747 if (Result->getBlockDecl()->hasCaptures()) { 15748 // First, this expression has a new cleanup object. 15749 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15750 Cleanup.setExprNeedsCleanups(true); 15751 15752 // It also gets a branch-protected scope if any of the captured 15753 // variables needs destruction. 15754 for (const auto &CI : Result->getBlockDecl()->captures()) { 15755 const VarDecl *var = CI.getVariable(); 15756 if (var->getType().isDestructedType() != QualType::DK_none) { 15757 setFunctionHasBranchProtectedScope(); 15758 break; 15759 } 15760 } 15761 } 15762 15763 if (getCurFunction()) 15764 getCurFunction()->addBlock(BD); 15765 15766 return Result; 15767 } 15768 15769 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15770 SourceLocation RPLoc) { 15771 TypeSourceInfo *TInfo; 15772 GetTypeFromParser(Ty, &TInfo); 15773 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15774 } 15775 15776 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15777 Expr *E, TypeSourceInfo *TInfo, 15778 SourceLocation RPLoc) { 15779 Expr *OrigExpr = E; 15780 bool IsMS = false; 15781 15782 // CUDA device code does not support varargs. 15783 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15784 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15785 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15786 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15787 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15788 } 15789 } 15790 15791 // NVPTX does not support va_arg expression. 15792 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15793 Context.getTargetInfo().getTriple().isNVPTX()) 15794 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15795 15796 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15797 // as Microsoft ABI on an actual Microsoft platform, where 15798 // __builtin_ms_va_list and __builtin_va_list are the same.) 15799 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15800 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15801 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15802 if (Context.hasSameType(MSVaListType, E->getType())) { 15803 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15804 return ExprError(); 15805 IsMS = true; 15806 } 15807 } 15808 15809 // Get the va_list type 15810 QualType VaListType = Context.getBuiltinVaListType(); 15811 if (!IsMS) { 15812 if (VaListType->isArrayType()) { 15813 // Deal with implicit array decay; for example, on x86-64, 15814 // va_list is an array, but it's supposed to decay to 15815 // a pointer for va_arg. 15816 VaListType = Context.getArrayDecayedType(VaListType); 15817 // Make sure the input expression also decays appropriately. 15818 ExprResult Result = UsualUnaryConversions(E); 15819 if (Result.isInvalid()) 15820 return ExprError(); 15821 E = Result.get(); 15822 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15823 // If va_list is a record type and we are compiling in C++ mode, 15824 // check the argument using reference binding. 15825 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15826 Context, Context.getLValueReferenceType(VaListType), false); 15827 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15828 if (Init.isInvalid()) 15829 return ExprError(); 15830 E = Init.getAs<Expr>(); 15831 } else { 15832 // Otherwise, the va_list argument must be an l-value because 15833 // it is modified by va_arg. 15834 if (!E->isTypeDependent() && 15835 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15836 return ExprError(); 15837 } 15838 } 15839 15840 if (!IsMS && !E->isTypeDependent() && 15841 !Context.hasSameType(VaListType, E->getType())) 15842 return ExprError( 15843 Diag(E->getBeginLoc(), 15844 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15845 << OrigExpr->getType() << E->getSourceRange()); 15846 15847 if (!TInfo->getType()->isDependentType()) { 15848 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15849 diag::err_second_parameter_to_va_arg_incomplete, 15850 TInfo->getTypeLoc())) 15851 return ExprError(); 15852 15853 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15854 TInfo->getType(), 15855 diag::err_second_parameter_to_va_arg_abstract, 15856 TInfo->getTypeLoc())) 15857 return ExprError(); 15858 15859 if (!TInfo->getType().isPODType(Context)) { 15860 Diag(TInfo->getTypeLoc().getBeginLoc(), 15861 TInfo->getType()->isObjCLifetimeType() 15862 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15863 : diag::warn_second_parameter_to_va_arg_not_pod) 15864 << TInfo->getType() 15865 << TInfo->getTypeLoc().getSourceRange(); 15866 } 15867 15868 // Check for va_arg where arguments of the given type will be promoted 15869 // (i.e. this va_arg is guaranteed to have undefined behavior). 15870 QualType PromoteType; 15871 if (TInfo->getType()->isPromotableIntegerType()) { 15872 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15873 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 15874 // and C2x 7.16.1.1p2 says, in part: 15875 // If type is not compatible with the type of the actual next argument 15876 // (as promoted according to the default argument promotions), the 15877 // behavior is undefined, except for the following cases: 15878 // - both types are pointers to qualified or unqualified versions of 15879 // compatible types; 15880 // - one type is a signed integer type, the other type is the 15881 // corresponding unsigned integer type, and the value is 15882 // representable in both types; 15883 // - one type is pointer to qualified or unqualified void and the 15884 // other is a pointer to a qualified or unqualified character type. 15885 // Given that type compatibility is the primary requirement (ignoring 15886 // qualifications), you would think we could call typesAreCompatible() 15887 // directly to test this. However, in C++, that checks for *same type*, 15888 // which causes false positives when passing an enumeration type to 15889 // va_arg. Instead, get the underlying type of the enumeration and pass 15890 // that. 15891 QualType UnderlyingType = TInfo->getType(); 15892 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 15893 UnderlyingType = ET->getDecl()->getIntegerType(); 15894 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15895 /*CompareUnqualified*/ true)) 15896 PromoteType = QualType(); 15897 15898 // If the types are still not compatible, we need to test whether the 15899 // promoted type and the underlying type are the same except for 15900 // signedness. Ask the AST for the correctly corresponding type and see 15901 // if that's compatible. 15902 if (!PromoteType.isNull() && 15903 PromoteType->isUnsignedIntegerType() != 15904 UnderlyingType->isUnsignedIntegerType()) { 15905 UnderlyingType = 15906 UnderlyingType->isUnsignedIntegerType() 15907 ? Context.getCorrespondingSignedType(UnderlyingType) 15908 : Context.getCorrespondingUnsignedType(UnderlyingType); 15909 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15910 /*CompareUnqualified*/ true)) 15911 PromoteType = QualType(); 15912 } 15913 } 15914 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15915 PromoteType = Context.DoubleTy; 15916 if (!PromoteType.isNull()) 15917 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15918 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15919 << TInfo->getType() 15920 << PromoteType 15921 << TInfo->getTypeLoc().getSourceRange()); 15922 } 15923 15924 QualType T = TInfo->getType().getNonLValueExprType(Context); 15925 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15926 } 15927 15928 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15929 // The type of __null will be int or long, depending on the size of 15930 // pointers on the target. 15931 QualType Ty; 15932 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15933 if (pw == Context.getTargetInfo().getIntWidth()) 15934 Ty = Context.IntTy; 15935 else if (pw == Context.getTargetInfo().getLongWidth()) 15936 Ty = Context.LongTy; 15937 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15938 Ty = Context.LongLongTy; 15939 else { 15940 llvm_unreachable("I don't know size of pointer!"); 15941 } 15942 15943 return new (Context) GNUNullExpr(Ty, TokenLoc); 15944 } 15945 15946 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15947 SourceLocation BuiltinLoc, 15948 SourceLocation RPLoc) { 15949 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15950 } 15951 15952 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15953 SourceLocation BuiltinLoc, 15954 SourceLocation RPLoc, 15955 DeclContext *ParentContext) { 15956 return new (Context) 15957 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15958 } 15959 15960 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15961 bool Diagnose) { 15962 if (!getLangOpts().ObjC) 15963 return false; 15964 15965 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15966 if (!PT) 15967 return false; 15968 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15969 15970 // Ignore any parens, implicit casts (should only be 15971 // array-to-pointer decays), and not-so-opaque values. The last is 15972 // important for making this trigger for property assignments. 15973 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15974 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15975 if (OV->getSourceExpr()) 15976 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15977 15978 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15979 if (!PT->isObjCIdType() && 15980 !(ID && ID->getIdentifier()->isStr("NSString"))) 15981 return false; 15982 if (!SL->isAscii()) 15983 return false; 15984 15985 if (Diagnose) { 15986 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15987 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15988 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15989 } 15990 return true; 15991 } 15992 15993 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15994 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15995 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15996 !SrcExpr->isNullPointerConstant( 15997 getASTContext(), Expr::NPC_NeverValueDependent)) { 15998 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15999 return false; 16000 if (Diagnose) { 16001 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 16002 << /*number*/1 16003 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 16004 Expr *NumLit = 16005 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 16006 if (NumLit) 16007 Exp = NumLit; 16008 } 16009 return true; 16010 } 16011 16012 return false; 16013 } 16014 16015 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 16016 const Expr *SrcExpr) { 16017 if (!DstType->isFunctionPointerType() || 16018 !SrcExpr->getType()->isFunctionType()) 16019 return false; 16020 16021 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 16022 if (!DRE) 16023 return false; 16024 16025 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 16026 if (!FD) 16027 return false; 16028 16029 return !S.checkAddressOfFunctionIsAvailable(FD, 16030 /*Complain=*/true, 16031 SrcExpr->getBeginLoc()); 16032 } 16033 16034 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 16035 SourceLocation Loc, 16036 QualType DstType, QualType SrcType, 16037 Expr *SrcExpr, AssignmentAction Action, 16038 bool *Complained) { 16039 if (Complained) 16040 *Complained = false; 16041 16042 // Decode the result (notice that AST's are still created for extensions). 16043 bool CheckInferredResultType = false; 16044 bool isInvalid = false; 16045 unsigned DiagKind = 0; 16046 ConversionFixItGenerator ConvHints; 16047 bool MayHaveConvFixit = false; 16048 bool MayHaveFunctionDiff = false; 16049 const ObjCInterfaceDecl *IFace = nullptr; 16050 const ObjCProtocolDecl *PDecl = nullptr; 16051 16052 switch (ConvTy) { 16053 case Compatible: 16054 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 16055 return false; 16056 16057 case PointerToInt: 16058 if (getLangOpts().CPlusPlus) { 16059 DiagKind = diag::err_typecheck_convert_pointer_int; 16060 isInvalid = true; 16061 } else { 16062 DiagKind = diag::ext_typecheck_convert_pointer_int; 16063 } 16064 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16065 MayHaveConvFixit = true; 16066 break; 16067 case IntToPointer: 16068 if (getLangOpts().CPlusPlus) { 16069 DiagKind = diag::err_typecheck_convert_int_pointer; 16070 isInvalid = true; 16071 } else { 16072 DiagKind = diag::ext_typecheck_convert_int_pointer; 16073 } 16074 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16075 MayHaveConvFixit = true; 16076 break; 16077 case IncompatibleFunctionPointer: 16078 if (getLangOpts().CPlusPlus) { 16079 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 16080 isInvalid = true; 16081 } else { 16082 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 16083 } 16084 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16085 MayHaveConvFixit = true; 16086 break; 16087 case IncompatiblePointer: 16088 if (Action == AA_Passing_CFAudited) { 16089 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 16090 } else if (getLangOpts().CPlusPlus) { 16091 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 16092 isInvalid = true; 16093 } else { 16094 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 16095 } 16096 CheckInferredResultType = DstType->isObjCObjectPointerType() && 16097 SrcType->isObjCObjectPointerType(); 16098 if (!CheckInferredResultType) { 16099 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16100 } else if (CheckInferredResultType) { 16101 SrcType = SrcType.getUnqualifiedType(); 16102 DstType = DstType.getUnqualifiedType(); 16103 } 16104 MayHaveConvFixit = true; 16105 break; 16106 case IncompatiblePointerSign: 16107 if (getLangOpts().CPlusPlus) { 16108 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 16109 isInvalid = true; 16110 } else { 16111 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 16112 } 16113 break; 16114 case FunctionVoidPointer: 16115 if (getLangOpts().CPlusPlus) { 16116 DiagKind = diag::err_typecheck_convert_pointer_void_func; 16117 isInvalid = true; 16118 } else { 16119 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 16120 } 16121 break; 16122 case IncompatiblePointerDiscardsQualifiers: { 16123 // Perform array-to-pointer decay if necessary. 16124 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 16125 16126 isInvalid = true; 16127 16128 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 16129 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 16130 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 16131 DiagKind = diag::err_typecheck_incompatible_address_space; 16132 break; 16133 16134 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 16135 DiagKind = diag::err_typecheck_incompatible_ownership; 16136 break; 16137 } 16138 16139 llvm_unreachable("unknown error case for discarding qualifiers!"); 16140 // fallthrough 16141 } 16142 case CompatiblePointerDiscardsQualifiers: 16143 // If the qualifiers lost were because we were applying the 16144 // (deprecated) C++ conversion from a string literal to a char* 16145 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 16146 // Ideally, this check would be performed in 16147 // checkPointerTypesForAssignment. However, that would require a 16148 // bit of refactoring (so that the second argument is an 16149 // expression, rather than a type), which should be done as part 16150 // of a larger effort to fix checkPointerTypesForAssignment for 16151 // C++ semantics. 16152 if (getLangOpts().CPlusPlus && 16153 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 16154 return false; 16155 if (getLangOpts().CPlusPlus) { 16156 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 16157 isInvalid = true; 16158 } else { 16159 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 16160 } 16161 16162 break; 16163 case IncompatibleNestedPointerQualifiers: 16164 if (getLangOpts().CPlusPlus) { 16165 isInvalid = true; 16166 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 16167 } else { 16168 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16169 } 16170 break; 16171 case IncompatibleNestedPointerAddressSpaceMismatch: 16172 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16173 isInvalid = true; 16174 break; 16175 case IntToBlockPointer: 16176 DiagKind = diag::err_int_to_block_pointer; 16177 isInvalid = true; 16178 break; 16179 case IncompatibleBlockPointer: 16180 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16181 isInvalid = true; 16182 break; 16183 case IncompatibleObjCQualifiedId: { 16184 if (SrcType->isObjCQualifiedIdType()) { 16185 const ObjCObjectPointerType *srcOPT = 16186 SrcType->castAs<ObjCObjectPointerType>(); 16187 for (auto *srcProto : srcOPT->quals()) { 16188 PDecl = srcProto; 16189 break; 16190 } 16191 if (const ObjCInterfaceType *IFaceT = 16192 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16193 IFace = IFaceT->getDecl(); 16194 } 16195 else if (DstType->isObjCQualifiedIdType()) { 16196 const ObjCObjectPointerType *dstOPT = 16197 DstType->castAs<ObjCObjectPointerType>(); 16198 for (auto *dstProto : dstOPT->quals()) { 16199 PDecl = dstProto; 16200 break; 16201 } 16202 if (const ObjCInterfaceType *IFaceT = 16203 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16204 IFace = IFaceT->getDecl(); 16205 } 16206 if (getLangOpts().CPlusPlus) { 16207 DiagKind = diag::err_incompatible_qualified_id; 16208 isInvalid = true; 16209 } else { 16210 DiagKind = diag::warn_incompatible_qualified_id; 16211 } 16212 break; 16213 } 16214 case IncompatibleVectors: 16215 if (getLangOpts().CPlusPlus) { 16216 DiagKind = diag::err_incompatible_vectors; 16217 isInvalid = true; 16218 } else { 16219 DiagKind = diag::warn_incompatible_vectors; 16220 } 16221 break; 16222 case IncompatibleObjCWeakRef: 16223 DiagKind = diag::err_arc_weak_unavailable_assign; 16224 isInvalid = true; 16225 break; 16226 case Incompatible: 16227 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16228 if (Complained) 16229 *Complained = true; 16230 return true; 16231 } 16232 16233 DiagKind = diag::err_typecheck_convert_incompatible; 16234 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16235 MayHaveConvFixit = true; 16236 isInvalid = true; 16237 MayHaveFunctionDiff = true; 16238 break; 16239 } 16240 16241 QualType FirstType, SecondType; 16242 switch (Action) { 16243 case AA_Assigning: 16244 case AA_Initializing: 16245 // The destination type comes first. 16246 FirstType = DstType; 16247 SecondType = SrcType; 16248 break; 16249 16250 case AA_Returning: 16251 case AA_Passing: 16252 case AA_Passing_CFAudited: 16253 case AA_Converting: 16254 case AA_Sending: 16255 case AA_Casting: 16256 // The source type comes first. 16257 FirstType = SrcType; 16258 SecondType = DstType; 16259 break; 16260 } 16261 16262 PartialDiagnostic FDiag = PDiag(DiagKind); 16263 if (Action == AA_Passing_CFAudited) 16264 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16265 else 16266 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16267 16268 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16269 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16270 auto isPlainChar = [](const clang::Type *Type) { 16271 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16272 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16273 }; 16274 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16275 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16276 } 16277 16278 // If we can fix the conversion, suggest the FixIts. 16279 if (!ConvHints.isNull()) { 16280 for (FixItHint &H : ConvHints.Hints) 16281 FDiag << H; 16282 } 16283 16284 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16285 16286 if (MayHaveFunctionDiff) 16287 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16288 16289 Diag(Loc, FDiag); 16290 if ((DiagKind == diag::warn_incompatible_qualified_id || 16291 DiagKind == diag::err_incompatible_qualified_id) && 16292 PDecl && IFace && !IFace->hasDefinition()) 16293 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16294 << IFace << PDecl; 16295 16296 if (SecondType == Context.OverloadTy) 16297 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16298 FirstType, /*TakingAddress=*/true); 16299 16300 if (CheckInferredResultType) 16301 EmitRelatedResultTypeNote(SrcExpr); 16302 16303 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16304 EmitRelatedResultTypeNoteForReturn(DstType); 16305 16306 if (Complained) 16307 *Complained = true; 16308 return isInvalid; 16309 } 16310 16311 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16312 llvm::APSInt *Result, 16313 AllowFoldKind CanFold) { 16314 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16315 public: 16316 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16317 QualType T) override { 16318 return S.Diag(Loc, diag::err_ice_not_integral) 16319 << T << S.LangOpts.CPlusPlus; 16320 } 16321 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16322 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16323 } 16324 } Diagnoser; 16325 16326 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16327 } 16328 16329 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16330 llvm::APSInt *Result, 16331 unsigned DiagID, 16332 AllowFoldKind CanFold) { 16333 class IDDiagnoser : public VerifyICEDiagnoser { 16334 unsigned DiagID; 16335 16336 public: 16337 IDDiagnoser(unsigned DiagID) 16338 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16339 16340 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16341 return S.Diag(Loc, DiagID); 16342 } 16343 } Diagnoser(DiagID); 16344 16345 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16346 } 16347 16348 Sema::SemaDiagnosticBuilder 16349 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16350 QualType T) { 16351 return diagnoseNotICE(S, Loc); 16352 } 16353 16354 Sema::SemaDiagnosticBuilder 16355 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16356 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16357 } 16358 16359 ExprResult 16360 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16361 VerifyICEDiagnoser &Diagnoser, 16362 AllowFoldKind CanFold) { 16363 SourceLocation DiagLoc = E->getBeginLoc(); 16364 16365 if (getLangOpts().CPlusPlus11) { 16366 // C++11 [expr.const]p5: 16367 // If an expression of literal class type is used in a context where an 16368 // integral constant expression is required, then that class type shall 16369 // have a single non-explicit conversion function to an integral or 16370 // unscoped enumeration type 16371 ExprResult Converted; 16372 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16373 VerifyICEDiagnoser &BaseDiagnoser; 16374 public: 16375 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16376 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16377 BaseDiagnoser.Suppress, true), 16378 BaseDiagnoser(BaseDiagnoser) {} 16379 16380 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16381 QualType T) override { 16382 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16383 } 16384 16385 SemaDiagnosticBuilder diagnoseIncomplete( 16386 Sema &S, SourceLocation Loc, QualType T) override { 16387 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16388 } 16389 16390 SemaDiagnosticBuilder diagnoseExplicitConv( 16391 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16392 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16393 } 16394 16395 SemaDiagnosticBuilder noteExplicitConv( 16396 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16397 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16398 << ConvTy->isEnumeralType() << ConvTy; 16399 } 16400 16401 SemaDiagnosticBuilder diagnoseAmbiguous( 16402 Sema &S, SourceLocation Loc, QualType T) override { 16403 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16404 } 16405 16406 SemaDiagnosticBuilder noteAmbiguous( 16407 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16408 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16409 << ConvTy->isEnumeralType() << ConvTy; 16410 } 16411 16412 SemaDiagnosticBuilder diagnoseConversion( 16413 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16414 llvm_unreachable("conversion functions are permitted"); 16415 } 16416 } ConvertDiagnoser(Diagnoser); 16417 16418 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16419 ConvertDiagnoser); 16420 if (Converted.isInvalid()) 16421 return Converted; 16422 E = Converted.get(); 16423 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16424 return ExprError(); 16425 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16426 // An ICE must be of integral or unscoped enumeration type. 16427 if (!Diagnoser.Suppress) 16428 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16429 << E->getSourceRange(); 16430 return ExprError(); 16431 } 16432 16433 ExprResult RValueExpr = DefaultLvalueConversion(E); 16434 if (RValueExpr.isInvalid()) 16435 return ExprError(); 16436 16437 E = RValueExpr.get(); 16438 16439 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16440 // in the non-ICE case. 16441 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16442 if (Result) 16443 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16444 if (!isa<ConstantExpr>(E)) 16445 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16446 : ConstantExpr::Create(Context, E); 16447 return E; 16448 } 16449 16450 Expr::EvalResult EvalResult; 16451 SmallVector<PartialDiagnosticAt, 8> Notes; 16452 EvalResult.Diag = &Notes; 16453 16454 // Try to evaluate the expression, and produce diagnostics explaining why it's 16455 // not a constant expression as a side-effect. 16456 bool Folded = 16457 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16458 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16459 16460 if (!isa<ConstantExpr>(E)) 16461 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16462 16463 // In C++11, we can rely on diagnostics being produced for any expression 16464 // which is not a constant expression. If no diagnostics were produced, then 16465 // this is a constant expression. 16466 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16467 if (Result) 16468 *Result = EvalResult.Val.getInt(); 16469 return E; 16470 } 16471 16472 // If our only note is the usual "invalid subexpression" note, just point 16473 // the caret at its location rather than producing an essentially 16474 // redundant note. 16475 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16476 diag::note_invalid_subexpr_in_const_expr) { 16477 DiagLoc = Notes[0].first; 16478 Notes.clear(); 16479 } 16480 16481 if (!Folded || !CanFold) { 16482 if (!Diagnoser.Suppress) { 16483 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16484 for (const PartialDiagnosticAt &Note : Notes) 16485 Diag(Note.first, Note.second); 16486 } 16487 16488 return ExprError(); 16489 } 16490 16491 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16492 for (const PartialDiagnosticAt &Note : Notes) 16493 Diag(Note.first, Note.second); 16494 16495 if (Result) 16496 *Result = EvalResult.Val.getInt(); 16497 return E; 16498 } 16499 16500 namespace { 16501 // Handle the case where we conclude a expression which we speculatively 16502 // considered to be unevaluated is actually evaluated. 16503 class TransformToPE : public TreeTransform<TransformToPE> { 16504 typedef TreeTransform<TransformToPE> BaseTransform; 16505 16506 public: 16507 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16508 16509 // Make sure we redo semantic analysis 16510 bool AlwaysRebuild() { return true; } 16511 bool ReplacingOriginal() { return true; } 16512 16513 // We need to special-case DeclRefExprs referring to FieldDecls which 16514 // are not part of a member pointer formation; normal TreeTransforming 16515 // doesn't catch this case because of the way we represent them in the AST. 16516 // FIXME: This is a bit ugly; is it really the best way to handle this 16517 // case? 16518 // 16519 // Error on DeclRefExprs referring to FieldDecls. 16520 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16521 if (isa<FieldDecl>(E->getDecl()) && 16522 !SemaRef.isUnevaluatedContext()) 16523 return SemaRef.Diag(E->getLocation(), 16524 diag::err_invalid_non_static_member_use) 16525 << E->getDecl() << E->getSourceRange(); 16526 16527 return BaseTransform::TransformDeclRefExpr(E); 16528 } 16529 16530 // Exception: filter out member pointer formation 16531 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16532 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16533 return E; 16534 16535 return BaseTransform::TransformUnaryOperator(E); 16536 } 16537 16538 // The body of a lambda-expression is in a separate expression evaluation 16539 // context so never needs to be transformed. 16540 // FIXME: Ideally we wouldn't transform the closure type either, and would 16541 // just recreate the capture expressions and lambda expression. 16542 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16543 return SkipLambdaBody(E, Body); 16544 } 16545 }; 16546 } 16547 16548 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16549 assert(isUnevaluatedContext() && 16550 "Should only transform unevaluated expressions"); 16551 ExprEvalContexts.back().Context = 16552 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16553 if (isUnevaluatedContext()) 16554 return E; 16555 return TransformToPE(*this).TransformExpr(E); 16556 } 16557 16558 void 16559 Sema::PushExpressionEvaluationContext( 16560 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16561 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16562 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16563 LambdaContextDecl, ExprContext); 16564 Cleanup.reset(); 16565 if (!MaybeODRUseExprs.empty()) 16566 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16567 } 16568 16569 void 16570 Sema::PushExpressionEvaluationContext( 16571 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16572 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16573 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16574 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16575 } 16576 16577 namespace { 16578 16579 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16580 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16581 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16582 if (E->getOpcode() == UO_Deref) 16583 return CheckPossibleDeref(S, E->getSubExpr()); 16584 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16585 return CheckPossibleDeref(S, E->getBase()); 16586 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16587 return CheckPossibleDeref(S, E->getBase()); 16588 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16589 QualType Inner; 16590 QualType Ty = E->getType(); 16591 if (const auto *Ptr = Ty->getAs<PointerType>()) 16592 Inner = Ptr->getPointeeType(); 16593 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16594 Inner = Arr->getElementType(); 16595 else 16596 return nullptr; 16597 16598 if (Inner->hasAttr(attr::NoDeref)) 16599 return E; 16600 } 16601 return nullptr; 16602 } 16603 16604 } // namespace 16605 16606 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16607 for (const Expr *E : Rec.PossibleDerefs) { 16608 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16609 if (DeclRef) { 16610 const ValueDecl *Decl = DeclRef->getDecl(); 16611 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16612 << Decl->getName() << E->getSourceRange(); 16613 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16614 } else { 16615 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16616 << E->getSourceRange(); 16617 } 16618 } 16619 Rec.PossibleDerefs.clear(); 16620 } 16621 16622 /// Check whether E, which is either a discarded-value expression or an 16623 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16624 /// and if so, remove it from the list of volatile-qualified assignments that 16625 /// we are going to warn are deprecated. 16626 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16627 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16628 return; 16629 16630 // Note: ignoring parens here is not justified by the standard rules, but 16631 // ignoring parentheses seems like a more reasonable approach, and this only 16632 // drives a deprecation warning so doesn't affect conformance. 16633 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16634 if (BO->getOpcode() == BO_Assign) { 16635 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16636 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16637 LHSs.end()); 16638 } 16639 } 16640 } 16641 16642 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16643 if (isUnevaluatedContext() || !E.isUsable() || !Decl || 16644 !Decl->isConsteval() || isConstantEvaluated() || 16645 RebuildingImmediateInvocation) 16646 return E; 16647 16648 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16649 /// It's OK if this fails; we'll also remove this in 16650 /// HandleImmediateInvocations, but catching it here allows us to avoid 16651 /// walking the AST looking for it in simple cases. 16652 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16653 if (auto *DeclRef = 16654 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16655 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16656 16657 E = MaybeCreateExprWithCleanups(E); 16658 16659 ConstantExpr *Res = ConstantExpr::Create( 16660 getASTContext(), E.get(), 16661 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16662 getASTContext()), 16663 /*IsImmediateInvocation*/ true); 16664 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16665 return Res; 16666 } 16667 16668 static void EvaluateAndDiagnoseImmediateInvocation( 16669 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16670 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16671 Expr::EvalResult Eval; 16672 Eval.Diag = &Notes; 16673 ConstantExpr *CE = Candidate.getPointer(); 16674 bool Result = CE->EvaluateAsConstantExpr( 16675 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16676 if (!Result || !Notes.empty()) { 16677 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16678 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16679 InnerExpr = FunctionalCast->getSubExpr(); 16680 FunctionDecl *FD = nullptr; 16681 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16682 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16683 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16684 FD = Call->getConstructor(); 16685 else 16686 llvm_unreachable("unhandled decl kind"); 16687 assert(FD->isConsteval()); 16688 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16689 for (auto &Note : Notes) 16690 SemaRef.Diag(Note.first, Note.second); 16691 return; 16692 } 16693 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16694 } 16695 16696 static void RemoveNestedImmediateInvocation( 16697 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16698 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16699 struct ComplexRemove : TreeTransform<ComplexRemove> { 16700 using Base = TreeTransform<ComplexRemove>; 16701 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16702 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16703 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16704 CurrentII; 16705 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16706 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16707 SmallVector<Sema::ImmediateInvocationCandidate, 16708 4>::reverse_iterator Current) 16709 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16710 void RemoveImmediateInvocation(ConstantExpr* E) { 16711 auto It = std::find_if(CurrentII, IISet.rend(), 16712 [E](Sema::ImmediateInvocationCandidate Elem) { 16713 return Elem.getPointer() == E; 16714 }); 16715 assert(It != IISet.rend() && 16716 "ConstantExpr marked IsImmediateInvocation should " 16717 "be present"); 16718 It->setInt(1); // Mark as deleted 16719 } 16720 ExprResult TransformConstantExpr(ConstantExpr *E) { 16721 if (!E->isImmediateInvocation()) 16722 return Base::TransformConstantExpr(E); 16723 RemoveImmediateInvocation(E); 16724 return Base::TransformExpr(E->getSubExpr()); 16725 } 16726 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16727 /// we need to remove its DeclRefExpr from the DRSet. 16728 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16729 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16730 return Base::TransformCXXOperatorCallExpr(E); 16731 } 16732 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16733 /// here. 16734 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16735 if (!Init) 16736 return Init; 16737 /// ConstantExpr are the first layer of implicit node to be removed so if 16738 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16739 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16740 if (CE->isImmediateInvocation()) 16741 RemoveImmediateInvocation(CE); 16742 return Base::TransformInitializer(Init, NotCopyInit); 16743 } 16744 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16745 DRSet.erase(E); 16746 return E; 16747 } 16748 bool AlwaysRebuild() { return false; } 16749 bool ReplacingOriginal() { return true; } 16750 bool AllowSkippingCXXConstructExpr() { 16751 bool Res = AllowSkippingFirstCXXConstructExpr; 16752 AllowSkippingFirstCXXConstructExpr = true; 16753 return Res; 16754 } 16755 bool AllowSkippingFirstCXXConstructExpr = true; 16756 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16757 Rec.ImmediateInvocationCandidates, It); 16758 16759 /// CXXConstructExpr with a single argument are getting skipped by 16760 /// TreeTransform in some situtation because they could be implicit. This 16761 /// can only occur for the top-level CXXConstructExpr because it is used 16762 /// nowhere in the expression being transformed therefore will not be rebuilt. 16763 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16764 /// skipping the first CXXConstructExpr. 16765 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16766 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16767 16768 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16769 assert(Res.isUsable()); 16770 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16771 It->getPointer()->setSubExpr(Res.get()); 16772 } 16773 16774 static void 16775 HandleImmediateInvocations(Sema &SemaRef, 16776 Sema::ExpressionEvaluationContextRecord &Rec) { 16777 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16778 Rec.ReferenceToConsteval.size() == 0) || 16779 SemaRef.RebuildingImmediateInvocation) 16780 return; 16781 16782 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16783 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16784 /// need to remove ReferenceToConsteval in the immediate invocation. 16785 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16786 16787 /// Prevent sema calls during the tree transform from adding pointers that 16788 /// are already in the sets. 16789 llvm::SaveAndRestore<bool> DisableIITracking( 16790 SemaRef.RebuildingImmediateInvocation, true); 16791 16792 /// Prevent diagnostic during tree transfrom as they are duplicates 16793 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16794 16795 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16796 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16797 if (!It->getInt()) 16798 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16799 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16800 Rec.ReferenceToConsteval.size()) { 16801 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16802 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16803 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16804 bool VisitDeclRefExpr(DeclRefExpr *E) { 16805 DRSet.erase(E); 16806 return DRSet.size(); 16807 } 16808 } Visitor(Rec.ReferenceToConsteval); 16809 Visitor.TraverseStmt( 16810 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16811 } 16812 for (auto CE : Rec.ImmediateInvocationCandidates) 16813 if (!CE.getInt()) 16814 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16815 for (auto DR : Rec.ReferenceToConsteval) { 16816 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16817 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16818 << FD; 16819 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16820 } 16821 } 16822 16823 void Sema::PopExpressionEvaluationContext() { 16824 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16825 unsigned NumTypos = Rec.NumTypos; 16826 16827 if (!Rec.Lambdas.empty()) { 16828 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16829 if (!getLangOpts().CPlusPlus20 && 16830 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 16831 Rec.isUnevaluated() || 16832 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 16833 unsigned D; 16834 if (Rec.isUnevaluated()) { 16835 // C++11 [expr.prim.lambda]p2: 16836 // A lambda-expression shall not appear in an unevaluated operand 16837 // (Clause 5). 16838 D = diag::err_lambda_unevaluated_operand; 16839 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16840 // C++1y [expr.const]p2: 16841 // A conditional-expression e is a core constant expression unless the 16842 // evaluation of e, following the rules of the abstract machine, would 16843 // evaluate [...] a lambda-expression. 16844 D = diag::err_lambda_in_constant_expression; 16845 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16846 // C++17 [expr.prim.lamda]p2: 16847 // A lambda-expression shall not appear [...] in a template-argument. 16848 D = diag::err_lambda_in_invalid_context; 16849 } else 16850 llvm_unreachable("Couldn't infer lambda error message."); 16851 16852 for (const auto *L : Rec.Lambdas) 16853 Diag(L->getBeginLoc(), D); 16854 } 16855 } 16856 16857 WarnOnPendingNoDerefs(Rec); 16858 HandleImmediateInvocations(*this, Rec); 16859 16860 // Warn on any volatile-qualified simple-assignments that are not discarded- 16861 // value expressions nor unevaluated operands (those cases get removed from 16862 // this list by CheckUnusedVolatileAssignment). 16863 for (auto *BO : Rec.VolatileAssignmentLHSs) 16864 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16865 << BO->getType(); 16866 16867 // When are coming out of an unevaluated context, clear out any 16868 // temporaries that we may have created as part of the evaluation of 16869 // the expression in that context: they aren't relevant because they 16870 // will never be constructed. 16871 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16872 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16873 ExprCleanupObjects.end()); 16874 Cleanup = Rec.ParentCleanup; 16875 CleanupVarDeclMarking(); 16876 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16877 // Otherwise, merge the contexts together. 16878 } else { 16879 Cleanup.mergeFrom(Rec.ParentCleanup); 16880 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16881 Rec.SavedMaybeODRUseExprs.end()); 16882 } 16883 16884 // Pop the current expression evaluation context off the stack. 16885 ExprEvalContexts.pop_back(); 16886 16887 // The global expression evaluation context record is never popped. 16888 ExprEvalContexts.back().NumTypos += NumTypos; 16889 } 16890 16891 void Sema::DiscardCleanupsInEvaluationContext() { 16892 ExprCleanupObjects.erase( 16893 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16894 ExprCleanupObjects.end()); 16895 Cleanup.reset(); 16896 MaybeODRUseExprs.clear(); 16897 } 16898 16899 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16900 ExprResult Result = CheckPlaceholderExpr(E); 16901 if (Result.isInvalid()) 16902 return ExprError(); 16903 E = Result.get(); 16904 if (!E->getType()->isVariablyModifiedType()) 16905 return E; 16906 return TransformToPotentiallyEvaluated(E); 16907 } 16908 16909 /// Are we in a context that is potentially constant evaluated per C++20 16910 /// [expr.const]p12? 16911 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16912 /// C++2a [expr.const]p12: 16913 // An expression or conversion is potentially constant evaluated if it is 16914 switch (SemaRef.ExprEvalContexts.back().Context) { 16915 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16916 // -- a manifestly constant-evaluated expression, 16917 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16918 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16919 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16920 // -- a potentially-evaluated expression, 16921 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16922 // -- an immediate subexpression of a braced-init-list, 16923 16924 // -- [FIXME] an expression of the form & cast-expression that occurs 16925 // within a templated entity 16926 // -- a subexpression of one of the above that is not a subexpression of 16927 // a nested unevaluated operand. 16928 return true; 16929 16930 case Sema::ExpressionEvaluationContext::Unevaluated: 16931 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16932 // Expressions in this context are never evaluated. 16933 return false; 16934 } 16935 llvm_unreachable("Invalid context"); 16936 } 16937 16938 /// Return true if this function has a calling convention that requires mangling 16939 /// in the size of the parameter pack. 16940 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16941 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16942 // we don't need parameter type sizes. 16943 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16944 if (!TT.isOSWindows() || !TT.isX86()) 16945 return false; 16946 16947 // If this is C++ and this isn't an extern "C" function, parameters do not 16948 // need to be complete. In this case, C++ mangling will apply, which doesn't 16949 // use the size of the parameters. 16950 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16951 return false; 16952 16953 // Stdcall, fastcall, and vectorcall need this special treatment. 16954 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16955 switch (CC) { 16956 case CC_X86StdCall: 16957 case CC_X86FastCall: 16958 case CC_X86VectorCall: 16959 return true; 16960 default: 16961 break; 16962 } 16963 return false; 16964 } 16965 16966 /// Require that all of the parameter types of function be complete. Normally, 16967 /// parameter types are only required to be complete when a function is called 16968 /// or defined, but to mangle functions with certain calling conventions, the 16969 /// mangler needs to know the size of the parameter list. In this situation, 16970 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16971 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16972 /// result in a linker error. Clang doesn't implement this behavior, and instead 16973 /// attempts to error at compile time. 16974 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16975 SourceLocation Loc) { 16976 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16977 FunctionDecl *FD; 16978 ParmVarDecl *Param; 16979 16980 public: 16981 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16982 : FD(FD), Param(Param) {} 16983 16984 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16985 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16986 StringRef CCName; 16987 switch (CC) { 16988 case CC_X86StdCall: 16989 CCName = "stdcall"; 16990 break; 16991 case CC_X86FastCall: 16992 CCName = "fastcall"; 16993 break; 16994 case CC_X86VectorCall: 16995 CCName = "vectorcall"; 16996 break; 16997 default: 16998 llvm_unreachable("CC does not need mangling"); 16999 } 17000 17001 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 17002 << Param->getDeclName() << FD->getDeclName() << CCName; 17003 } 17004 }; 17005 17006 for (ParmVarDecl *Param : FD->parameters()) { 17007 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 17008 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 17009 } 17010 } 17011 17012 namespace { 17013 enum class OdrUseContext { 17014 /// Declarations in this context are not odr-used. 17015 None, 17016 /// Declarations in this context are formally odr-used, but this is a 17017 /// dependent context. 17018 Dependent, 17019 /// Declarations in this context are odr-used but not actually used (yet). 17020 FormallyOdrUsed, 17021 /// Declarations in this context are used. 17022 Used 17023 }; 17024 } 17025 17026 /// Are we within a context in which references to resolved functions or to 17027 /// variables result in odr-use? 17028 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 17029 OdrUseContext Result; 17030 17031 switch (SemaRef.ExprEvalContexts.back().Context) { 17032 case Sema::ExpressionEvaluationContext::Unevaluated: 17033 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17034 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17035 return OdrUseContext::None; 17036 17037 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17038 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17039 Result = OdrUseContext::Used; 17040 break; 17041 17042 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17043 Result = OdrUseContext::FormallyOdrUsed; 17044 break; 17045 17046 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17047 // A default argument formally results in odr-use, but doesn't actually 17048 // result in a use in any real sense until it itself is used. 17049 Result = OdrUseContext::FormallyOdrUsed; 17050 break; 17051 } 17052 17053 if (SemaRef.CurContext->isDependentContext()) 17054 return OdrUseContext::Dependent; 17055 17056 return Result; 17057 } 17058 17059 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 17060 if (!Func->isConstexpr()) 17061 return false; 17062 17063 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 17064 return true; 17065 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 17066 return CCD && CCD->getInheritedConstructor(); 17067 } 17068 17069 /// Mark a function referenced, and check whether it is odr-used 17070 /// (C++ [basic.def.odr]p2, C99 6.9p3) 17071 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 17072 bool MightBeOdrUse) { 17073 assert(Func && "No function?"); 17074 17075 Func->setReferenced(); 17076 17077 // Recursive functions aren't really used until they're used from some other 17078 // context. 17079 bool IsRecursiveCall = CurContext == Func; 17080 17081 // C++11 [basic.def.odr]p3: 17082 // A function whose name appears as a potentially-evaluated expression is 17083 // odr-used if it is the unique lookup result or the selected member of a 17084 // set of overloaded functions [...]. 17085 // 17086 // We (incorrectly) mark overload resolution as an unevaluated context, so we 17087 // can just check that here. 17088 OdrUseContext OdrUse = 17089 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 17090 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 17091 OdrUse = OdrUseContext::FormallyOdrUsed; 17092 17093 // Trivial default constructors and destructors are never actually used. 17094 // FIXME: What about other special members? 17095 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 17096 OdrUse == OdrUseContext::Used) { 17097 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 17098 if (Constructor->isDefaultConstructor()) 17099 OdrUse = OdrUseContext::FormallyOdrUsed; 17100 if (isa<CXXDestructorDecl>(Func)) 17101 OdrUse = OdrUseContext::FormallyOdrUsed; 17102 } 17103 17104 // C++20 [expr.const]p12: 17105 // A function [...] is needed for constant evaluation if it is [...] a 17106 // constexpr function that is named by an expression that is potentially 17107 // constant evaluated 17108 bool NeededForConstantEvaluation = 17109 isPotentiallyConstantEvaluatedContext(*this) && 17110 isImplicitlyDefinableConstexprFunction(Func); 17111 17112 // Determine whether we require a function definition to exist, per 17113 // C++11 [temp.inst]p3: 17114 // Unless a function template specialization has been explicitly 17115 // instantiated or explicitly specialized, the function template 17116 // specialization is implicitly instantiated when the specialization is 17117 // referenced in a context that requires a function definition to exist. 17118 // C++20 [temp.inst]p7: 17119 // The existence of a definition of a [...] function is considered to 17120 // affect the semantics of the program if the [...] function is needed for 17121 // constant evaluation by an expression 17122 // C++20 [basic.def.odr]p10: 17123 // Every program shall contain exactly one definition of every non-inline 17124 // function or variable that is odr-used in that program outside of a 17125 // discarded statement 17126 // C++20 [special]p1: 17127 // The implementation will implicitly define [defaulted special members] 17128 // if they are odr-used or needed for constant evaluation. 17129 // 17130 // Note that we skip the implicit instantiation of templates that are only 17131 // used in unused default arguments or by recursive calls to themselves. 17132 // This is formally non-conforming, but seems reasonable in practice. 17133 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 17134 NeededForConstantEvaluation); 17135 17136 // C++14 [temp.expl.spec]p6: 17137 // If a template [...] is explicitly specialized then that specialization 17138 // shall be declared before the first use of that specialization that would 17139 // cause an implicit instantiation to take place, in every translation unit 17140 // in which such a use occurs 17141 if (NeedDefinition && 17142 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 17143 Func->getMemberSpecializationInfo())) 17144 checkSpecializationVisibility(Loc, Func); 17145 17146 if (getLangOpts().CUDA) 17147 CheckCUDACall(Loc, Func); 17148 17149 if (getLangOpts().SYCLIsDevice) 17150 checkSYCLDeviceFunction(Loc, Func); 17151 17152 // If we need a definition, try to create one. 17153 if (NeedDefinition && !Func->getBody()) { 17154 runWithSufficientStackSpace(Loc, [&] { 17155 if (CXXConstructorDecl *Constructor = 17156 dyn_cast<CXXConstructorDecl>(Func)) { 17157 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 17158 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 17159 if (Constructor->isDefaultConstructor()) { 17160 if (Constructor->isTrivial() && 17161 !Constructor->hasAttr<DLLExportAttr>()) 17162 return; 17163 DefineImplicitDefaultConstructor(Loc, Constructor); 17164 } else if (Constructor->isCopyConstructor()) { 17165 DefineImplicitCopyConstructor(Loc, Constructor); 17166 } else if (Constructor->isMoveConstructor()) { 17167 DefineImplicitMoveConstructor(Loc, Constructor); 17168 } 17169 } else if (Constructor->getInheritedConstructor()) { 17170 DefineInheritingConstructor(Loc, Constructor); 17171 } 17172 } else if (CXXDestructorDecl *Destructor = 17173 dyn_cast<CXXDestructorDecl>(Func)) { 17174 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17175 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17176 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17177 return; 17178 DefineImplicitDestructor(Loc, Destructor); 17179 } 17180 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17181 MarkVTableUsed(Loc, Destructor->getParent()); 17182 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17183 if (MethodDecl->isOverloadedOperator() && 17184 MethodDecl->getOverloadedOperator() == OO_Equal) { 17185 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17186 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17187 if (MethodDecl->isCopyAssignmentOperator()) 17188 DefineImplicitCopyAssignment(Loc, MethodDecl); 17189 else if (MethodDecl->isMoveAssignmentOperator()) 17190 DefineImplicitMoveAssignment(Loc, MethodDecl); 17191 } 17192 } else if (isa<CXXConversionDecl>(MethodDecl) && 17193 MethodDecl->getParent()->isLambda()) { 17194 CXXConversionDecl *Conversion = 17195 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17196 if (Conversion->isLambdaToBlockPointerConversion()) 17197 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17198 else 17199 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17200 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17201 MarkVTableUsed(Loc, MethodDecl->getParent()); 17202 } 17203 17204 if (Func->isDefaulted() && !Func->isDeleted()) { 17205 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17206 if (DCK != DefaultedComparisonKind::None) 17207 DefineDefaultedComparison(Loc, Func, DCK); 17208 } 17209 17210 // Implicit instantiation of function templates and member functions of 17211 // class templates. 17212 if (Func->isImplicitlyInstantiable()) { 17213 TemplateSpecializationKind TSK = 17214 Func->getTemplateSpecializationKindForInstantiation(); 17215 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17216 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17217 if (FirstInstantiation) { 17218 PointOfInstantiation = Loc; 17219 if (auto *MSI = Func->getMemberSpecializationInfo()) 17220 MSI->setPointOfInstantiation(Loc); 17221 // FIXME: Notify listener. 17222 else 17223 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17224 } else if (TSK != TSK_ImplicitInstantiation) { 17225 // Use the point of use as the point of instantiation, instead of the 17226 // point of explicit instantiation (which we track as the actual point 17227 // of instantiation). This gives better backtraces in diagnostics. 17228 PointOfInstantiation = Loc; 17229 } 17230 17231 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17232 Func->isConstexpr()) { 17233 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17234 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17235 CodeSynthesisContexts.size()) 17236 PendingLocalImplicitInstantiations.push_back( 17237 std::make_pair(Func, PointOfInstantiation)); 17238 else if (Func->isConstexpr()) 17239 // Do not defer instantiations of constexpr functions, to avoid the 17240 // expression evaluator needing to call back into Sema if it sees a 17241 // call to such a function. 17242 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17243 else { 17244 Func->setInstantiationIsPending(true); 17245 PendingInstantiations.push_back( 17246 std::make_pair(Func, PointOfInstantiation)); 17247 // Notify the consumer that a function was implicitly instantiated. 17248 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17249 } 17250 } 17251 } else { 17252 // Walk redefinitions, as some of them may be instantiable. 17253 for (auto i : Func->redecls()) { 17254 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17255 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17256 } 17257 } 17258 }); 17259 } 17260 17261 // C++14 [except.spec]p17: 17262 // An exception-specification is considered to be needed when: 17263 // - the function is odr-used or, if it appears in an unevaluated operand, 17264 // would be odr-used if the expression were potentially-evaluated; 17265 // 17266 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17267 // function is a pure virtual function we're calling, and in that case the 17268 // function was selected by overload resolution and we need to resolve its 17269 // exception specification for a different reason. 17270 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17271 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17272 ResolveExceptionSpec(Loc, FPT); 17273 17274 // If this is the first "real" use, act on that. 17275 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17276 // Keep track of used but undefined functions. 17277 if (!Func->isDefined()) { 17278 if (mightHaveNonExternalLinkage(Func)) 17279 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17280 else if (Func->getMostRecentDecl()->isInlined() && 17281 !LangOpts.GNUInline && 17282 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17283 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17284 else if (isExternalWithNoLinkageType(Func)) 17285 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17286 } 17287 17288 // Some x86 Windows calling conventions mangle the size of the parameter 17289 // pack into the name. Computing the size of the parameters requires the 17290 // parameter types to be complete. Check that now. 17291 if (funcHasParameterSizeMangling(*this, Func)) 17292 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17293 17294 // In the MS C++ ABI, the compiler emits destructor variants where they are 17295 // used. If the destructor is used here but defined elsewhere, mark the 17296 // virtual base destructors referenced. If those virtual base destructors 17297 // are inline, this will ensure they are defined when emitting the complete 17298 // destructor variant. This checking may be redundant if the destructor is 17299 // provided later in this TU. 17300 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17301 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17302 CXXRecordDecl *Parent = Dtor->getParent(); 17303 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17304 CheckCompleteDestructorVariant(Loc, Dtor); 17305 } 17306 } 17307 17308 Func->markUsed(Context); 17309 } 17310 } 17311 17312 /// Directly mark a variable odr-used. Given a choice, prefer to use 17313 /// MarkVariableReferenced since it does additional checks and then 17314 /// calls MarkVarDeclODRUsed. 17315 /// If the variable must be captured: 17316 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17317 /// - else capture it in the DeclContext that maps to the 17318 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17319 static void 17320 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17321 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17322 // Keep track of used but undefined variables. 17323 // FIXME: We shouldn't suppress this warning for static data members. 17324 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17325 (!Var->isExternallyVisible() || Var->isInline() || 17326 SemaRef.isExternalWithNoLinkageType(Var)) && 17327 !(Var->isStaticDataMember() && Var->hasInit())) { 17328 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17329 if (old.isInvalid()) 17330 old = Loc; 17331 } 17332 QualType CaptureType, DeclRefType; 17333 if (SemaRef.LangOpts.OpenMP) 17334 SemaRef.tryCaptureOpenMPLambdas(Var); 17335 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17336 /*EllipsisLoc*/ SourceLocation(), 17337 /*BuildAndDiagnose*/ true, 17338 CaptureType, DeclRefType, 17339 FunctionScopeIndexToStopAt); 17340 17341 if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) { 17342 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 17343 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 17344 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 17345 if (VarTarget == Sema::CVT_Host && 17346 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 17347 UserTarget == Sema::CFT_Global)) { 17348 // Diagnose ODR-use of host global variables in device functions. 17349 // Reference of device global variables in host functions is allowed 17350 // through shadow variables therefore it is not diagnosed. 17351 if (SemaRef.LangOpts.CUDAIsDevice) { 17352 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 17353 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 17354 SemaRef.targetDiag(Var->getLocation(), 17355 Var->getType().isConstQualified() 17356 ? diag::note_cuda_const_var_unpromoted 17357 : diag::note_cuda_host_var); 17358 } 17359 } else if (VarTarget == Sema::CVT_Device && 17360 (UserTarget == Sema::CFT_Host || 17361 UserTarget == Sema::CFT_HostDevice) && 17362 !Var->hasExternalStorage()) { 17363 // Record a CUDA/HIP device side variable if it is ODR-used 17364 // by host code. This is done conservatively, when the variable is 17365 // referenced in any of the following contexts: 17366 // - a non-function context 17367 // - a host function 17368 // - a host device function 17369 // This makes the ODR-use of the device side variable by host code to 17370 // be visible in the device compilation for the compiler to be able to 17371 // emit template variables instantiated by host code only and to 17372 // externalize the static device side variable ODR-used by host code. 17373 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 17374 } 17375 } 17376 17377 Var->markUsed(SemaRef.Context); 17378 } 17379 17380 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17381 SourceLocation Loc, 17382 unsigned CapturingScopeIndex) { 17383 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17384 } 17385 17386 static void 17387 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17388 ValueDecl *var, DeclContext *DC) { 17389 DeclContext *VarDC = var->getDeclContext(); 17390 17391 // If the parameter still belongs to the translation unit, then 17392 // we're actually just using one parameter in the declaration of 17393 // the next. 17394 if (isa<ParmVarDecl>(var) && 17395 isa<TranslationUnitDecl>(VarDC)) 17396 return; 17397 17398 // For C code, don't diagnose about capture if we're not actually in code 17399 // right now; it's impossible to write a non-constant expression outside of 17400 // function context, so we'll get other (more useful) diagnostics later. 17401 // 17402 // For C++, things get a bit more nasty... it would be nice to suppress this 17403 // diagnostic for certain cases like using a local variable in an array bound 17404 // for a member of a local class, but the correct predicate is not obvious. 17405 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17406 return; 17407 17408 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17409 unsigned ContextKind = 3; // unknown 17410 if (isa<CXXMethodDecl>(VarDC) && 17411 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17412 ContextKind = 2; 17413 } else if (isa<FunctionDecl>(VarDC)) { 17414 ContextKind = 0; 17415 } else if (isa<BlockDecl>(VarDC)) { 17416 ContextKind = 1; 17417 } 17418 17419 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17420 << var << ValueKind << ContextKind << VarDC; 17421 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17422 << var; 17423 17424 // FIXME: Add additional diagnostic info about class etc. which prevents 17425 // capture. 17426 } 17427 17428 17429 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17430 bool &SubCapturesAreNested, 17431 QualType &CaptureType, 17432 QualType &DeclRefType) { 17433 // Check whether we've already captured it. 17434 if (CSI->CaptureMap.count(Var)) { 17435 // If we found a capture, any subcaptures are nested. 17436 SubCapturesAreNested = true; 17437 17438 // Retrieve the capture type for this variable. 17439 CaptureType = CSI->getCapture(Var).getCaptureType(); 17440 17441 // Compute the type of an expression that refers to this variable. 17442 DeclRefType = CaptureType.getNonReferenceType(); 17443 17444 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17445 // are mutable in the sense that user can change their value - they are 17446 // private instances of the captured declarations. 17447 const Capture &Cap = CSI->getCapture(Var); 17448 if (Cap.isCopyCapture() && 17449 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17450 !(isa<CapturedRegionScopeInfo>(CSI) && 17451 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17452 DeclRefType.addConst(); 17453 return true; 17454 } 17455 return false; 17456 } 17457 17458 // Only block literals, captured statements, and lambda expressions can 17459 // capture; other scopes don't work. 17460 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17461 SourceLocation Loc, 17462 const bool Diagnose, Sema &S) { 17463 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17464 return getLambdaAwareParentOfDeclContext(DC); 17465 else if (Var->hasLocalStorage()) { 17466 if (Diagnose) 17467 diagnoseUncapturableValueReference(S, Loc, Var, DC); 17468 } 17469 return nullptr; 17470 } 17471 17472 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17473 // certain types of variables (unnamed, variably modified types etc.) 17474 // so check for eligibility. 17475 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17476 SourceLocation Loc, 17477 const bool Diagnose, Sema &S) { 17478 17479 bool IsBlock = isa<BlockScopeInfo>(CSI); 17480 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17481 17482 // Lambdas are not allowed to capture unnamed variables 17483 // (e.g. anonymous unions). 17484 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17485 // assuming that's the intent. 17486 if (IsLambda && !Var->getDeclName()) { 17487 if (Diagnose) { 17488 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17489 S.Diag(Var->getLocation(), diag::note_declared_at); 17490 } 17491 return false; 17492 } 17493 17494 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17495 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17496 if (Diagnose) { 17497 S.Diag(Loc, diag::err_ref_vm_type); 17498 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17499 } 17500 return false; 17501 } 17502 // Prohibit structs with flexible array members too. 17503 // We cannot capture what is in the tail end of the struct. 17504 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17505 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17506 if (Diagnose) { 17507 if (IsBlock) 17508 S.Diag(Loc, diag::err_ref_flexarray_type); 17509 else 17510 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17511 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17512 } 17513 return false; 17514 } 17515 } 17516 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17517 // Lambdas and captured statements are not allowed to capture __block 17518 // variables; they don't support the expected semantics. 17519 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17520 if (Diagnose) { 17521 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17522 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17523 } 17524 return false; 17525 } 17526 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17527 if (S.getLangOpts().OpenCL && IsBlock && 17528 Var->getType()->isBlockPointerType()) { 17529 if (Diagnose) 17530 S.Diag(Loc, diag::err_opencl_block_ref_block); 17531 return false; 17532 } 17533 17534 return true; 17535 } 17536 17537 // Returns true if the capture by block was successful. 17538 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17539 SourceLocation Loc, 17540 const bool BuildAndDiagnose, 17541 QualType &CaptureType, 17542 QualType &DeclRefType, 17543 const bool Nested, 17544 Sema &S, bool Invalid) { 17545 bool ByRef = false; 17546 17547 // Blocks are not allowed to capture arrays, excepting OpenCL. 17548 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17549 // (decayed to pointers). 17550 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17551 if (BuildAndDiagnose) { 17552 S.Diag(Loc, diag::err_ref_array_type); 17553 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17554 Invalid = true; 17555 } else { 17556 return false; 17557 } 17558 } 17559 17560 // Forbid the block-capture of autoreleasing variables. 17561 if (!Invalid && 17562 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17563 if (BuildAndDiagnose) { 17564 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17565 << /*block*/ 0; 17566 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17567 Invalid = true; 17568 } else { 17569 return false; 17570 } 17571 } 17572 17573 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17574 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17575 QualType PointeeTy = PT->getPointeeType(); 17576 17577 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17578 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17579 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17580 if (BuildAndDiagnose) { 17581 SourceLocation VarLoc = Var->getLocation(); 17582 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17583 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17584 } 17585 } 17586 } 17587 17588 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17589 if (HasBlocksAttr || CaptureType->isReferenceType() || 17590 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17591 // Block capture by reference does not change the capture or 17592 // declaration reference types. 17593 ByRef = true; 17594 } else { 17595 // Block capture by copy introduces 'const'. 17596 CaptureType = CaptureType.getNonReferenceType().withConst(); 17597 DeclRefType = CaptureType; 17598 } 17599 17600 // Actually capture the variable. 17601 if (BuildAndDiagnose) 17602 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17603 CaptureType, Invalid); 17604 17605 return !Invalid; 17606 } 17607 17608 17609 /// Capture the given variable in the captured region. 17610 static bool captureInCapturedRegion( 17611 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 17612 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 17613 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 17614 bool IsTopScope, Sema &S, bool Invalid) { 17615 // By default, capture variables by reference. 17616 bool ByRef = true; 17617 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17618 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17619 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17620 // Using an LValue reference type is consistent with Lambdas (see below). 17621 if (S.isOpenMPCapturedDecl(Var)) { 17622 bool HasConst = DeclRefType.isConstQualified(); 17623 DeclRefType = DeclRefType.getUnqualifiedType(); 17624 // Don't lose diagnostics about assignments to const. 17625 if (HasConst) 17626 DeclRefType.addConst(); 17627 } 17628 // Do not capture firstprivates in tasks. 17629 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17630 OMPC_unknown) 17631 return true; 17632 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17633 RSI->OpenMPCaptureLevel); 17634 } 17635 17636 if (ByRef) 17637 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17638 else 17639 CaptureType = DeclRefType; 17640 17641 // Actually capture the variable. 17642 if (BuildAndDiagnose) 17643 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17644 Loc, SourceLocation(), CaptureType, Invalid); 17645 17646 return !Invalid; 17647 } 17648 17649 /// Capture the given variable in the lambda. 17650 static bool captureInLambda(LambdaScopeInfo *LSI, 17651 VarDecl *Var, 17652 SourceLocation Loc, 17653 const bool BuildAndDiagnose, 17654 QualType &CaptureType, 17655 QualType &DeclRefType, 17656 const bool RefersToCapturedVariable, 17657 const Sema::TryCaptureKind Kind, 17658 SourceLocation EllipsisLoc, 17659 const bool IsTopScope, 17660 Sema &S, bool Invalid) { 17661 // Determine whether we are capturing by reference or by value. 17662 bool ByRef = false; 17663 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17664 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17665 } else { 17666 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17667 } 17668 17669 // Compute the type of the field that will capture this variable. 17670 if (ByRef) { 17671 // C++11 [expr.prim.lambda]p15: 17672 // An entity is captured by reference if it is implicitly or 17673 // explicitly captured but not captured by copy. It is 17674 // unspecified whether additional unnamed non-static data 17675 // members are declared in the closure type for entities 17676 // captured by reference. 17677 // 17678 // FIXME: It is not clear whether we want to build an lvalue reference 17679 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17680 // to do the former, while EDG does the latter. Core issue 1249 will 17681 // clarify, but for now we follow GCC because it's a more permissive and 17682 // easily defensible position. 17683 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17684 } else { 17685 // C++11 [expr.prim.lambda]p14: 17686 // For each entity captured by copy, an unnamed non-static 17687 // data member is declared in the closure type. The 17688 // declaration order of these members is unspecified. The type 17689 // of such a data member is the type of the corresponding 17690 // captured entity if the entity is not a reference to an 17691 // object, or the referenced type otherwise. [Note: If the 17692 // captured entity is a reference to a function, the 17693 // corresponding data member is also a reference to a 17694 // function. - end note ] 17695 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17696 if (!RefType->getPointeeType()->isFunctionType()) 17697 CaptureType = RefType->getPointeeType(); 17698 } 17699 17700 // Forbid the lambda copy-capture of autoreleasing variables. 17701 if (!Invalid && 17702 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17703 if (BuildAndDiagnose) { 17704 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17705 S.Diag(Var->getLocation(), diag::note_previous_decl) 17706 << Var->getDeclName(); 17707 Invalid = true; 17708 } else { 17709 return false; 17710 } 17711 } 17712 17713 // Make sure that by-copy captures are of a complete and non-abstract type. 17714 if (!Invalid && BuildAndDiagnose) { 17715 if (!CaptureType->isDependentType() && 17716 S.RequireCompleteSizedType( 17717 Loc, CaptureType, 17718 diag::err_capture_of_incomplete_or_sizeless_type, 17719 Var->getDeclName())) 17720 Invalid = true; 17721 else if (S.RequireNonAbstractType(Loc, CaptureType, 17722 diag::err_capture_of_abstract_type)) 17723 Invalid = true; 17724 } 17725 } 17726 17727 // Compute the type of a reference to this captured variable. 17728 if (ByRef) 17729 DeclRefType = CaptureType.getNonReferenceType(); 17730 else { 17731 // C++ [expr.prim.lambda]p5: 17732 // The closure type for a lambda-expression has a public inline 17733 // function call operator [...]. This function call operator is 17734 // declared const (9.3.1) if and only if the lambda-expression's 17735 // parameter-declaration-clause is not followed by mutable. 17736 DeclRefType = CaptureType.getNonReferenceType(); 17737 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17738 DeclRefType.addConst(); 17739 } 17740 17741 // Add the capture. 17742 if (BuildAndDiagnose) 17743 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17744 Loc, EllipsisLoc, CaptureType, Invalid); 17745 17746 return !Invalid; 17747 } 17748 17749 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 17750 // Offer a Copy fix even if the type is dependent. 17751 if (Var->getType()->isDependentType()) 17752 return true; 17753 QualType T = Var->getType().getNonReferenceType(); 17754 if (T.isTriviallyCopyableType(Context)) 17755 return true; 17756 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 17757 17758 if (!(RD = RD->getDefinition())) 17759 return false; 17760 if (RD->hasSimpleCopyConstructor()) 17761 return true; 17762 if (RD->hasUserDeclaredCopyConstructor()) 17763 for (CXXConstructorDecl *Ctor : RD->ctors()) 17764 if (Ctor->isCopyConstructor()) 17765 return !Ctor->isDeleted(); 17766 } 17767 return false; 17768 } 17769 17770 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 17771 /// default capture. Fixes may be omitted if they aren't allowed by the 17772 /// standard, for example we can't emit a default copy capture fix-it if we 17773 /// already explicitly copy capture capture another variable. 17774 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 17775 VarDecl *Var) { 17776 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 17777 // Don't offer Capture by copy of default capture by copy fixes if Var is 17778 // known not to be copy constructible. 17779 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 17780 17781 SmallString<32> FixBuffer; 17782 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 17783 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 17784 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 17785 if (ShouldOfferCopyFix) { 17786 // Offer fixes to insert an explicit capture for the variable. 17787 // [] -> [VarName] 17788 // [OtherCapture] -> [OtherCapture, VarName] 17789 FixBuffer.assign({Separator, Var->getName()}); 17790 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17791 << Var << /*value*/ 0 17792 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17793 } 17794 // As above but capture by reference. 17795 FixBuffer.assign({Separator, "&", Var->getName()}); 17796 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17797 << Var << /*reference*/ 1 17798 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17799 } 17800 17801 // Only try to offer default capture if there are no captures excluding this 17802 // and init captures. 17803 // [this]: OK. 17804 // [X = Y]: OK. 17805 // [&A, &B]: Don't offer. 17806 // [A, B]: Don't offer. 17807 if (llvm::any_of(LSI->Captures, [](Capture &C) { 17808 return !C.isThisCapture() && !C.isInitCapture(); 17809 })) 17810 return; 17811 17812 // The default capture specifiers, '=' or '&', must appear first in the 17813 // capture body. 17814 SourceLocation DefaultInsertLoc = 17815 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 17816 17817 if (ShouldOfferCopyFix) { 17818 bool CanDefaultCopyCapture = true; 17819 // [=, *this] OK since c++17 17820 // [=, this] OK since c++20 17821 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 17822 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 17823 ? LSI->getCXXThisCapture().isCopyCapture() 17824 : false; 17825 // We can't use default capture by copy if any captures already specified 17826 // capture by copy. 17827 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 17828 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 17829 })) { 17830 FixBuffer.assign({"=", Separator}); 17831 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17832 << /*value*/ 0 17833 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17834 } 17835 } 17836 17837 // We can't use default capture by reference if any captures already specified 17838 // capture by reference. 17839 if (llvm::none_of(LSI->Captures, [](Capture &C) { 17840 return !C.isInitCapture() && C.isReferenceCapture() && 17841 !C.isThisCapture(); 17842 })) { 17843 FixBuffer.assign({"&", Separator}); 17844 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17845 << /*reference*/ 1 17846 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17847 } 17848 } 17849 17850 bool Sema::tryCaptureVariable( 17851 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17852 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17853 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17854 // An init-capture is notionally from the context surrounding its 17855 // declaration, but its parent DC is the lambda class. 17856 DeclContext *VarDC = Var->getDeclContext(); 17857 if (Var->isInitCapture()) 17858 VarDC = VarDC->getParent(); 17859 17860 DeclContext *DC = CurContext; 17861 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17862 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17863 // We need to sync up the Declaration Context with the 17864 // FunctionScopeIndexToStopAt 17865 if (FunctionScopeIndexToStopAt) { 17866 unsigned FSIndex = FunctionScopes.size() - 1; 17867 while (FSIndex != MaxFunctionScopesIndex) { 17868 DC = getLambdaAwareParentOfDeclContext(DC); 17869 --FSIndex; 17870 } 17871 } 17872 17873 17874 // If the variable is declared in the current context, there is no need to 17875 // capture it. 17876 if (VarDC == DC) return true; 17877 17878 // Capture global variables if it is required to use private copy of this 17879 // variable. 17880 bool IsGlobal = !Var->hasLocalStorage(); 17881 if (IsGlobal && 17882 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17883 MaxFunctionScopesIndex))) 17884 return true; 17885 Var = Var->getCanonicalDecl(); 17886 17887 // Walk up the stack to determine whether we can capture the variable, 17888 // performing the "simple" checks that don't depend on type. We stop when 17889 // we've either hit the declared scope of the variable or find an existing 17890 // capture of that variable. We start from the innermost capturing-entity 17891 // (the DC) and ensure that all intervening capturing-entities 17892 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17893 // declcontext can either capture the variable or have already captured 17894 // the variable. 17895 CaptureType = Var->getType(); 17896 DeclRefType = CaptureType.getNonReferenceType(); 17897 bool Nested = false; 17898 bool Explicit = (Kind != TryCapture_Implicit); 17899 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17900 do { 17901 // Only block literals, captured statements, and lambda expressions can 17902 // capture; other scopes don't work. 17903 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17904 ExprLoc, 17905 BuildAndDiagnose, 17906 *this); 17907 // We need to check for the parent *first* because, if we *have* 17908 // private-captured a global variable, we need to recursively capture it in 17909 // intermediate blocks, lambdas, etc. 17910 if (!ParentDC) { 17911 if (IsGlobal) { 17912 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17913 break; 17914 } 17915 return true; 17916 } 17917 17918 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17919 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17920 17921 17922 // Check whether we've already captured it. 17923 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17924 DeclRefType)) { 17925 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17926 break; 17927 } 17928 // If we are instantiating a generic lambda call operator body, 17929 // we do not want to capture new variables. What was captured 17930 // during either a lambdas transformation or initial parsing 17931 // should be used. 17932 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17933 if (BuildAndDiagnose) { 17934 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17935 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17936 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17937 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17938 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17939 buildLambdaCaptureFixit(*this, LSI, Var); 17940 } else 17941 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17942 } 17943 return true; 17944 } 17945 17946 // Try to capture variable-length arrays types. 17947 if (Var->getType()->isVariablyModifiedType()) { 17948 // We're going to walk down into the type and look for VLA 17949 // expressions. 17950 QualType QTy = Var->getType(); 17951 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17952 QTy = PVD->getOriginalType(); 17953 captureVariablyModifiedType(Context, QTy, CSI); 17954 } 17955 17956 if (getLangOpts().OpenMP) { 17957 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17958 // OpenMP private variables should not be captured in outer scope, so 17959 // just break here. Similarly, global variables that are captured in a 17960 // target region should not be captured outside the scope of the region. 17961 if (RSI->CapRegionKind == CR_OpenMP) { 17962 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17963 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17964 // If the variable is private (i.e. not captured) and has variably 17965 // modified type, we still need to capture the type for correct 17966 // codegen in all regions, associated with the construct. Currently, 17967 // it is captured in the innermost captured region only. 17968 if (IsOpenMPPrivateDecl != OMPC_unknown && 17969 Var->getType()->isVariablyModifiedType()) { 17970 QualType QTy = Var->getType(); 17971 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17972 QTy = PVD->getOriginalType(); 17973 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17974 I < E; ++I) { 17975 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17976 FunctionScopes[FunctionScopesIndex - I]); 17977 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17978 "Wrong number of captured regions associated with the " 17979 "OpenMP construct."); 17980 captureVariablyModifiedType(Context, QTy, OuterRSI); 17981 } 17982 } 17983 bool IsTargetCap = 17984 IsOpenMPPrivateDecl != OMPC_private && 17985 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17986 RSI->OpenMPCaptureLevel); 17987 // Do not capture global if it is not privatized in outer regions. 17988 bool IsGlobalCap = 17989 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17990 RSI->OpenMPCaptureLevel); 17991 17992 // When we detect target captures we are looking from inside the 17993 // target region, therefore we need to propagate the capture from the 17994 // enclosing region. Therefore, the capture is not initially nested. 17995 if (IsTargetCap) 17996 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17997 17998 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17999 (IsGlobal && !IsGlobalCap)) { 18000 Nested = !IsTargetCap; 18001 bool HasConst = DeclRefType.isConstQualified(); 18002 DeclRefType = DeclRefType.getUnqualifiedType(); 18003 // Don't lose diagnostics about assignments to const. 18004 if (HasConst) 18005 DeclRefType.addConst(); 18006 CaptureType = Context.getLValueReferenceType(DeclRefType); 18007 break; 18008 } 18009 } 18010 } 18011 } 18012 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 18013 // No capture-default, and this is not an explicit capture 18014 // so cannot capture this variable. 18015 if (BuildAndDiagnose) { 18016 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18017 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18018 auto *LSI = cast<LambdaScopeInfo>(CSI); 18019 if (LSI->Lambda) { 18020 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18021 buildLambdaCaptureFixit(*this, LSI, Var); 18022 } 18023 // FIXME: If we error out because an outer lambda can not implicitly 18024 // capture a variable that an inner lambda explicitly captures, we 18025 // should have the inner lambda do the explicit capture - because 18026 // it makes for cleaner diagnostics later. This would purely be done 18027 // so that the diagnostic does not misleadingly claim that a variable 18028 // can not be captured by a lambda implicitly even though it is captured 18029 // explicitly. Suggestion: 18030 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 18031 // at the function head 18032 // - cache the StartingDeclContext - this must be a lambda 18033 // - captureInLambda in the innermost lambda the variable. 18034 } 18035 return true; 18036 } 18037 18038 FunctionScopesIndex--; 18039 DC = ParentDC; 18040 Explicit = false; 18041 } while (!VarDC->Equals(DC)); 18042 18043 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 18044 // computing the type of the capture at each step, checking type-specific 18045 // requirements, and adding captures if requested. 18046 // If the variable had already been captured previously, we start capturing 18047 // at the lambda nested within that one. 18048 bool Invalid = false; 18049 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 18050 ++I) { 18051 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 18052 18053 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18054 // certain types of variables (unnamed, variably modified types etc.) 18055 // so check for eligibility. 18056 if (!Invalid) 18057 Invalid = 18058 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 18059 18060 // After encountering an error, if we're actually supposed to capture, keep 18061 // capturing in nested contexts to suppress any follow-on diagnostics. 18062 if (Invalid && !BuildAndDiagnose) 18063 return true; 18064 18065 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 18066 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18067 DeclRefType, Nested, *this, Invalid); 18068 Nested = true; 18069 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18070 Invalid = !captureInCapturedRegion( 18071 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 18072 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 18073 Nested = true; 18074 } else { 18075 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18076 Invalid = 18077 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18078 DeclRefType, Nested, Kind, EllipsisLoc, 18079 /*IsTopScope*/ I == N - 1, *this, Invalid); 18080 Nested = true; 18081 } 18082 18083 if (Invalid && !BuildAndDiagnose) 18084 return true; 18085 } 18086 return Invalid; 18087 } 18088 18089 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 18090 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 18091 QualType CaptureType; 18092 QualType DeclRefType; 18093 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 18094 /*BuildAndDiagnose=*/true, CaptureType, 18095 DeclRefType, nullptr); 18096 } 18097 18098 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 18099 QualType CaptureType; 18100 QualType DeclRefType; 18101 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18102 /*BuildAndDiagnose=*/false, CaptureType, 18103 DeclRefType, nullptr); 18104 } 18105 18106 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 18107 QualType CaptureType; 18108 QualType DeclRefType; 18109 18110 // Determine whether we can capture this variable. 18111 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18112 /*BuildAndDiagnose=*/false, CaptureType, 18113 DeclRefType, nullptr)) 18114 return QualType(); 18115 18116 return DeclRefType; 18117 } 18118 18119 namespace { 18120 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 18121 // The produced TemplateArgumentListInfo* points to data stored within this 18122 // object, so should only be used in contexts where the pointer will not be 18123 // used after the CopiedTemplateArgs object is destroyed. 18124 class CopiedTemplateArgs { 18125 bool HasArgs; 18126 TemplateArgumentListInfo TemplateArgStorage; 18127 public: 18128 template<typename RefExpr> 18129 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 18130 if (HasArgs) 18131 E->copyTemplateArgumentsInto(TemplateArgStorage); 18132 } 18133 operator TemplateArgumentListInfo*() 18134 #ifdef __has_cpp_attribute 18135 #if __has_cpp_attribute(clang::lifetimebound) 18136 [[clang::lifetimebound]] 18137 #endif 18138 #endif 18139 { 18140 return HasArgs ? &TemplateArgStorage : nullptr; 18141 } 18142 }; 18143 } 18144 18145 /// Walk the set of potential results of an expression and mark them all as 18146 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 18147 /// 18148 /// \return A new expression if we found any potential results, ExprEmpty() if 18149 /// not, and ExprError() if we diagnosed an error. 18150 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 18151 NonOdrUseReason NOUR) { 18152 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 18153 // an object that satisfies the requirements for appearing in a 18154 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 18155 // is immediately applied." This function handles the lvalue-to-rvalue 18156 // conversion part. 18157 // 18158 // If we encounter a node that claims to be an odr-use but shouldn't be, we 18159 // transform it into the relevant kind of non-odr-use node and rebuild the 18160 // tree of nodes leading to it. 18161 // 18162 // This is a mini-TreeTransform that only transforms a restricted subset of 18163 // nodes (and only certain operands of them). 18164 18165 // Rebuild a subexpression. 18166 auto Rebuild = [&](Expr *Sub) { 18167 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 18168 }; 18169 18170 // Check whether a potential result satisfies the requirements of NOUR. 18171 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 18172 // Any entity other than a VarDecl is always odr-used whenever it's named 18173 // in a potentially-evaluated expression. 18174 auto *VD = dyn_cast<VarDecl>(D); 18175 if (!VD) 18176 return true; 18177 18178 // C++2a [basic.def.odr]p4: 18179 // A variable x whose name appears as a potentially-evalauted expression 18180 // e is odr-used by e unless 18181 // -- x is a reference that is usable in constant expressions, or 18182 // -- x is a variable of non-reference type that is usable in constant 18183 // expressions and has no mutable subobjects, and e is an element of 18184 // the set of potential results of an expression of 18185 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18186 // conversion is applied, or 18187 // -- x is a variable of non-reference type, and e is an element of the 18188 // set of potential results of a discarded-value expression to which 18189 // the lvalue-to-rvalue conversion is not applied 18190 // 18191 // We check the first bullet and the "potentially-evaluated" condition in 18192 // BuildDeclRefExpr. We check the type requirements in the second bullet 18193 // in CheckLValueToRValueConversionOperand below. 18194 switch (NOUR) { 18195 case NOUR_None: 18196 case NOUR_Unevaluated: 18197 llvm_unreachable("unexpected non-odr-use-reason"); 18198 18199 case NOUR_Constant: 18200 // Constant references were handled when they were built. 18201 if (VD->getType()->isReferenceType()) 18202 return true; 18203 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18204 if (RD->hasMutableFields()) 18205 return true; 18206 if (!VD->isUsableInConstantExpressions(S.Context)) 18207 return true; 18208 break; 18209 18210 case NOUR_Discarded: 18211 if (VD->getType()->isReferenceType()) 18212 return true; 18213 break; 18214 } 18215 return false; 18216 }; 18217 18218 // Mark that this expression does not constitute an odr-use. 18219 auto MarkNotOdrUsed = [&] { 18220 S.MaybeODRUseExprs.remove(E); 18221 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18222 LSI->markVariableExprAsNonODRUsed(E); 18223 }; 18224 18225 // C++2a [basic.def.odr]p2: 18226 // The set of potential results of an expression e is defined as follows: 18227 switch (E->getStmtClass()) { 18228 // -- If e is an id-expression, ... 18229 case Expr::DeclRefExprClass: { 18230 auto *DRE = cast<DeclRefExpr>(E); 18231 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18232 break; 18233 18234 // Rebuild as a non-odr-use DeclRefExpr. 18235 MarkNotOdrUsed(); 18236 return DeclRefExpr::Create( 18237 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18238 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18239 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18240 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18241 } 18242 18243 case Expr::FunctionParmPackExprClass: { 18244 auto *FPPE = cast<FunctionParmPackExpr>(E); 18245 // If any of the declarations in the pack is odr-used, then the expression 18246 // as a whole constitutes an odr-use. 18247 for (VarDecl *D : *FPPE) 18248 if (IsPotentialResultOdrUsed(D)) 18249 return ExprEmpty(); 18250 18251 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18252 // nothing cares about whether we marked this as an odr-use, but it might 18253 // be useful for non-compiler tools. 18254 MarkNotOdrUsed(); 18255 break; 18256 } 18257 18258 // -- If e is a subscripting operation with an array operand... 18259 case Expr::ArraySubscriptExprClass: { 18260 auto *ASE = cast<ArraySubscriptExpr>(E); 18261 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18262 if (!OldBase->getType()->isArrayType()) 18263 break; 18264 ExprResult Base = Rebuild(OldBase); 18265 if (!Base.isUsable()) 18266 return Base; 18267 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18268 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18269 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18270 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18271 ASE->getRBracketLoc()); 18272 } 18273 18274 case Expr::MemberExprClass: { 18275 auto *ME = cast<MemberExpr>(E); 18276 // -- If e is a class member access expression [...] naming a non-static 18277 // data member... 18278 if (isa<FieldDecl>(ME->getMemberDecl())) { 18279 ExprResult Base = Rebuild(ME->getBase()); 18280 if (!Base.isUsable()) 18281 return Base; 18282 return MemberExpr::Create( 18283 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18284 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18285 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18286 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18287 ME->getObjectKind(), ME->isNonOdrUse()); 18288 } 18289 18290 if (ME->getMemberDecl()->isCXXInstanceMember()) 18291 break; 18292 18293 // -- If e is a class member access expression naming a static data member, 18294 // ... 18295 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18296 break; 18297 18298 // Rebuild as a non-odr-use MemberExpr. 18299 MarkNotOdrUsed(); 18300 return MemberExpr::Create( 18301 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 18302 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 18303 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 18304 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 18305 } 18306 18307 case Expr::BinaryOperatorClass: { 18308 auto *BO = cast<BinaryOperator>(E); 18309 Expr *LHS = BO->getLHS(); 18310 Expr *RHS = BO->getRHS(); 18311 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18312 if (BO->getOpcode() == BO_PtrMemD) { 18313 ExprResult Sub = Rebuild(LHS); 18314 if (!Sub.isUsable()) 18315 return Sub; 18316 LHS = Sub.get(); 18317 // -- If e is a comma expression, ... 18318 } else if (BO->getOpcode() == BO_Comma) { 18319 ExprResult Sub = Rebuild(RHS); 18320 if (!Sub.isUsable()) 18321 return Sub; 18322 RHS = Sub.get(); 18323 } else { 18324 break; 18325 } 18326 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18327 LHS, RHS); 18328 } 18329 18330 // -- If e has the form (e1)... 18331 case Expr::ParenExprClass: { 18332 auto *PE = cast<ParenExpr>(E); 18333 ExprResult Sub = Rebuild(PE->getSubExpr()); 18334 if (!Sub.isUsable()) 18335 return Sub; 18336 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18337 } 18338 18339 // -- If e is a glvalue conditional expression, ... 18340 // We don't apply this to a binary conditional operator. FIXME: Should we? 18341 case Expr::ConditionalOperatorClass: { 18342 auto *CO = cast<ConditionalOperator>(E); 18343 ExprResult LHS = Rebuild(CO->getLHS()); 18344 if (LHS.isInvalid()) 18345 return ExprError(); 18346 ExprResult RHS = Rebuild(CO->getRHS()); 18347 if (RHS.isInvalid()) 18348 return ExprError(); 18349 if (!LHS.isUsable() && !RHS.isUsable()) 18350 return ExprEmpty(); 18351 if (!LHS.isUsable()) 18352 LHS = CO->getLHS(); 18353 if (!RHS.isUsable()) 18354 RHS = CO->getRHS(); 18355 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18356 CO->getCond(), LHS.get(), RHS.get()); 18357 } 18358 18359 // [Clang extension] 18360 // -- If e has the form __extension__ e1... 18361 case Expr::UnaryOperatorClass: { 18362 auto *UO = cast<UnaryOperator>(E); 18363 if (UO->getOpcode() != UO_Extension) 18364 break; 18365 ExprResult Sub = Rebuild(UO->getSubExpr()); 18366 if (!Sub.isUsable()) 18367 return Sub; 18368 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18369 Sub.get()); 18370 } 18371 18372 // [Clang extension] 18373 // -- If e has the form _Generic(...), the set of potential results is the 18374 // union of the sets of potential results of the associated expressions. 18375 case Expr::GenericSelectionExprClass: { 18376 auto *GSE = cast<GenericSelectionExpr>(E); 18377 18378 SmallVector<Expr *, 4> AssocExprs; 18379 bool AnyChanged = false; 18380 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18381 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18382 if (AssocExpr.isInvalid()) 18383 return ExprError(); 18384 if (AssocExpr.isUsable()) { 18385 AssocExprs.push_back(AssocExpr.get()); 18386 AnyChanged = true; 18387 } else { 18388 AssocExprs.push_back(OrigAssocExpr); 18389 } 18390 } 18391 18392 return AnyChanged ? S.CreateGenericSelectionExpr( 18393 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18394 GSE->getRParenLoc(), GSE->getControllingExpr(), 18395 GSE->getAssocTypeSourceInfos(), AssocExprs) 18396 : ExprEmpty(); 18397 } 18398 18399 // [Clang extension] 18400 // -- If e has the form __builtin_choose_expr(...), the set of potential 18401 // results is the union of the sets of potential results of the 18402 // second and third subexpressions. 18403 case Expr::ChooseExprClass: { 18404 auto *CE = cast<ChooseExpr>(E); 18405 18406 ExprResult LHS = Rebuild(CE->getLHS()); 18407 if (LHS.isInvalid()) 18408 return ExprError(); 18409 18410 ExprResult RHS = Rebuild(CE->getLHS()); 18411 if (RHS.isInvalid()) 18412 return ExprError(); 18413 18414 if (!LHS.get() && !RHS.get()) 18415 return ExprEmpty(); 18416 if (!LHS.isUsable()) 18417 LHS = CE->getLHS(); 18418 if (!RHS.isUsable()) 18419 RHS = CE->getRHS(); 18420 18421 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18422 RHS.get(), CE->getRParenLoc()); 18423 } 18424 18425 // Step through non-syntactic nodes. 18426 case Expr::ConstantExprClass: { 18427 auto *CE = cast<ConstantExpr>(E); 18428 ExprResult Sub = Rebuild(CE->getSubExpr()); 18429 if (!Sub.isUsable()) 18430 return Sub; 18431 return ConstantExpr::Create(S.Context, Sub.get()); 18432 } 18433 18434 // We could mostly rely on the recursive rebuilding to rebuild implicit 18435 // casts, but not at the top level, so rebuild them here. 18436 case Expr::ImplicitCastExprClass: { 18437 auto *ICE = cast<ImplicitCastExpr>(E); 18438 // Only step through the narrow set of cast kinds we expect to encounter. 18439 // Anything else suggests we've left the region in which potential results 18440 // can be found. 18441 switch (ICE->getCastKind()) { 18442 case CK_NoOp: 18443 case CK_DerivedToBase: 18444 case CK_UncheckedDerivedToBase: { 18445 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18446 if (!Sub.isUsable()) 18447 return Sub; 18448 CXXCastPath Path(ICE->path()); 18449 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18450 ICE->getValueKind(), &Path); 18451 } 18452 18453 default: 18454 break; 18455 } 18456 break; 18457 } 18458 18459 default: 18460 break; 18461 } 18462 18463 // Can't traverse through this node. Nothing to do. 18464 return ExprEmpty(); 18465 } 18466 18467 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18468 // Check whether the operand is or contains an object of non-trivial C union 18469 // type. 18470 if (E->getType().isVolatileQualified() && 18471 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18472 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18473 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18474 Sema::NTCUC_LValueToRValueVolatile, 18475 NTCUK_Destruct|NTCUK_Copy); 18476 18477 // C++2a [basic.def.odr]p4: 18478 // [...] an expression of non-volatile-qualified non-class type to which 18479 // the lvalue-to-rvalue conversion is applied [...] 18480 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18481 return E; 18482 18483 ExprResult Result = 18484 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18485 if (Result.isInvalid()) 18486 return ExprError(); 18487 return Result.get() ? Result : E; 18488 } 18489 18490 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18491 Res = CorrectDelayedTyposInExpr(Res); 18492 18493 if (!Res.isUsable()) 18494 return Res; 18495 18496 // If a constant-expression is a reference to a variable where we delay 18497 // deciding whether it is an odr-use, just assume we will apply the 18498 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18499 // (a non-type template argument), we have special handling anyway. 18500 return CheckLValueToRValueConversionOperand(Res.get()); 18501 } 18502 18503 void Sema::CleanupVarDeclMarking() { 18504 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18505 // call. 18506 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18507 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18508 18509 for (Expr *E : LocalMaybeODRUseExprs) { 18510 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18511 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18512 DRE->getLocation(), *this); 18513 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18514 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18515 *this); 18516 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18517 for (VarDecl *VD : *FP) 18518 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18519 } else { 18520 llvm_unreachable("Unexpected expression"); 18521 } 18522 } 18523 18524 assert(MaybeODRUseExprs.empty() && 18525 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18526 } 18527 18528 static void DoMarkVarDeclReferenced( 18529 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 18530 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18531 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18532 isa<FunctionParmPackExpr>(E)) && 18533 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18534 Var->setReferenced(); 18535 18536 if (Var->isInvalidDecl()) 18537 return; 18538 18539 auto *MSI = Var->getMemberSpecializationInfo(); 18540 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18541 : Var->getTemplateSpecializationKind(); 18542 18543 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18544 bool UsableInConstantExpr = 18545 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18546 18547 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 18548 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 18549 } 18550 18551 // C++20 [expr.const]p12: 18552 // A variable [...] is needed for constant evaluation if it is [...] a 18553 // variable whose name appears as a potentially constant evaluated 18554 // expression that is either a contexpr variable or is of non-volatile 18555 // const-qualified integral type or of reference type 18556 bool NeededForConstantEvaluation = 18557 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18558 18559 bool NeedDefinition = 18560 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18561 18562 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18563 "Can't instantiate a partial template specialization."); 18564 18565 // If this might be a member specialization of a static data member, check 18566 // the specialization is visible. We already did the checks for variable 18567 // template specializations when we created them. 18568 if (NeedDefinition && TSK != TSK_Undeclared && 18569 !isa<VarTemplateSpecializationDecl>(Var)) 18570 SemaRef.checkSpecializationVisibility(Loc, Var); 18571 18572 // Perform implicit instantiation of static data members, static data member 18573 // templates of class templates, and variable template specializations. Delay 18574 // instantiations of variable templates, except for those that could be used 18575 // in a constant expression. 18576 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18577 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18578 // instantiation declaration if a variable is usable in a constant 18579 // expression (among other cases). 18580 bool TryInstantiating = 18581 TSK == TSK_ImplicitInstantiation || 18582 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18583 18584 if (TryInstantiating) { 18585 SourceLocation PointOfInstantiation = 18586 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18587 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18588 if (FirstInstantiation) { 18589 PointOfInstantiation = Loc; 18590 if (MSI) 18591 MSI->setPointOfInstantiation(PointOfInstantiation); 18592 // FIXME: Notify listener. 18593 else 18594 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18595 } 18596 18597 if (UsableInConstantExpr) { 18598 // Do not defer instantiations of variables that could be used in a 18599 // constant expression. 18600 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18601 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18602 }); 18603 18604 // Re-set the member to trigger a recomputation of the dependence bits 18605 // for the expression. 18606 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18607 DRE->setDecl(DRE->getDecl()); 18608 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18609 ME->setMemberDecl(ME->getMemberDecl()); 18610 } else if (FirstInstantiation || 18611 isa<VarTemplateSpecializationDecl>(Var)) { 18612 // FIXME: For a specialization of a variable template, we don't 18613 // distinguish between "declaration and type implicitly instantiated" 18614 // and "implicit instantiation of definition requested", so we have 18615 // no direct way to avoid enqueueing the pending instantiation 18616 // multiple times. 18617 SemaRef.PendingInstantiations 18618 .push_back(std::make_pair(Var, PointOfInstantiation)); 18619 } 18620 } 18621 } 18622 18623 // C++2a [basic.def.odr]p4: 18624 // A variable x whose name appears as a potentially-evaluated expression e 18625 // is odr-used by e unless 18626 // -- x is a reference that is usable in constant expressions 18627 // -- x is a variable of non-reference type that is usable in constant 18628 // expressions and has no mutable subobjects [FIXME], and e is an 18629 // element of the set of potential results of an expression of 18630 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18631 // conversion is applied 18632 // -- x is a variable of non-reference type, and e is an element of the set 18633 // of potential results of a discarded-value expression to which the 18634 // lvalue-to-rvalue conversion is not applied [FIXME] 18635 // 18636 // We check the first part of the second bullet here, and 18637 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18638 // FIXME: To get the third bullet right, we need to delay this even for 18639 // variables that are not usable in constant expressions. 18640 18641 // If we already know this isn't an odr-use, there's nothing more to do. 18642 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18643 if (DRE->isNonOdrUse()) 18644 return; 18645 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18646 if (ME->isNonOdrUse()) 18647 return; 18648 18649 switch (OdrUse) { 18650 case OdrUseContext::None: 18651 assert((!E || isa<FunctionParmPackExpr>(E)) && 18652 "missing non-odr-use marking for unevaluated decl ref"); 18653 break; 18654 18655 case OdrUseContext::FormallyOdrUsed: 18656 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18657 // behavior. 18658 break; 18659 18660 case OdrUseContext::Used: 18661 // If we might later find that this expression isn't actually an odr-use, 18662 // delay the marking. 18663 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18664 SemaRef.MaybeODRUseExprs.insert(E); 18665 else 18666 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18667 break; 18668 18669 case OdrUseContext::Dependent: 18670 // If this is a dependent context, we don't need to mark variables as 18671 // odr-used, but we may still need to track them for lambda capture. 18672 // FIXME: Do we also need to do this inside dependent typeid expressions 18673 // (which are modeled as unevaluated at this point)? 18674 const bool RefersToEnclosingScope = 18675 (SemaRef.CurContext != Var->getDeclContext() && 18676 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18677 if (RefersToEnclosingScope) { 18678 LambdaScopeInfo *const LSI = 18679 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18680 if (LSI && (!LSI->CallOperator || 18681 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18682 // If a variable could potentially be odr-used, defer marking it so 18683 // until we finish analyzing the full expression for any 18684 // lvalue-to-rvalue 18685 // or discarded value conversions that would obviate odr-use. 18686 // Add it to the list of potential captures that will be analyzed 18687 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18688 // unless the variable is a reference that was initialized by a constant 18689 // expression (this will never need to be captured or odr-used). 18690 // 18691 // FIXME: We can simplify this a lot after implementing P0588R1. 18692 assert(E && "Capture variable should be used in an expression."); 18693 if (!Var->getType()->isReferenceType() || 18694 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18695 LSI->addPotentialCapture(E->IgnoreParens()); 18696 } 18697 } 18698 break; 18699 } 18700 } 18701 18702 /// Mark a variable referenced, and check whether it is odr-used 18703 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18704 /// used directly for normal expressions referring to VarDecl. 18705 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18706 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 18707 } 18708 18709 static void 18710 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 18711 bool MightBeOdrUse, 18712 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18713 if (SemaRef.isInOpenMPDeclareTargetContext()) 18714 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18715 18716 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18717 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 18718 return; 18719 } 18720 18721 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18722 18723 // If this is a call to a method via a cast, also mark the method in the 18724 // derived class used in case codegen can devirtualize the call. 18725 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18726 if (!ME) 18727 return; 18728 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18729 if (!MD) 18730 return; 18731 // Only attempt to devirtualize if this is truly a virtual call. 18732 bool IsVirtualCall = MD->isVirtual() && 18733 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18734 if (!IsVirtualCall) 18735 return; 18736 18737 // If it's possible to devirtualize the call, mark the called function 18738 // referenced. 18739 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18740 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18741 if (DM) 18742 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18743 } 18744 18745 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18746 /// 18747 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18748 /// handled with care if the DeclRefExpr is not newly-created. 18749 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18750 // TODO: update this with DR# once a defect report is filed. 18751 // C++11 defect. The address of a pure member should not be an ODR use, even 18752 // if it's a qualified reference. 18753 bool OdrUse = true; 18754 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18755 if (Method->isVirtual() && 18756 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18757 OdrUse = false; 18758 18759 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18760 if (!isUnevaluatedContext() && !isConstantEvaluated() && 18761 FD->isConsteval() && !RebuildingImmediateInvocation) 18762 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18763 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 18764 RefsMinusAssignments); 18765 } 18766 18767 /// Perform reference-marking and odr-use handling for a MemberExpr. 18768 void Sema::MarkMemberReferenced(MemberExpr *E) { 18769 // C++11 [basic.def.odr]p2: 18770 // A non-overloaded function whose name appears as a potentially-evaluated 18771 // expression or a member of a set of candidate functions, if selected by 18772 // overload resolution when referred to from a potentially-evaluated 18773 // expression, is odr-used, unless it is a pure virtual function and its 18774 // name is not explicitly qualified. 18775 bool MightBeOdrUse = true; 18776 if (E->performsVirtualDispatch(getLangOpts())) { 18777 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18778 if (Method->isPure()) 18779 MightBeOdrUse = false; 18780 } 18781 SourceLocation Loc = 18782 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18783 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 18784 RefsMinusAssignments); 18785 } 18786 18787 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18788 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18789 for (VarDecl *VD : *E) 18790 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 18791 RefsMinusAssignments); 18792 } 18793 18794 /// Perform marking for a reference to an arbitrary declaration. It 18795 /// marks the declaration referenced, and performs odr-use checking for 18796 /// functions and variables. This method should not be used when building a 18797 /// normal expression which refers to a variable. 18798 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18799 bool MightBeOdrUse) { 18800 if (MightBeOdrUse) { 18801 if (auto *VD = dyn_cast<VarDecl>(D)) { 18802 MarkVariableReferenced(Loc, VD); 18803 return; 18804 } 18805 } 18806 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18807 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18808 return; 18809 } 18810 D->setReferenced(); 18811 } 18812 18813 namespace { 18814 // Mark all of the declarations used by a type as referenced. 18815 // FIXME: Not fully implemented yet! We need to have a better understanding 18816 // of when we're entering a context we should not recurse into. 18817 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18818 // TreeTransforms rebuilding the type in a new context. Rather than 18819 // duplicating the TreeTransform logic, we should consider reusing it here. 18820 // Currently that causes problems when rebuilding LambdaExprs. 18821 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18822 Sema &S; 18823 SourceLocation Loc; 18824 18825 public: 18826 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18827 18828 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18829 18830 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18831 }; 18832 } 18833 18834 bool MarkReferencedDecls::TraverseTemplateArgument( 18835 const TemplateArgument &Arg) { 18836 { 18837 // A non-type template argument is a constant-evaluated context. 18838 EnterExpressionEvaluationContext Evaluated( 18839 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18840 if (Arg.getKind() == TemplateArgument::Declaration) { 18841 if (Decl *D = Arg.getAsDecl()) 18842 S.MarkAnyDeclReferenced(Loc, D, true); 18843 } else if (Arg.getKind() == TemplateArgument::Expression) { 18844 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18845 } 18846 } 18847 18848 return Inherited::TraverseTemplateArgument(Arg); 18849 } 18850 18851 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18852 MarkReferencedDecls Marker(*this, Loc); 18853 Marker.TraverseType(T); 18854 } 18855 18856 namespace { 18857 /// Helper class that marks all of the declarations referenced by 18858 /// potentially-evaluated subexpressions as "referenced". 18859 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18860 public: 18861 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18862 bool SkipLocalVariables; 18863 18864 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18865 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18866 18867 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18868 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18869 } 18870 18871 void VisitDeclRefExpr(DeclRefExpr *E) { 18872 // If we were asked not to visit local variables, don't. 18873 if (SkipLocalVariables) { 18874 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18875 if (VD->hasLocalStorage()) 18876 return; 18877 } 18878 18879 // FIXME: This can trigger the instantiation of the initializer of a 18880 // variable, which can cause the expression to become value-dependent 18881 // or error-dependent. Do we need to propagate the new dependence bits? 18882 S.MarkDeclRefReferenced(E); 18883 } 18884 18885 void VisitMemberExpr(MemberExpr *E) { 18886 S.MarkMemberReferenced(E); 18887 Visit(E->getBase()); 18888 } 18889 }; 18890 } // namespace 18891 18892 /// Mark any declarations that appear within this expression or any 18893 /// potentially-evaluated subexpressions as "referenced". 18894 /// 18895 /// \param SkipLocalVariables If true, don't mark local variables as 18896 /// 'referenced'. 18897 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18898 bool SkipLocalVariables) { 18899 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18900 } 18901 18902 /// Emit a diagnostic when statements are reachable. 18903 /// FIXME: check for reachability even in expressions for which we don't build a 18904 /// CFG (eg, in the initializer of a global or in a constant expression). 18905 /// For example, 18906 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; } 18907 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, 18908 const PartialDiagnostic &PD) { 18909 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18910 if (!FunctionScopes.empty()) 18911 FunctionScopes.back()->PossiblyUnreachableDiags.push_back( 18912 sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18913 return true; 18914 } 18915 18916 // The initializer of a constexpr variable or of the first declaration of a 18917 // static data member is not syntactically a constant evaluated constant, 18918 // but nonetheless is always required to be a constant expression, so we 18919 // can skip diagnosing. 18920 // FIXME: Using the mangling context here is a hack. 18921 if (auto *VD = dyn_cast_or_null<VarDecl>( 18922 ExprEvalContexts.back().ManglingContextDecl)) { 18923 if (VD->isConstexpr() || 18924 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18925 return false; 18926 // FIXME: For any other kind of variable, we should build a CFG for its 18927 // initializer and check whether the context in question is reachable. 18928 } 18929 18930 Diag(Loc, PD); 18931 return true; 18932 } 18933 18934 /// Emit a diagnostic that describes an effect on the run-time behavior 18935 /// of the program being compiled. 18936 /// 18937 /// This routine emits the given diagnostic when the code currently being 18938 /// type-checked is "potentially evaluated", meaning that there is a 18939 /// possibility that the code will actually be executable. Code in sizeof() 18940 /// expressions, code used only during overload resolution, etc., are not 18941 /// potentially evaluated. This routine will suppress such diagnostics or, 18942 /// in the absolutely nutty case of potentially potentially evaluated 18943 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18944 /// later. 18945 /// 18946 /// This routine should be used for all diagnostics that describe the run-time 18947 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18948 /// Failure to do so will likely result in spurious diagnostics or failures 18949 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18950 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18951 const PartialDiagnostic &PD) { 18952 switch (ExprEvalContexts.back().Context) { 18953 case ExpressionEvaluationContext::Unevaluated: 18954 case ExpressionEvaluationContext::UnevaluatedList: 18955 case ExpressionEvaluationContext::UnevaluatedAbstract: 18956 case ExpressionEvaluationContext::DiscardedStatement: 18957 // The argument will never be evaluated, so don't complain. 18958 break; 18959 18960 case ExpressionEvaluationContext::ConstantEvaluated: 18961 // Relevant diagnostics should be produced by constant evaluation. 18962 break; 18963 18964 case ExpressionEvaluationContext::PotentiallyEvaluated: 18965 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18966 return DiagIfReachable(Loc, Stmts, PD); 18967 } 18968 18969 return false; 18970 } 18971 18972 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18973 const PartialDiagnostic &PD) { 18974 return DiagRuntimeBehavior( 18975 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18976 } 18977 18978 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18979 CallExpr *CE, FunctionDecl *FD) { 18980 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18981 return false; 18982 18983 // If we're inside a decltype's expression, don't check for a valid return 18984 // type or construct temporaries until we know whether this is the last call. 18985 if (ExprEvalContexts.back().ExprContext == 18986 ExpressionEvaluationContextRecord::EK_Decltype) { 18987 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18988 return false; 18989 } 18990 18991 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18992 FunctionDecl *FD; 18993 CallExpr *CE; 18994 18995 public: 18996 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18997 : FD(FD), CE(CE) { } 18998 18999 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 19000 if (!FD) { 19001 S.Diag(Loc, diag::err_call_incomplete_return) 19002 << T << CE->getSourceRange(); 19003 return; 19004 } 19005 19006 S.Diag(Loc, diag::err_call_function_incomplete_return) 19007 << CE->getSourceRange() << FD << T; 19008 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 19009 << FD->getDeclName(); 19010 } 19011 } Diagnoser(FD, CE); 19012 19013 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 19014 return true; 19015 19016 return false; 19017 } 19018 19019 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 19020 // will prevent this condition from triggering, which is what we want. 19021 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 19022 SourceLocation Loc; 19023 19024 unsigned diagnostic = diag::warn_condition_is_assignment; 19025 bool IsOrAssign = false; 19026 19027 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 19028 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 19029 return; 19030 19031 IsOrAssign = Op->getOpcode() == BO_OrAssign; 19032 19033 // Greylist some idioms by putting them into a warning subcategory. 19034 if (ObjCMessageExpr *ME 19035 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 19036 Selector Sel = ME->getSelector(); 19037 19038 // self = [<foo> init...] 19039 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 19040 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19041 19042 // <foo> = [<bar> nextObject] 19043 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 19044 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19045 } 19046 19047 Loc = Op->getOperatorLoc(); 19048 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 19049 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 19050 return; 19051 19052 IsOrAssign = Op->getOperator() == OO_PipeEqual; 19053 Loc = Op->getOperatorLoc(); 19054 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 19055 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 19056 else { 19057 // Not an assignment. 19058 return; 19059 } 19060 19061 Diag(Loc, diagnostic) << E->getSourceRange(); 19062 19063 SourceLocation Open = E->getBeginLoc(); 19064 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 19065 Diag(Loc, diag::note_condition_assign_silence) 19066 << FixItHint::CreateInsertion(Open, "(") 19067 << FixItHint::CreateInsertion(Close, ")"); 19068 19069 if (IsOrAssign) 19070 Diag(Loc, diag::note_condition_or_assign_to_comparison) 19071 << FixItHint::CreateReplacement(Loc, "!="); 19072 else 19073 Diag(Loc, diag::note_condition_assign_to_comparison) 19074 << FixItHint::CreateReplacement(Loc, "=="); 19075 } 19076 19077 /// Redundant parentheses over an equality comparison can indicate 19078 /// that the user intended an assignment used as condition. 19079 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 19080 // Don't warn if the parens came from a macro. 19081 SourceLocation parenLoc = ParenE->getBeginLoc(); 19082 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 19083 return; 19084 // Don't warn for dependent expressions. 19085 if (ParenE->isTypeDependent()) 19086 return; 19087 19088 Expr *E = ParenE->IgnoreParens(); 19089 19090 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 19091 if (opE->getOpcode() == BO_EQ && 19092 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 19093 == Expr::MLV_Valid) { 19094 SourceLocation Loc = opE->getOperatorLoc(); 19095 19096 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 19097 SourceRange ParenERange = ParenE->getSourceRange(); 19098 Diag(Loc, diag::note_equality_comparison_silence) 19099 << FixItHint::CreateRemoval(ParenERange.getBegin()) 19100 << FixItHint::CreateRemoval(ParenERange.getEnd()); 19101 Diag(Loc, diag::note_equality_comparison_to_assign) 19102 << FixItHint::CreateReplacement(Loc, "="); 19103 } 19104 } 19105 19106 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 19107 bool IsConstexpr) { 19108 DiagnoseAssignmentAsCondition(E); 19109 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 19110 DiagnoseEqualityWithExtraParens(parenE); 19111 19112 ExprResult result = CheckPlaceholderExpr(E); 19113 if (result.isInvalid()) return ExprError(); 19114 E = result.get(); 19115 19116 if (!E->isTypeDependent()) { 19117 if (getLangOpts().CPlusPlus) 19118 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 19119 19120 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 19121 if (ERes.isInvalid()) 19122 return ExprError(); 19123 E = ERes.get(); 19124 19125 QualType T = E->getType(); 19126 if (!T->isScalarType()) { // C99 6.8.4.1p1 19127 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 19128 << T << E->getSourceRange(); 19129 return ExprError(); 19130 } 19131 CheckBoolLikeConversion(E, Loc); 19132 } 19133 19134 return E; 19135 } 19136 19137 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 19138 Expr *SubExpr, ConditionKind CK) { 19139 // Empty conditions are valid in for-statements. 19140 if (!SubExpr) 19141 return ConditionResult(); 19142 19143 ExprResult Cond; 19144 switch (CK) { 19145 case ConditionKind::Boolean: 19146 Cond = CheckBooleanCondition(Loc, SubExpr); 19147 break; 19148 19149 case ConditionKind::ConstexprIf: 19150 Cond = CheckBooleanCondition(Loc, SubExpr, true); 19151 break; 19152 19153 case ConditionKind::Switch: 19154 Cond = CheckSwitchCondition(Loc, SubExpr); 19155 break; 19156 } 19157 if (Cond.isInvalid()) { 19158 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 19159 {SubExpr}); 19160 if (!Cond.get()) 19161 return ConditionError(); 19162 } 19163 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 19164 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 19165 if (!FullExpr.get()) 19166 return ConditionError(); 19167 19168 return ConditionResult(*this, nullptr, FullExpr, 19169 CK == ConditionKind::ConstexprIf); 19170 } 19171 19172 namespace { 19173 /// A visitor for rebuilding a call to an __unknown_any expression 19174 /// to have an appropriate type. 19175 struct RebuildUnknownAnyFunction 19176 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 19177 19178 Sema &S; 19179 19180 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 19181 19182 ExprResult VisitStmt(Stmt *S) { 19183 llvm_unreachable("unexpected statement!"); 19184 } 19185 19186 ExprResult VisitExpr(Expr *E) { 19187 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 19188 << E->getSourceRange(); 19189 return ExprError(); 19190 } 19191 19192 /// Rebuild an expression which simply semantically wraps another 19193 /// expression which it shares the type and value kind of. 19194 template <class T> ExprResult rebuildSugarExpr(T *E) { 19195 ExprResult SubResult = Visit(E->getSubExpr()); 19196 if (SubResult.isInvalid()) return ExprError(); 19197 19198 Expr *SubExpr = SubResult.get(); 19199 E->setSubExpr(SubExpr); 19200 E->setType(SubExpr->getType()); 19201 E->setValueKind(SubExpr->getValueKind()); 19202 assert(E->getObjectKind() == OK_Ordinary); 19203 return E; 19204 } 19205 19206 ExprResult VisitParenExpr(ParenExpr *E) { 19207 return rebuildSugarExpr(E); 19208 } 19209 19210 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19211 return rebuildSugarExpr(E); 19212 } 19213 19214 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19215 ExprResult SubResult = Visit(E->getSubExpr()); 19216 if (SubResult.isInvalid()) return ExprError(); 19217 19218 Expr *SubExpr = SubResult.get(); 19219 E->setSubExpr(SubExpr); 19220 E->setType(S.Context.getPointerType(SubExpr->getType())); 19221 assert(E->isPRValue()); 19222 assert(E->getObjectKind() == OK_Ordinary); 19223 return E; 19224 } 19225 19226 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19227 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19228 19229 E->setType(VD->getType()); 19230 19231 assert(E->isPRValue()); 19232 if (S.getLangOpts().CPlusPlus && 19233 !(isa<CXXMethodDecl>(VD) && 19234 cast<CXXMethodDecl>(VD)->isInstance())) 19235 E->setValueKind(VK_LValue); 19236 19237 return E; 19238 } 19239 19240 ExprResult VisitMemberExpr(MemberExpr *E) { 19241 return resolveDecl(E, E->getMemberDecl()); 19242 } 19243 19244 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19245 return resolveDecl(E, E->getDecl()); 19246 } 19247 }; 19248 } 19249 19250 /// Given a function expression of unknown-any type, try to rebuild it 19251 /// to have a function type. 19252 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19253 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19254 if (Result.isInvalid()) return ExprError(); 19255 return S.DefaultFunctionArrayConversion(Result.get()); 19256 } 19257 19258 namespace { 19259 /// A visitor for rebuilding an expression of type __unknown_anytype 19260 /// into one which resolves the type directly on the referring 19261 /// expression. Strict preservation of the original source 19262 /// structure is not a goal. 19263 struct RebuildUnknownAnyExpr 19264 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19265 19266 Sema &S; 19267 19268 /// The current destination type. 19269 QualType DestType; 19270 19271 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19272 : S(S), DestType(CastType) {} 19273 19274 ExprResult VisitStmt(Stmt *S) { 19275 llvm_unreachable("unexpected statement!"); 19276 } 19277 19278 ExprResult VisitExpr(Expr *E) { 19279 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19280 << E->getSourceRange(); 19281 return ExprError(); 19282 } 19283 19284 ExprResult VisitCallExpr(CallExpr *E); 19285 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 19286 19287 /// Rebuild an expression which simply semantically wraps another 19288 /// expression which it shares the type and value kind of. 19289 template <class T> ExprResult rebuildSugarExpr(T *E) { 19290 ExprResult SubResult = Visit(E->getSubExpr()); 19291 if (SubResult.isInvalid()) return ExprError(); 19292 Expr *SubExpr = SubResult.get(); 19293 E->setSubExpr(SubExpr); 19294 E->setType(SubExpr->getType()); 19295 E->setValueKind(SubExpr->getValueKind()); 19296 assert(E->getObjectKind() == OK_Ordinary); 19297 return E; 19298 } 19299 19300 ExprResult VisitParenExpr(ParenExpr *E) { 19301 return rebuildSugarExpr(E); 19302 } 19303 19304 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19305 return rebuildSugarExpr(E); 19306 } 19307 19308 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19309 const PointerType *Ptr = DestType->getAs<PointerType>(); 19310 if (!Ptr) { 19311 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19312 << E->getSourceRange(); 19313 return ExprError(); 19314 } 19315 19316 if (isa<CallExpr>(E->getSubExpr())) { 19317 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19318 << E->getSourceRange(); 19319 return ExprError(); 19320 } 19321 19322 assert(E->isPRValue()); 19323 assert(E->getObjectKind() == OK_Ordinary); 19324 E->setType(DestType); 19325 19326 // Build the sub-expression as if it were an object of the pointee type. 19327 DestType = Ptr->getPointeeType(); 19328 ExprResult SubResult = Visit(E->getSubExpr()); 19329 if (SubResult.isInvalid()) return ExprError(); 19330 E->setSubExpr(SubResult.get()); 19331 return E; 19332 } 19333 19334 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19335 19336 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19337 19338 ExprResult VisitMemberExpr(MemberExpr *E) { 19339 return resolveDecl(E, E->getMemberDecl()); 19340 } 19341 19342 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19343 return resolveDecl(E, E->getDecl()); 19344 } 19345 }; 19346 } 19347 19348 /// Rebuilds a call expression which yielded __unknown_anytype. 19349 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19350 Expr *CalleeExpr = E->getCallee(); 19351 19352 enum FnKind { 19353 FK_MemberFunction, 19354 FK_FunctionPointer, 19355 FK_BlockPointer 19356 }; 19357 19358 FnKind Kind; 19359 QualType CalleeType = CalleeExpr->getType(); 19360 if (CalleeType == S.Context.BoundMemberTy) { 19361 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19362 Kind = FK_MemberFunction; 19363 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19364 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19365 CalleeType = Ptr->getPointeeType(); 19366 Kind = FK_FunctionPointer; 19367 } else { 19368 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19369 Kind = FK_BlockPointer; 19370 } 19371 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19372 19373 // Verify that this is a legal result type of a function. 19374 if (DestType->isArrayType() || DestType->isFunctionType()) { 19375 unsigned diagID = diag::err_func_returning_array_function; 19376 if (Kind == FK_BlockPointer) 19377 diagID = diag::err_block_returning_array_function; 19378 19379 S.Diag(E->getExprLoc(), diagID) 19380 << DestType->isFunctionType() << DestType; 19381 return ExprError(); 19382 } 19383 19384 // Otherwise, go ahead and set DestType as the call's result. 19385 E->setType(DestType.getNonLValueExprType(S.Context)); 19386 E->setValueKind(Expr::getValueKindForType(DestType)); 19387 assert(E->getObjectKind() == OK_Ordinary); 19388 19389 // Rebuild the function type, replacing the result type with DestType. 19390 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19391 if (Proto) { 19392 // __unknown_anytype(...) is a special case used by the debugger when 19393 // it has no idea what a function's signature is. 19394 // 19395 // We want to build this call essentially under the K&R 19396 // unprototyped rules, but making a FunctionNoProtoType in C++ 19397 // would foul up all sorts of assumptions. However, we cannot 19398 // simply pass all arguments as variadic arguments, nor can we 19399 // portably just call the function under a non-variadic type; see 19400 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19401 // However, it turns out that in practice it is generally safe to 19402 // call a function declared as "A foo(B,C,D);" under the prototype 19403 // "A foo(B,C,D,...);". The only known exception is with the 19404 // Windows ABI, where any variadic function is implicitly cdecl 19405 // regardless of its normal CC. Therefore we change the parameter 19406 // types to match the types of the arguments. 19407 // 19408 // This is a hack, but it is far superior to moving the 19409 // corresponding target-specific code from IR-gen to Sema/AST. 19410 19411 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19412 SmallVector<QualType, 8> ArgTypes; 19413 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19414 ArgTypes.reserve(E->getNumArgs()); 19415 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19416 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); 19417 } 19418 ParamTypes = ArgTypes; 19419 } 19420 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19421 Proto->getExtProtoInfo()); 19422 } else { 19423 DestType = S.Context.getFunctionNoProtoType(DestType, 19424 FnType->getExtInfo()); 19425 } 19426 19427 // Rebuild the appropriate pointer-to-function type. 19428 switch (Kind) { 19429 case FK_MemberFunction: 19430 // Nothing to do. 19431 break; 19432 19433 case FK_FunctionPointer: 19434 DestType = S.Context.getPointerType(DestType); 19435 break; 19436 19437 case FK_BlockPointer: 19438 DestType = S.Context.getBlockPointerType(DestType); 19439 break; 19440 } 19441 19442 // Finally, we can recurse. 19443 ExprResult CalleeResult = Visit(CalleeExpr); 19444 if (!CalleeResult.isUsable()) return ExprError(); 19445 E->setCallee(CalleeResult.get()); 19446 19447 // Bind a temporary if necessary. 19448 return S.MaybeBindToTemporary(E); 19449 } 19450 19451 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19452 // Verify that this is a legal result type of a call. 19453 if (DestType->isArrayType() || DestType->isFunctionType()) { 19454 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19455 << DestType->isFunctionType() << DestType; 19456 return ExprError(); 19457 } 19458 19459 // Rewrite the method result type if available. 19460 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19461 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19462 Method->setReturnType(DestType); 19463 } 19464 19465 // Change the type of the message. 19466 E->setType(DestType.getNonReferenceType()); 19467 E->setValueKind(Expr::getValueKindForType(DestType)); 19468 19469 return S.MaybeBindToTemporary(E); 19470 } 19471 19472 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19473 // The only case we should ever see here is a function-to-pointer decay. 19474 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19475 assert(E->isPRValue()); 19476 assert(E->getObjectKind() == OK_Ordinary); 19477 19478 E->setType(DestType); 19479 19480 // Rebuild the sub-expression as the pointee (function) type. 19481 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19482 19483 ExprResult Result = Visit(E->getSubExpr()); 19484 if (!Result.isUsable()) return ExprError(); 19485 19486 E->setSubExpr(Result.get()); 19487 return E; 19488 } else if (E->getCastKind() == CK_LValueToRValue) { 19489 assert(E->isPRValue()); 19490 assert(E->getObjectKind() == OK_Ordinary); 19491 19492 assert(isa<BlockPointerType>(E->getType())); 19493 19494 E->setType(DestType); 19495 19496 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19497 DestType = S.Context.getLValueReferenceType(DestType); 19498 19499 ExprResult Result = Visit(E->getSubExpr()); 19500 if (!Result.isUsable()) return ExprError(); 19501 19502 E->setSubExpr(Result.get()); 19503 return E; 19504 } else { 19505 llvm_unreachable("Unhandled cast type!"); 19506 } 19507 } 19508 19509 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19510 ExprValueKind ValueKind = VK_LValue; 19511 QualType Type = DestType; 19512 19513 // We know how to make this work for certain kinds of decls: 19514 19515 // - functions 19516 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19517 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19518 DestType = Ptr->getPointeeType(); 19519 ExprResult Result = resolveDecl(E, VD); 19520 if (Result.isInvalid()) return ExprError(); 19521 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 19522 VK_PRValue); 19523 } 19524 19525 if (!Type->isFunctionType()) { 19526 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19527 << VD << E->getSourceRange(); 19528 return ExprError(); 19529 } 19530 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19531 // We must match the FunctionDecl's type to the hack introduced in 19532 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19533 // type. See the lengthy commentary in that routine. 19534 QualType FDT = FD->getType(); 19535 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19536 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19537 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19538 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19539 SourceLocation Loc = FD->getLocation(); 19540 FunctionDecl *NewFD = FunctionDecl::Create( 19541 S.Context, FD->getDeclContext(), Loc, Loc, 19542 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19543 SC_None, S.getCurFPFeatures().isFPConstrained(), 19544 false /*isInlineSpecified*/, FD->hasPrototype(), 19545 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19546 19547 if (FD->getQualifier()) 19548 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19549 19550 SmallVector<ParmVarDecl*, 16> Params; 19551 for (const auto &AI : FT->param_types()) { 19552 ParmVarDecl *Param = 19553 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19554 Param->setScopeInfo(0, Params.size()); 19555 Params.push_back(Param); 19556 } 19557 NewFD->setParams(Params); 19558 DRE->setDecl(NewFD); 19559 VD = DRE->getDecl(); 19560 } 19561 } 19562 19563 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19564 if (MD->isInstance()) { 19565 ValueKind = VK_PRValue; 19566 Type = S.Context.BoundMemberTy; 19567 } 19568 19569 // Function references aren't l-values in C. 19570 if (!S.getLangOpts().CPlusPlus) 19571 ValueKind = VK_PRValue; 19572 19573 // - variables 19574 } else if (isa<VarDecl>(VD)) { 19575 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19576 Type = RefTy->getPointeeType(); 19577 } else if (Type->isFunctionType()) { 19578 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19579 << VD << E->getSourceRange(); 19580 return ExprError(); 19581 } 19582 19583 // - nothing else 19584 } else { 19585 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19586 << VD << E->getSourceRange(); 19587 return ExprError(); 19588 } 19589 19590 // Modifying the declaration like this is friendly to IR-gen but 19591 // also really dangerous. 19592 VD->setType(DestType); 19593 E->setType(Type); 19594 E->setValueKind(ValueKind); 19595 return E; 19596 } 19597 19598 /// Check a cast of an unknown-any type. We intentionally only 19599 /// trigger this for C-style casts. 19600 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19601 Expr *CastExpr, CastKind &CastKind, 19602 ExprValueKind &VK, CXXCastPath &Path) { 19603 // The type we're casting to must be either void or complete. 19604 if (!CastType->isVoidType() && 19605 RequireCompleteType(TypeRange.getBegin(), CastType, 19606 diag::err_typecheck_cast_to_incomplete)) 19607 return ExprError(); 19608 19609 // Rewrite the casted expression from scratch. 19610 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19611 if (!result.isUsable()) return ExprError(); 19612 19613 CastExpr = result.get(); 19614 VK = CastExpr->getValueKind(); 19615 CastKind = CK_NoOp; 19616 19617 return CastExpr; 19618 } 19619 19620 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19621 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19622 } 19623 19624 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19625 Expr *arg, QualType ¶mType) { 19626 // If the syntactic form of the argument is not an explicit cast of 19627 // any sort, just do default argument promotion. 19628 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19629 if (!castArg) { 19630 ExprResult result = DefaultArgumentPromotion(arg); 19631 if (result.isInvalid()) return ExprError(); 19632 paramType = result.get()->getType(); 19633 return result; 19634 } 19635 19636 // Otherwise, use the type that was written in the explicit cast. 19637 assert(!arg->hasPlaceholderType()); 19638 paramType = castArg->getTypeAsWritten(); 19639 19640 // Copy-initialize a parameter of that type. 19641 InitializedEntity entity = 19642 InitializedEntity::InitializeParameter(Context, paramType, 19643 /*consumed*/ false); 19644 return PerformCopyInitialization(entity, callLoc, arg); 19645 } 19646 19647 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19648 Expr *orig = E; 19649 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19650 while (true) { 19651 E = E->IgnoreParenImpCasts(); 19652 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19653 E = call->getCallee(); 19654 diagID = diag::err_uncasted_call_of_unknown_any; 19655 } else { 19656 break; 19657 } 19658 } 19659 19660 SourceLocation loc; 19661 NamedDecl *d; 19662 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19663 loc = ref->getLocation(); 19664 d = ref->getDecl(); 19665 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19666 loc = mem->getMemberLoc(); 19667 d = mem->getMemberDecl(); 19668 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19669 diagID = diag::err_uncasted_call_of_unknown_any; 19670 loc = msg->getSelectorStartLoc(); 19671 d = msg->getMethodDecl(); 19672 if (!d) { 19673 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19674 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19675 << orig->getSourceRange(); 19676 return ExprError(); 19677 } 19678 } else { 19679 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19680 << E->getSourceRange(); 19681 return ExprError(); 19682 } 19683 19684 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19685 19686 // Never recoverable. 19687 return ExprError(); 19688 } 19689 19690 /// Check for operands with placeholder types and complain if found. 19691 /// Returns ExprError() if there was an error and no recovery was possible. 19692 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19693 if (!Context.isDependenceAllowed()) { 19694 // C cannot handle TypoExpr nodes on either side of a binop because it 19695 // doesn't handle dependent types properly, so make sure any TypoExprs have 19696 // been dealt with before checking the operands. 19697 ExprResult Result = CorrectDelayedTyposInExpr(E); 19698 if (!Result.isUsable()) return ExprError(); 19699 E = Result.get(); 19700 } 19701 19702 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19703 if (!placeholderType) return E; 19704 19705 switch (placeholderType->getKind()) { 19706 19707 // Overloaded expressions. 19708 case BuiltinType::Overload: { 19709 // Try to resolve a single function template specialization. 19710 // This is obligatory. 19711 ExprResult Result = E; 19712 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19713 return Result; 19714 19715 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19716 // leaves Result unchanged on failure. 19717 Result = E; 19718 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19719 return Result; 19720 19721 // If that failed, try to recover with a call. 19722 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19723 /*complain*/ true); 19724 return Result; 19725 } 19726 19727 // Bound member functions. 19728 case BuiltinType::BoundMember: { 19729 ExprResult result = E; 19730 const Expr *BME = E->IgnoreParens(); 19731 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19732 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19733 if (isa<CXXPseudoDestructorExpr>(BME)) { 19734 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19735 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19736 if (ME->getMemberNameInfo().getName().getNameKind() == 19737 DeclarationName::CXXDestructorName) 19738 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19739 } 19740 tryToRecoverWithCall(result, PD, 19741 /*complain*/ true); 19742 return result; 19743 } 19744 19745 // ARC unbridged casts. 19746 case BuiltinType::ARCUnbridgedCast: { 19747 Expr *realCast = stripARCUnbridgedCast(E); 19748 diagnoseARCUnbridgedCast(realCast); 19749 return realCast; 19750 } 19751 19752 // Expressions of unknown type. 19753 case BuiltinType::UnknownAny: 19754 return diagnoseUnknownAnyExpr(*this, E); 19755 19756 // Pseudo-objects. 19757 case BuiltinType::PseudoObject: 19758 return checkPseudoObjectRValue(E); 19759 19760 case BuiltinType::BuiltinFn: { 19761 // Accept __noop without parens by implicitly converting it to a call expr. 19762 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19763 if (DRE) { 19764 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19765 if (FD->getBuiltinID() == Builtin::BI__noop) { 19766 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19767 CK_BuiltinFnToFnPtr) 19768 .get(); 19769 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19770 VK_PRValue, SourceLocation(), 19771 FPOptionsOverride()); 19772 } 19773 } 19774 19775 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19776 return ExprError(); 19777 } 19778 19779 case BuiltinType::IncompleteMatrixIdx: 19780 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19781 ->getRowIdx() 19782 ->getBeginLoc(), 19783 diag::err_matrix_incomplete_index); 19784 return ExprError(); 19785 19786 // Expressions of unknown type. 19787 case BuiltinType::OMPArraySection: 19788 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19789 return ExprError(); 19790 19791 // Expressions of unknown type. 19792 case BuiltinType::OMPArrayShaping: 19793 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19794 19795 case BuiltinType::OMPIterator: 19796 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19797 19798 // Everything else should be impossible. 19799 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19800 case BuiltinType::Id: 19801 #include "clang/Basic/OpenCLImageTypes.def" 19802 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19803 case BuiltinType::Id: 19804 #include "clang/Basic/OpenCLExtensionTypes.def" 19805 #define SVE_TYPE(Name, Id, SingletonId) \ 19806 case BuiltinType::Id: 19807 #include "clang/Basic/AArch64SVEACLETypes.def" 19808 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19809 case BuiltinType::Id: 19810 #include "clang/Basic/PPCTypes.def" 19811 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19812 #include "clang/Basic/RISCVVTypes.def" 19813 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19814 #define PLACEHOLDER_TYPE(Id, SingletonId) 19815 #include "clang/AST/BuiltinTypes.def" 19816 break; 19817 } 19818 19819 llvm_unreachable("invalid placeholder type!"); 19820 } 19821 19822 bool Sema::CheckCaseExpression(Expr *E) { 19823 if (E->isTypeDependent()) 19824 return true; 19825 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19826 return E->getType()->isIntegralOrEnumerationType(); 19827 return false; 19828 } 19829 19830 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19831 ExprResult 19832 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19833 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19834 "Unknown Objective-C Boolean value!"); 19835 QualType BoolT = Context.ObjCBuiltinBoolTy; 19836 if (!Context.getBOOLDecl()) { 19837 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19838 Sema::LookupOrdinaryName); 19839 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19840 NamedDecl *ND = Result.getFoundDecl(); 19841 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19842 Context.setBOOLDecl(TD); 19843 } 19844 } 19845 if (Context.getBOOLDecl()) 19846 BoolT = Context.getBOOLType(); 19847 return new (Context) 19848 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19849 } 19850 19851 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19852 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19853 SourceLocation RParen) { 19854 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { 19855 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19856 return Spec.getPlatform() == Platform; 19857 }); 19858 // Transcribe the "ios" availability check to "maccatalyst" when compiling 19859 // for "maccatalyst" if "maccatalyst" is not specified. 19860 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { 19861 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19862 return Spec.getPlatform() == "ios"; 19863 }); 19864 } 19865 if (Spec == AvailSpecs.end()) 19866 return None; 19867 return Spec->getVersion(); 19868 }; 19869 19870 VersionTuple Version; 19871 if (auto MaybeVersion = 19872 FindSpecVersion(Context.getTargetInfo().getPlatformName())) 19873 Version = *MaybeVersion; 19874 19875 // The use of `@available` in the enclosing context should be analyzed to 19876 // warn when it's used inappropriately (i.e. not if(@available)). 19877 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 19878 Context->HasPotentialAvailabilityViolations = true; 19879 19880 return new (Context) 19881 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19882 } 19883 19884 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19885 ArrayRef<Expr *> SubExprs, QualType T) { 19886 if (!Context.getLangOpts().RecoveryAST) 19887 return ExprError(); 19888 19889 if (isSFINAEContext()) 19890 return ExprError(); 19891 19892 if (T.isNull() || T->isUndeducedType() || 19893 !Context.getLangOpts().RecoveryASTType) 19894 // We don't know the concrete type, fallback to dependent type. 19895 T = Context.DependentTy; 19896 19897 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19898 } 19899