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/ParentMapContext.h" 29 #include "clang/AST/RecursiveASTVisitor.h" 30 #include "clang/AST/Type.h" 31 #include "clang/AST/TypeLoc.h" 32 #include "clang/Basic/Builtins.h" 33 #include "clang/Basic/DiagnosticSema.h" 34 #include "clang/Basic/PartialDiagnostic.h" 35 #include "clang/Basic/SourceManager.h" 36 #include "clang/Basic/Specifiers.h" 37 #include "clang/Basic/TargetInfo.h" 38 #include "clang/Lex/LiteralSupport.h" 39 #include "clang/Lex/Preprocessor.h" 40 #include "clang/Sema/AnalysisBasedWarnings.h" 41 #include "clang/Sema/DeclSpec.h" 42 #include "clang/Sema/DelayedDiagnostic.h" 43 #include "clang/Sema/Designator.h" 44 #include "clang/Sema/Initialization.h" 45 #include "clang/Sema/Lookup.h" 46 #include "clang/Sema/Overload.h" 47 #include "clang/Sema/ParsedTemplate.h" 48 #include "clang/Sema/Scope.h" 49 #include "clang/Sema/ScopeInfo.h" 50 #include "clang/Sema/SemaFixItUtils.h" 51 #include "clang/Sema/SemaInternal.h" 52 #include "clang/Sema/Template.h" 53 #include "llvm/ADT/STLExtras.h" 54 #include "llvm/ADT/StringExtras.h" 55 #include "llvm/Support/Casting.h" 56 #include "llvm/Support/ConvertUTF.h" 57 #include "llvm/Support/SaveAndRestore.h" 58 #include "llvm/Support/TypeSize.h" 59 60 using namespace clang; 61 using namespace sema; 62 63 /// Determine whether the use of this declaration is valid, without 64 /// emitting diagnostics. 65 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 66 // See if this is an auto-typed variable whose initializer we are parsing. 67 if (ParsingInitForAutoVars.count(D)) 68 return false; 69 70 // See if this is a deleted function. 71 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 72 if (FD->isDeleted()) 73 return false; 74 75 // If the function has a deduced return type, and we can't deduce it, 76 // then we can't use it either. 77 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 78 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 79 return false; 80 81 // See if this is an aligned allocation/deallocation function that is 82 // unavailable. 83 if (TreatUnavailableAsInvalid && 84 isUnavailableAlignedAllocationFunction(*FD)) 85 return false; 86 } 87 88 // See if this function is unavailable. 89 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 90 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 91 return false; 92 93 if (isa<UnresolvedUsingIfExistsDecl>(D)) 94 return false; 95 96 return true; 97 } 98 99 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 100 // Warn if this is used but marked unused. 101 if (const auto *A = D->getAttr<UnusedAttr>()) { 102 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 103 // should diagnose them. 104 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 105 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 106 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 107 if (DC && !DC->hasAttr<UnusedAttr>()) 108 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 109 } 110 } 111 } 112 113 /// Emit a note explaining that this function is deleted. 114 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 115 assert(Decl && Decl->isDeleted()); 116 117 if (Decl->isDefaulted()) { 118 // If the method was explicitly defaulted, point at that declaration. 119 if (!Decl->isImplicit()) 120 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 121 122 // Try to diagnose why this special member function was implicitly 123 // deleted. This might fail, if that reason no longer applies. 124 DiagnoseDeletedDefaultedFunction(Decl); 125 return; 126 } 127 128 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 129 if (Ctor && Ctor->isInheritingConstructor()) 130 return NoteDeletedInheritingConstructor(Ctor); 131 132 Diag(Decl->getLocation(), diag::note_availability_specified_here) 133 << Decl << 1; 134 } 135 136 /// Determine whether a FunctionDecl was ever declared with an 137 /// explicit storage class. 138 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 139 for (auto I : D->redecls()) { 140 if (I->getStorageClass() != SC_None) 141 return true; 142 } 143 return false; 144 } 145 146 /// Check whether we're in an extern inline function and referring to a 147 /// variable or function with internal linkage (C11 6.7.4p3). 148 /// 149 /// This is only a warning because we used to silently accept this code, but 150 /// in many cases it will not behave correctly. This is not enabled in C++ mode 151 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 152 /// and so while there may still be user mistakes, most of the time we can't 153 /// prove that there are errors. 154 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 155 const NamedDecl *D, 156 SourceLocation Loc) { 157 // This is disabled under C++; there are too many ways for this to fire in 158 // contexts where the warning is a false positive, or where it is technically 159 // correct but benign. 160 if (S.getLangOpts().CPlusPlus) 161 return; 162 163 // Check if this is an inlined function or method. 164 FunctionDecl *Current = S.getCurFunctionDecl(); 165 if (!Current) 166 return; 167 if (!Current->isInlined()) 168 return; 169 if (!Current->isExternallyVisible()) 170 return; 171 172 // Check if the decl has internal linkage. 173 if (D->getFormalLinkage() != InternalLinkage) 174 return; 175 176 // Downgrade from ExtWarn to Extension if 177 // (1) the supposedly external inline function is in the main file, 178 // and probably won't be included anywhere else. 179 // (2) the thing we're referencing is a pure function. 180 // (3) the thing we're referencing is another inline function. 181 // This last can give us false negatives, but it's better than warning on 182 // wrappers for simple C library functions. 183 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 184 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 185 if (!DowngradeWarning && UsedFn) 186 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 187 188 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 189 : diag::ext_internal_in_extern_inline) 190 << /*IsVar=*/!UsedFn << D; 191 192 S.MaybeSuggestAddingStaticToDecl(Current); 193 194 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 195 << D; 196 } 197 198 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 199 const FunctionDecl *First = Cur->getFirstDecl(); 200 201 // Suggest "static" on the function, if possible. 202 if (!hasAnyExplicitStorageClass(First)) { 203 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 204 Diag(DeclBegin, diag::note_convert_inline_to_static) 205 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 206 } 207 } 208 209 /// Determine whether the use of this declaration is valid, and 210 /// emit any corresponding diagnostics. 211 /// 212 /// This routine diagnoses various problems with referencing 213 /// declarations that can occur when using a declaration. For example, 214 /// it might warn if a deprecated or unavailable declaration is being 215 /// used, or produce an error (and return true) if a C++0x deleted 216 /// function is being used. 217 /// 218 /// \returns true if there was an error (this declaration cannot be 219 /// referenced), false otherwise. 220 /// 221 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 222 const ObjCInterfaceDecl *UnknownObjCClass, 223 bool ObjCPropertyAccess, 224 bool AvoidPartialAvailabilityChecks, 225 ObjCInterfaceDecl *ClassReceiver) { 226 SourceLocation Loc = Locs.front(); 227 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 228 // If there were any diagnostics suppressed by template argument deduction, 229 // emit them now. 230 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 231 if (Pos != SuppressedDiagnostics.end()) { 232 for (const PartialDiagnosticAt &Suppressed : Pos->second) 233 Diag(Suppressed.first, Suppressed.second); 234 235 // Clear out the list of suppressed diagnostics, so that we don't emit 236 // them again for this specialization. However, we don't obsolete this 237 // entry from the table, because we want to avoid ever emitting these 238 // diagnostics again. 239 Pos->second.clear(); 240 } 241 242 // C++ [basic.start.main]p3: 243 // The function 'main' shall not be used within a program. 244 if (cast<FunctionDecl>(D)->isMain()) 245 Diag(Loc, diag::ext_main_used); 246 247 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 248 } 249 250 // See if this is an auto-typed variable whose initializer we are parsing. 251 if (ParsingInitForAutoVars.count(D)) { 252 if (isa<BindingDecl>(D)) { 253 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 254 << D->getDeclName(); 255 } else { 256 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 257 << D->getDeclName() << cast<VarDecl>(D)->getType(); 258 } 259 return true; 260 } 261 262 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 263 // See if this is a deleted function. 264 if (FD->isDeleted()) { 265 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 266 if (Ctor && Ctor->isInheritingConstructor()) 267 Diag(Loc, diag::err_deleted_inherited_ctor_use) 268 << Ctor->getParent() 269 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 270 else 271 Diag(Loc, diag::err_deleted_function_use); 272 NoteDeletedFunction(FD); 273 return true; 274 } 275 276 // [expr.prim.id]p4 277 // A program that refers explicitly or implicitly to a function with a 278 // trailing requires-clause whose constraint-expression is not satisfied, 279 // other than to declare it, is ill-formed. [...] 280 // 281 // See if this is a function with constraints that need to be satisfied. 282 // Check this before deducing the return type, as it might instantiate the 283 // definition. 284 if (FD->getTrailingRequiresClause()) { 285 ConstraintSatisfaction Satisfaction; 286 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 287 // A diagnostic will have already been generated (non-constant 288 // constraint expression, for example) 289 return true; 290 if (!Satisfaction.IsSatisfied) { 291 Diag(Loc, 292 diag::err_reference_to_function_with_unsatisfied_constraints) 293 << D; 294 DiagnoseUnsatisfiedConstraint(Satisfaction); 295 return true; 296 } 297 } 298 299 // If the function has a deduced return type, and we can't deduce it, 300 // then we can't use it either. 301 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 302 DeduceReturnType(FD, Loc)) 303 return true; 304 305 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 306 return true; 307 308 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 309 return true; 310 } 311 312 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 313 // Lambdas are only default-constructible or assignable in C++2a onwards. 314 if (MD->getParent()->isLambda() && 315 ((isa<CXXConstructorDecl>(MD) && 316 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 317 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 318 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 319 << !isa<CXXConstructorDecl>(MD); 320 } 321 } 322 323 auto getReferencedObjCProp = [](const NamedDecl *D) -> 324 const ObjCPropertyDecl * { 325 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 326 return MD->findPropertyDecl(); 327 return nullptr; 328 }; 329 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 330 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 331 return true; 332 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 333 return true; 334 } 335 336 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 337 // Only the variables omp_in and omp_out are allowed in the combiner. 338 // Only the variables omp_priv and omp_orig are allowed in the 339 // initializer-clause. 340 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 341 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 342 isa<VarDecl>(D)) { 343 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 344 << getCurFunction()->HasOMPDeclareReductionCombiner; 345 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 346 return true; 347 } 348 349 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 350 // List-items in map clauses on this construct may only refer to the declared 351 // variable var and entities that could be referenced by a procedure defined 352 // at the same location 353 if (LangOpts.OpenMP && isa<VarDecl>(D) && 354 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 355 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 356 << getOpenMPDeclareMapperVarName(); 357 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 358 return true; 359 } 360 361 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) { 362 Diag(Loc, diag::err_use_of_empty_using_if_exists); 363 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); 364 return true; 365 } 366 367 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 368 AvoidPartialAvailabilityChecks, ClassReceiver); 369 370 DiagnoseUnusedOfDecl(*this, D, Loc); 371 372 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 373 374 if (auto *VD = dyn_cast<ValueDecl>(D)) 375 checkTypeSupport(VD->getType(), Loc, VD); 376 377 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 378 if (!Context.getTargetInfo().isTLSSupported()) 379 if (const auto *VD = dyn_cast<VarDecl>(D)) 380 if (VD->getTLSKind() != VarDecl::TLS_None) 381 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 382 } 383 384 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 385 !isUnevaluatedContext()) { 386 // C++ [expr.prim.req.nested] p3 387 // A local parameter shall only appear as an unevaluated operand 388 // (Clause 8) within the constraint-expression. 389 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 390 << D; 391 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 392 return true; 393 } 394 395 return false; 396 } 397 398 /// DiagnoseSentinelCalls - This routine checks whether a call or 399 /// message-send is to a declaration with the sentinel attribute, and 400 /// if so, it checks that the requirements of the sentinel are 401 /// satisfied. 402 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 403 ArrayRef<Expr *> Args) { 404 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 405 if (!attr) 406 return; 407 408 // The number of formal parameters of the declaration. 409 unsigned numFormalParams; 410 411 // The kind of declaration. This is also an index into a %select in 412 // the diagnostic. 413 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 414 415 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 416 numFormalParams = MD->param_size(); 417 calleeType = CT_Method; 418 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 419 numFormalParams = FD->param_size(); 420 calleeType = CT_Function; 421 } else if (isa<VarDecl>(D)) { 422 QualType type = cast<ValueDecl>(D)->getType(); 423 const FunctionType *fn = nullptr; 424 if (const PointerType *ptr = type->getAs<PointerType>()) { 425 fn = ptr->getPointeeType()->getAs<FunctionType>(); 426 if (!fn) return; 427 calleeType = CT_Function; 428 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 429 fn = ptr->getPointeeType()->castAs<FunctionType>(); 430 calleeType = CT_Block; 431 } else { 432 return; 433 } 434 435 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 436 numFormalParams = proto->getNumParams(); 437 } else { 438 numFormalParams = 0; 439 } 440 } else { 441 return; 442 } 443 444 // "nullPos" is the number of formal parameters at the end which 445 // effectively count as part of the variadic arguments. This is 446 // useful if you would prefer to not have *any* formal parameters, 447 // but the language forces you to have at least one. 448 unsigned nullPos = attr->getNullPos(); 449 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 450 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 451 452 // The number of arguments which should follow the sentinel. 453 unsigned numArgsAfterSentinel = attr->getSentinel(); 454 455 // If there aren't enough arguments for all the formal parameters, 456 // the sentinel, and the args after the sentinel, complain. 457 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 458 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 459 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 460 return; 461 } 462 463 // Otherwise, find the sentinel expression. 464 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 465 if (!sentinelExpr) return; 466 if (sentinelExpr->isValueDependent()) return; 467 if (Context.isSentinelNullExpr(sentinelExpr)) return; 468 469 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 470 // or 'NULL' if those are actually defined in the context. Only use 471 // 'nil' for ObjC methods, where it's much more likely that the 472 // variadic arguments form a list of object pointers. 473 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 474 std::string NullValue; 475 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 476 NullValue = "nil"; 477 else if (getLangOpts().CPlusPlus11) 478 NullValue = "nullptr"; 479 else if (PP.isMacroDefined("NULL")) 480 NullValue = "NULL"; 481 else 482 NullValue = "(void*) 0"; 483 484 if (MissingNilLoc.isInvalid()) 485 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 486 else 487 Diag(MissingNilLoc, diag::warn_missing_sentinel) 488 << int(calleeType) 489 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 490 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 491 } 492 493 SourceRange Sema::getExprRange(Expr *E) const { 494 return E ? E->getSourceRange() : SourceRange(); 495 } 496 497 //===----------------------------------------------------------------------===// 498 // Standard Promotions and Conversions 499 //===----------------------------------------------------------------------===// 500 501 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 502 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 503 // Handle any placeholder expressions which made it here. 504 if (E->hasPlaceholderType()) { 505 ExprResult result = CheckPlaceholderExpr(E); 506 if (result.isInvalid()) return ExprError(); 507 E = result.get(); 508 } 509 510 QualType Ty = E->getType(); 511 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 512 513 if (Ty->isFunctionType()) { 514 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 515 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 516 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 517 return ExprError(); 518 519 E = ImpCastExprToType(E, Context.getPointerType(Ty), 520 CK_FunctionToPointerDecay).get(); 521 } else if (Ty->isArrayType()) { 522 // In C90 mode, arrays only promote to pointers if the array expression is 523 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 524 // type 'array of type' is converted to an expression that has type 'pointer 525 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 526 // that has type 'array of type' ...". The relevant change is "an lvalue" 527 // (C90) to "an expression" (C99). 528 // 529 // C++ 4.2p1: 530 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 531 // T" can be converted to an rvalue of type "pointer to T". 532 // 533 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { 534 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 535 CK_ArrayToPointerDecay); 536 if (Res.isInvalid()) 537 return ExprError(); 538 E = Res.get(); 539 } 540 } 541 return E; 542 } 543 544 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 545 // Check to see if we are dereferencing a null pointer. If so, 546 // and if not volatile-qualified, this is undefined behavior that the 547 // optimizer will delete, so warn about it. People sometimes try to use this 548 // to get a deterministic trap and are surprised by clang's behavior. This 549 // only handles the pattern "*null", which is a very syntactic check. 550 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 551 if (UO && UO->getOpcode() == UO_Deref && 552 UO->getSubExpr()->getType()->isPointerType()) { 553 const LangAS AS = 554 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 555 if ((!isTargetAddressSpace(AS) || 556 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 557 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 558 S.Context, Expr::NPC_ValueDependentIsNotNull) && 559 !UO->getType().isVolatileQualified()) { 560 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 561 S.PDiag(diag::warn_indirection_through_null) 562 << UO->getSubExpr()->getSourceRange()); 563 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 564 S.PDiag(diag::note_indirection_through_null)); 565 } 566 } 567 } 568 569 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 570 SourceLocation AssignLoc, 571 const Expr* RHS) { 572 const ObjCIvarDecl *IV = OIRE->getDecl(); 573 if (!IV) 574 return; 575 576 DeclarationName MemberName = IV->getDeclName(); 577 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 578 if (!Member || !Member->isStr("isa")) 579 return; 580 581 const Expr *Base = OIRE->getBase(); 582 QualType BaseType = Base->getType(); 583 if (OIRE->isArrow()) 584 BaseType = BaseType->getPointeeType(); 585 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 586 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 587 ObjCInterfaceDecl *ClassDeclared = nullptr; 588 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 589 if (!ClassDeclared->getSuperClass() 590 && (*ClassDeclared->ivar_begin()) == IV) { 591 if (RHS) { 592 NamedDecl *ObjectSetClass = 593 S.LookupSingleName(S.TUScope, 594 &S.Context.Idents.get("object_setClass"), 595 SourceLocation(), S.LookupOrdinaryName); 596 if (ObjectSetClass) { 597 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 598 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 599 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 600 "object_setClass(") 601 << FixItHint::CreateReplacement( 602 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 603 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 604 } 605 else 606 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 607 } else { 608 NamedDecl *ObjectGetClass = 609 S.LookupSingleName(S.TUScope, 610 &S.Context.Idents.get("object_getClass"), 611 SourceLocation(), S.LookupOrdinaryName); 612 if (ObjectGetClass) 613 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 614 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 615 "object_getClass(") 616 << FixItHint::CreateReplacement( 617 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 618 else 619 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 620 } 621 S.Diag(IV->getLocation(), diag::note_ivar_decl); 622 } 623 } 624 } 625 626 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 627 // Handle any placeholder expressions which made it here. 628 if (E->hasPlaceholderType()) { 629 ExprResult result = CheckPlaceholderExpr(E); 630 if (result.isInvalid()) return ExprError(); 631 E = result.get(); 632 } 633 634 // C++ [conv.lval]p1: 635 // A glvalue of a non-function, non-array type T can be 636 // converted to a prvalue. 637 if (!E->isGLValue()) return E; 638 639 QualType T = E->getType(); 640 assert(!T.isNull() && "r-value conversion on typeless expression?"); 641 642 // lvalue-to-rvalue conversion cannot be applied to function or array types. 643 if (T->isFunctionType() || T->isArrayType()) 644 return E; 645 646 // We don't want to throw lvalue-to-rvalue casts on top of 647 // expressions of certain types in C++. 648 if (getLangOpts().CPlusPlus && 649 (E->getType() == Context.OverloadTy || 650 T->isDependentType() || 651 T->isRecordType())) 652 return E; 653 654 // The C standard is actually really unclear on this point, and 655 // DR106 tells us what the result should be but not why. It's 656 // generally best to say that void types just doesn't undergo 657 // lvalue-to-rvalue at all. Note that expressions of unqualified 658 // 'void' type are never l-values, but qualified void can be. 659 if (T->isVoidType()) 660 return E; 661 662 // OpenCL usually rejects direct accesses to values of 'half' type. 663 if (getLangOpts().OpenCL && 664 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 665 T->isHalfType()) { 666 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 667 << 0 << T; 668 return ExprError(); 669 } 670 671 CheckForNullPointerDereference(*this, E); 672 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 673 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 674 &Context.Idents.get("object_getClass"), 675 SourceLocation(), LookupOrdinaryName); 676 if (ObjectGetClass) 677 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 678 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 679 << FixItHint::CreateReplacement( 680 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 681 else 682 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 683 } 684 else if (const ObjCIvarRefExpr *OIRE = 685 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 686 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 687 688 // C++ [conv.lval]p1: 689 // [...] If T is a non-class type, the type of the prvalue is the 690 // cv-unqualified version of T. Otherwise, the type of the 691 // rvalue is T. 692 // 693 // C99 6.3.2.1p2: 694 // If the lvalue has qualified type, the value has the unqualified 695 // version of the type of the lvalue; otherwise, the value has the 696 // type of the lvalue. 697 if (T.hasQualifiers()) 698 T = T.getUnqualifiedType(); 699 700 // Under the MS ABI, lock down the inheritance model now. 701 if (T->isMemberPointerType() && 702 Context.getTargetInfo().getCXXABI().isMicrosoft()) 703 (void)isCompleteType(E->getExprLoc(), T); 704 705 ExprResult Res = CheckLValueToRValueConversionOperand(E); 706 if (Res.isInvalid()) 707 return Res; 708 E = Res.get(); 709 710 // Loading a __weak object implicitly retains the value, so we need a cleanup to 711 // balance that. 712 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 713 Cleanup.setExprNeedsCleanups(true); 714 715 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 716 Cleanup.setExprNeedsCleanups(true); 717 718 // C++ [conv.lval]p3: 719 // If T is cv std::nullptr_t, the result is a null pointer constant. 720 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 721 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, 722 CurFPFeatureOverrides()); 723 724 // C11 6.3.2.1p2: 725 // ... if the lvalue has atomic type, the value has the non-atomic version 726 // of the type of the lvalue ... 727 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 728 T = Atomic->getValueType().getUnqualifiedType(); 729 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 730 nullptr, VK_PRValue, FPOptionsOverride()); 731 } 732 733 return Res; 734 } 735 736 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 737 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 738 if (Res.isInvalid()) 739 return ExprError(); 740 Res = DefaultLvalueConversion(Res.get()); 741 if (Res.isInvalid()) 742 return ExprError(); 743 return Res; 744 } 745 746 /// CallExprUnaryConversions - a special case of an unary conversion 747 /// performed on a function designator of a call expression. 748 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 749 QualType Ty = E->getType(); 750 ExprResult Res = E; 751 // Only do implicit cast for a function type, but not for a pointer 752 // to function type. 753 if (Ty->isFunctionType()) { 754 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 755 CK_FunctionToPointerDecay); 756 if (Res.isInvalid()) 757 return ExprError(); 758 } 759 Res = DefaultLvalueConversion(Res.get()); 760 if (Res.isInvalid()) 761 return ExprError(); 762 return Res.get(); 763 } 764 765 /// UsualUnaryConversions - Performs various conversions that are common to most 766 /// operators (C99 6.3). The conversions of array and function types are 767 /// sometimes suppressed. For example, the array->pointer conversion doesn't 768 /// apply if the array is an argument to the sizeof or address (&) operators. 769 /// In these instances, this routine should *not* be called. 770 ExprResult Sema::UsualUnaryConversions(Expr *E) { 771 // First, convert to an r-value. 772 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 773 if (Res.isInvalid()) 774 return ExprError(); 775 E = Res.get(); 776 777 QualType Ty = E->getType(); 778 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 779 780 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod(); 781 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() && 782 (getLangOpts().getFPEvalMethod() != 783 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine || 784 PP.getLastFPEvalPragmaLocation().isValid())) { 785 switch (EvalMethod) { 786 default: 787 llvm_unreachable("Unrecognized float evaluation method"); 788 break; 789 case LangOptions::FEM_UnsetOnCommandLine: 790 llvm_unreachable("Float evaluation method should be set by now"); 791 break; 792 case LangOptions::FEM_Double: 793 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0) 794 // Widen the expression to double. 795 return Ty->isComplexType() 796 ? ImpCastExprToType(E, 797 Context.getComplexType(Context.DoubleTy), 798 CK_FloatingComplexCast) 799 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast); 800 break; 801 case LangOptions::FEM_Extended: 802 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0) 803 // Widen the expression to long double. 804 return Ty->isComplexType() 805 ? ImpCastExprToType( 806 E, Context.getComplexType(Context.LongDoubleTy), 807 CK_FloatingComplexCast) 808 : ImpCastExprToType(E, Context.LongDoubleTy, 809 CK_FloatingCast); 810 break; 811 } 812 } 813 814 // Half FP have to be promoted to float unless it is natively supported 815 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 816 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 817 818 // Try to perform integral promotions if the object has a theoretically 819 // promotable type. 820 if (Ty->isIntegralOrUnscopedEnumerationType()) { 821 // C99 6.3.1.1p2: 822 // 823 // The following may be used in an expression wherever an int or 824 // unsigned int may be used: 825 // - an object or expression with an integer type whose integer 826 // conversion rank is less than or equal to the rank of int 827 // and unsigned int. 828 // - A bit-field of type _Bool, int, signed int, or unsigned int. 829 // 830 // If an int can represent all values of the original type, the 831 // value is converted to an int; otherwise, it is converted to an 832 // unsigned int. These are called the integer promotions. All 833 // other types are unchanged by the integer promotions. 834 835 QualType PTy = Context.isPromotableBitField(E); 836 if (!PTy.isNull()) { 837 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 838 return E; 839 } 840 if (Ty->isPromotableIntegerType()) { 841 QualType PT = Context.getPromotedIntegerType(Ty); 842 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 843 return E; 844 } 845 } 846 return E; 847 } 848 849 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 850 /// do not have a prototype. Arguments that have type float or __fp16 851 /// are promoted to double. All other argument types are converted by 852 /// UsualUnaryConversions(). 853 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 854 QualType Ty = E->getType(); 855 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 856 857 ExprResult Res = UsualUnaryConversions(E); 858 if (Res.isInvalid()) 859 return ExprError(); 860 E = Res.get(); 861 862 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 863 // promote to double. 864 // Note that default argument promotion applies only to float (and 865 // half/fp16); it does not apply to _Float16. 866 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 867 if (BTy && (BTy->getKind() == BuiltinType::Half || 868 BTy->getKind() == BuiltinType::Float)) { 869 if (getLangOpts().OpenCL && 870 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 871 if (BTy->getKind() == BuiltinType::Half) { 872 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 873 } 874 } else { 875 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 876 } 877 } 878 if (BTy && 879 getLangOpts().getExtendIntArgs() == 880 LangOptions::ExtendArgsKind::ExtendTo64 && 881 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && 882 Context.getTypeSizeInChars(BTy) < 883 Context.getTypeSizeInChars(Context.LongLongTy)) { 884 E = (Ty->isUnsignedIntegerType()) 885 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) 886 .get() 887 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); 888 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && 889 "Unexpected typesize for LongLongTy"); 890 } 891 892 // C++ performs lvalue-to-rvalue conversion as a default argument 893 // promotion, even on class types, but note: 894 // C++11 [conv.lval]p2: 895 // When an lvalue-to-rvalue conversion occurs in an unevaluated 896 // operand or a subexpression thereof the value contained in the 897 // referenced object is not accessed. Otherwise, if the glvalue 898 // has a class type, the conversion copy-initializes a temporary 899 // of type T from the glvalue and the result of the conversion 900 // is a prvalue for the temporary. 901 // FIXME: add some way to gate this entire thing for correctness in 902 // potentially potentially evaluated contexts. 903 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 904 ExprResult Temp = PerformCopyInitialization( 905 InitializedEntity::InitializeTemporary(E->getType()), 906 E->getExprLoc(), E); 907 if (Temp.isInvalid()) 908 return ExprError(); 909 E = Temp.get(); 910 } 911 912 return E; 913 } 914 915 /// Determine the degree of POD-ness for an expression. 916 /// Incomplete types are considered POD, since this check can be performed 917 /// when we're in an unevaluated context. 918 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 919 if (Ty->isIncompleteType()) { 920 // C++11 [expr.call]p7: 921 // After these conversions, if the argument does not have arithmetic, 922 // enumeration, pointer, pointer to member, or class type, the program 923 // is ill-formed. 924 // 925 // Since we've already performed array-to-pointer and function-to-pointer 926 // decay, the only such type in C++ is cv void. This also handles 927 // initializer lists as variadic arguments. 928 if (Ty->isVoidType()) 929 return VAK_Invalid; 930 931 if (Ty->isObjCObjectType()) 932 return VAK_Invalid; 933 return VAK_Valid; 934 } 935 936 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 937 return VAK_Invalid; 938 939 if (Ty.isCXX98PODType(Context)) 940 return VAK_Valid; 941 942 // C++11 [expr.call]p7: 943 // Passing a potentially-evaluated argument of class type (Clause 9) 944 // having a non-trivial copy constructor, a non-trivial move constructor, 945 // or a non-trivial destructor, with no corresponding parameter, 946 // is conditionally-supported with implementation-defined semantics. 947 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 948 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 949 if (!Record->hasNonTrivialCopyConstructor() && 950 !Record->hasNonTrivialMoveConstructor() && 951 !Record->hasNonTrivialDestructor()) 952 return VAK_ValidInCXX11; 953 954 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 955 return VAK_Valid; 956 957 if (Ty->isObjCObjectType()) 958 return VAK_Invalid; 959 960 if (getLangOpts().MSVCCompat) 961 return VAK_MSVCUndefined; 962 963 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 964 // permitted to reject them. We should consider doing so. 965 return VAK_Undefined; 966 } 967 968 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 969 // Don't allow one to pass an Objective-C interface to a vararg. 970 const QualType &Ty = E->getType(); 971 VarArgKind VAK = isValidVarArgType(Ty); 972 973 // Complain about passing non-POD types through varargs. 974 switch (VAK) { 975 case VAK_ValidInCXX11: 976 DiagRuntimeBehavior( 977 E->getBeginLoc(), nullptr, 978 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 979 LLVM_FALLTHROUGH; 980 case VAK_Valid: 981 if (Ty->isRecordType()) { 982 // This is unlikely to be what the user intended. If the class has a 983 // 'c_str' member function, the user probably meant to call that. 984 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 985 PDiag(diag::warn_pass_class_arg_to_vararg) 986 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 987 } 988 break; 989 990 case VAK_Undefined: 991 case VAK_MSVCUndefined: 992 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 993 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 994 << getLangOpts().CPlusPlus11 << Ty << CT); 995 break; 996 997 case VAK_Invalid: 998 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 999 Diag(E->getBeginLoc(), 1000 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 1001 << Ty << CT; 1002 else if (Ty->isObjCObjectType()) 1003 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 1004 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 1005 << Ty << CT); 1006 else 1007 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 1008 << isa<InitListExpr>(E) << Ty << CT; 1009 break; 1010 } 1011 } 1012 1013 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 1014 /// will create a trap if the resulting type is not a POD type. 1015 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 1016 FunctionDecl *FDecl) { 1017 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 1018 // Strip the unbridged-cast placeholder expression off, if applicable. 1019 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 1020 (CT == VariadicMethod || 1021 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 1022 E = stripARCUnbridgedCast(E); 1023 1024 // Otherwise, do normal placeholder checking. 1025 } else { 1026 ExprResult ExprRes = CheckPlaceholderExpr(E); 1027 if (ExprRes.isInvalid()) 1028 return ExprError(); 1029 E = ExprRes.get(); 1030 } 1031 } 1032 1033 ExprResult ExprRes = DefaultArgumentPromotion(E); 1034 if (ExprRes.isInvalid()) 1035 return ExprError(); 1036 1037 // Copy blocks to the heap. 1038 if (ExprRes.get()->getType()->isBlockPointerType()) 1039 maybeExtendBlockObject(ExprRes); 1040 1041 E = ExprRes.get(); 1042 1043 // Diagnostics regarding non-POD argument types are 1044 // emitted along with format string checking in Sema::CheckFunctionCall(). 1045 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 1046 // Turn this into a trap. 1047 CXXScopeSpec SS; 1048 SourceLocation TemplateKWLoc; 1049 UnqualifiedId Name; 1050 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1051 E->getBeginLoc()); 1052 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1053 /*HasTrailingLParen=*/true, 1054 /*IsAddressOfOperand=*/false); 1055 if (TrapFn.isInvalid()) 1056 return ExprError(); 1057 1058 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1059 None, E->getEndLoc()); 1060 if (Call.isInvalid()) 1061 return ExprError(); 1062 1063 ExprResult Comma = 1064 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1065 if (Comma.isInvalid()) 1066 return ExprError(); 1067 return Comma.get(); 1068 } 1069 1070 if (!getLangOpts().CPlusPlus && 1071 RequireCompleteType(E->getExprLoc(), E->getType(), 1072 diag::err_call_incomplete_argument)) 1073 return ExprError(); 1074 1075 return E; 1076 } 1077 1078 /// Converts an integer to complex float type. Helper function of 1079 /// UsualArithmeticConversions() 1080 /// 1081 /// \return false if the integer expression is an integer type and is 1082 /// successfully converted to the complex type. 1083 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1084 ExprResult &ComplexExpr, 1085 QualType IntTy, 1086 QualType ComplexTy, 1087 bool SkipCast) { 1088 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1089 if (SkipCast) return false; 1090 if (IntTy->isIntegerType()) { 1091 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1092 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1093 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1094 CK_FloatingRealToComplex); 1095 } else { 1096 assert(IntTy->isComplexIntegerType()); 1097 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1098 CK_IntegralComplexToFloatingComplex); 1099 } 1100 return false; 1101 } 1102 1103 /// Handle arithmetic conversion with complex types. Helper function of 1104 /// UsualArithmeticConversions() 1105 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1106 ExprResult &RHS, QualType LHSType, 1107 QualType RHSType, 1108 bool IsCompAssign) { 1109 // if we have an integer operand, the result is the complex type. 1110 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1111 /*skipCast*/false)) 1112 return LHSType; 1113 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1114 /*skipCast*/IsCompAssign)) 1115 return RHSType; 1116 1117 // This handles complex/complex, complex/float, or float/complex. 1118 // When both operands are complex, the shorter operand is converted to the 1119 // type of the longer, and that is the type of the result. This corresponds 1120 // to what is done when combining two real floating-point operands. 1121 // The fun begins when size promotion occur across type domains. 1122 // From H&S 6.3.4: When one operand is complex and the other is a real 1123 // floating-point type, the less precise type is converted, within it's 1124 // real or complex domain, to the precision of the other type. For example, 1125 // when combining a "long double" with a "double _Complex", the 1126 // "double _Complex" is promoted to "long double _Complex". 1127 1128 // Compute the rank of the two types, regardless of whether they are complex. 1129 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1130 1131 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1132 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1133 QualType LHSElementType = 1134 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1135 QualType RHSElementType = 1136 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1137 1138 QualType ResultType = S.Context.getComplexType(LHSElementType); 1139 if (Order < 0) { 1140 // Promote the precision of the LHS if not an assignment. 1141 ResultType = S.Context.getComplexType(RHSElementType); 1142 if (!IsCompAssign) { 1143 if (LHSComplexType) 1144 LHS = 1145 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1146 else 1147 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1148 } 1149 } else if (Order > 0) { 1150 // Promote the precision of the RHS. 1151 if (RHSComplexType) 1152 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1153 else 1154 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1155 } 1156 return ResultType; 1157 } 1158 1159 /// Handle arithmetic conversion from integer to float. Helper function 1160 /// of UsualArithmeticConversions() 1161 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1162 ExprResult &IntExpr, 1163 QualType FloatTy, QualType IntTy, 1164 bool ConvertFloat, bool ConvertInt) { 1165 if (IntTy->isIntegerType()) { 1166 if (ConvertInt) 1167 // Convert intExpr to the lhs floating point type. 1168 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1169 CK_IntegralToFloating); 1170 return FloatTy; 1171 } 1172 1173 // Convert both sides to the appropriate complex float. 1174 assert(IntTy->isComplexIntegerType()); 1175 QualType result = S.Context.getComplexType(FloatTy); 1176 1177 // _Complex int -> _Complex float 1178 if (ConvertInt) 1179 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1180 CK_IntegralComplexToFloatingComplex); 1181 1182 // float -> _Complex float 1183 if (ConvertFloat) 1184 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1185 CK_FloatingRealToComplex); 1186 1187 return result; 1188 } 1189 1190 /// Handle arithmethic conversion with floating point types. Helper 1191 /// function of UsualArithmeticConversions() 1192 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1193 ExprResult &RHS, QualType LHSType, 1194 QualType RHSType, bool IsCompAssign) { 1195 bool LHSFloat = LHSType->isRealFloatingType(); 1196 bool RHSFloat = RHSType->isRealFloatingType(); 1197 1198 // N1169 4.1.4: If one of the operands has a floating type and the other 1199 // operand has a fixed-point type, the fixed-point operand 1200 // is converted to the floating type [...] 1201 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1202 if (LHSFloat) 1203 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1204 else if (!IsCompAssign) 1205 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1206 return LHSFloat ? LHSType : RHSType; 1207 } 1208 1209 // If we have two real floating types, convert the smaller operand 1210 // to the bigger result. 1211 if (LHSFloat && RHSFloat) { 1212 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1213 if (order > 0) { 1214 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1215 return LHSType; 1216 } 1217 1218 assert(order < 0 && "illegal float comparison"); 1219 if (!IsCompAssign) 1220 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1221 return RHSType; 1222 } 1223 1224 if (LHSFloat) { 1225 // Half FP has to be promoted to float unless it is natively supported 1226 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1227 LHSType = S.Context.FloatTy; 1228 1229 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1230 /*ConvertFloat=*/!IsCompAssign, 1231 /*ConvertInt=*/ true); 1232 } 1233 assert(RHSFloat); 1234 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1235 /*ConvertFloat=*/ true, 1236 /*ConvertInt=*/!IsCompAssign); 1237 } 1238 1239 /// Diagnose attempts to convert between __float128, __ibm128 and 1240 /// long double if there is no support for such conversion. 1241 /// Helper function of UsualArithmeticConversions(). 1242 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1243 QualType RHSType) { 1244 // No issue if either is not a floating point type. 1245 if (!LHSType->isFloatingType() || !RHSType->isFloatingType()) 1246 return false; 1247 1248 // No issue if both have the same 128-bit float semantics. 1249 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1250 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1251 1252 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType; 1253 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType; 1254 1255 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem); 1256 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem); 1257 1258 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() || 1259 &RHSSem != &llvm::APFloat::IEEEquad()) && 1260 (&LHSSem != &llvm::APFloat::IEEEquad() || 1261 &RHSSem != &llvm::APFloat::PPCDoubleDouble())) 1262 return false; 1263 1264 return true; 1265 } 1266 1267 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1268 1269 namespace { 1270 /// These helper callbacks are placed in an anonymous namespace to 1271 /// permit their use as function template parameters. 1272 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1273 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1274 } 1275 1276 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1277 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1278 CK_IntegralComplexCast); 1279 } 1280 } 1281 1282 /// Handle integer arithmetic conversions. Helper function of 1283 /// UsualArithmeticConversions() 1284 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1285 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1286 ExprResult &RHS, QualType LHSType, 1287 QualType RHSType, bool IsCompAssign) { 1288 // The rules for this case are in C99 6.3.1.8 1289 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1290 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1291 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1292 if (LHSSigned == RHSSigned) { 1293 // Same signedness; use the higher-ranked type 1294 if (order >= 0) { 1295 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1296 return LHSType; 1297 } else if (!IsCompAssign) 1298 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1299 return RHSType; 1300 } else if (order != (LHSSigned ? 1 : -1)) { 1301 // The unsigned type has greater than or equal rank to the 1302 // signed type, so use the unsigned type 1303 if (RHSSigned) { 1304 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1305 return LHSType; 1306 } else if (!IsCompAssign) 1307 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1308 return RHSType; 1309 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1310 // The two types are different widths; if we are here, that 1311 // means the signed type is larger than the unsigned type, so 1312 // use the signed type. 1313 if (LHSSigned) { 1314 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1315 return LHSType; 1316 } else if (!IsCompAssign) 1317 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1318 return RHSType; 1319 } else { 1320 // The signed type is higher-ranked than the unsigned type, 1321 // but isn't actually any bigger (like unsigned int and long 1322 // on most 32-bit systems). Use the unsigned type corresponding 1323 // to the signed type. 1324 QualType result = 1325 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1326 RHS = (*doRHSCast)(S, RHS.get(), result); 1327 if (!IsCompAssign) 1328 LHS = (*doLHSCast)(S, LHS.get(), result); 1329 return result; 1330 } 1331 } 1332 1333 /// Handle conversions with GCC complex int extension. Helper function 1334 /// of UsualArithmeticConversions() 1335 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1336 ExprResult &RHS, QualType LHSType, 1337 QualType RHSType, 1338 bool IsCompAssign) { 1339 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1340 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1341 1342 if (LHSComplexInt && RHSComplexInt) { 1343 QualType LHSEltType = LHSComplexInt->getElementType(); 1344 QualType RHSEltType = RHSComplexInt->getElementType(); 1345 QualType ScalarType = 1346 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1347 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1348 1349 return S.Context.getComplexType(ScalarType); 1350 } 1351 1352 if (LHSComplexInt) { 1353 QualType LHSEltType = LHSComplexInt->getElementType(); 1354 QualType ScalarType = 1355 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1356 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1357 QualType ComplexType = S.Context.getComplexType(ScalarType); 1358 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1359 CK_IntegralRealToComplex); 1360 1361 return ComplexType; 1362 } 1363 1364 assert(RHSComplexInt); 1365 1366 QualType RHSEltType = RHSComplexInt->getElementType(); 1367 QualType ScalarType = 1368 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1369 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1370 QualType ComplexType = S.Context.getComplexType(ScalarType); 1371 1372 if (!IsCompAssign) 1373 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1374 CK_IntegralRealToComplex); 1375 return ComplexType; 1376 } 1377 1378 /// Return the rank of a given fixed point or integer type. The value itself 1379 /// doesn't matter, but the values must be increasing with proper increasing 1380 /// rank as described in N1169 4.1.1. 1381 static unsigned GetFixedPointRank(QualType Ty) { 1382 const auto *BTy = Ty->getAs<BuiltinType>(); 1383 assert(BTy && "Expected a builtin type."); 1384 1385 switch (BTy->getKind()) { 1386 case BuiltinType::ShortFract: 1387 case BuiltinType::UShortFract: 1388 case BuiltinType::SatShortFract: 1389 case BuiltinType::SatUShortFract: 1390 return 1; 1391 case BuiltinType::Fract: 1392 case BuiltinType::UFract: 1393 case BuiltinType::SatFract: 1394 case BuiltinType::SatUFract: 1395 return 2; 1396 case BuiltinType::LongFract: 1397 case BuiltinType::ULongFract: 1398 case BuiltinType::SatLongFract: 1399 case BuiltinType::SatULongFract: 1400 return 3; 1401 case BuiltinType::ShortAccum: 1402 case BuiltinType::UShortAccum: 1403 case BuiltinType::SatShortAccum: 1404 case BuiltinType::SatUShortAccum: 1405 return 4; 1406 case BuiltinType::Accum: 1407 case BuiltinType::UAccum: 1408 case BuiltinType::SatAccum: 1409 case BuiltinType::SatUAccum: 1410 return 5; 1411 case BuiltinType::LongAccum: 1412 case BuiltinType::ULongAccum: 1413 case BuiltinType::SatLongAccum: 1414 case BuiltinType::SatULongAccum: 1415 return 6; 1416 default: 1417 if (BTy->isInteger()) 1418 return 0; 1419 llvm_unreachable("Unexpected fixed point or integer type"); 1420 } 1421 } 1422 1423 /// handleFixedPointConversion - Fixed point operations between fixed 1424 /// point types and integers or other fixed point types do not fall under 1425 /// usual arithmetic conversion since these conversions could result in loss 1426 /// of precsision (N1169 4.1.4). These operations should be calculated with 1427 /// the full precision of their result type (N1169 4.1.6.2.1). 1428 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1429 QualType RHSTy) { 1430 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1431 "Expected at least one of the operands to be a fixed point type"); 1432 assert((LHSTy->isFixedPointOrIntegerType() || 1433 RHSTy->isFixedPointOrIntegerType()) && 1434 "Special fixed point arithmetic operation conversions are only " 1435 "applied to ints or other fixed point types"); 1436 1437 // If one operand has signed fixed-point type and the other operand has 1438 // unsigned fixed-point type, then the unsigned fixed-point operand is 1439 // converted to its corresponding signed fixed-point type and the resulting 1440 // type is the type of the converted operand. 1441 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1442 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1443 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1444 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1445 1446 // The result type is the type with the highest rank, whereby a fixed-point 1447 // conversion rank is always greater than an integer conversion rank; if the 1448 // type of either of the operands is a saturating fixedpoint type, the result 1449 // type shall be the saturating fixed-point type corresponding to the type 1450 // with the highest rank; the resulting value is converted (taking into 1451 // account rounding and overflow) to the precision of the resulting type. 1452 // Same ranks between signed and unsigned types are resolved earlier, so both 1453 // types are either signed or both unsigned at this point. 1454 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1455 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1456 1457 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1458 1459 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1460 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1461 1462 return ResultTy; 1463 } 1464 1465 /// Check that the usual arithmetic conversions can be performed on this pair of 1466 /// expressions that might be of enumeration type. 1467 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1468 SourceLocation Loc, 1469 Sema::ArithConvKind ACK) { 1470 // C++2a [expr.arith.conv]p1: 1471 // If one operand is of enumeration type and the other operand is of a 1472 // different enumeration type or a floating-point type, this behavior is 1473 // deprecated ([depr.arith.conv.enum]). 1474 // 1475 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1476 // Eventually we will presumably reject these cases (in C++23 onwards?). 1477 QualType L = LHS->getType(), R = RHS->getType(); 1478 bool LEnum = L->isUnscopedEnumerationType(), 1479 REnum = R->isUnscopedEnumerationType(); 1480 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1481 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1482 (REnum && L->isFloatingType())) { 1483 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1484 ? diag::warn_arith_conv_enum_float_cxx20 1485 : diag::warn_arith_conv_enum_float) 1486 << LHS->getSourceRange() << RHS->getSourceRange() 1487 << (int)ACK << LEnum << L << R; 1488 } else if (!IsCompAssign && LEnum && REnum && 1489 !S.Context.hasSameUnqualifiedType(L, R)) { 1490 unsigned DiagID; 1491 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1492 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1493 // If either enumeration type is unnamed, it's less likely that the 1494 // user cares about this, but this situation is still deprecated in 1495 // C++2a. Use a different warning group. 1496 DiagID = S.getLangOpts().CPlusPlus20 1497 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1498 : diag::warn_arith_conv_mixed_anon_enum_types; 1499 } else if (ACK == Sema::ACK_Conditional) { 1500 // Conditional expressions are separated out because they have 1501 // historically had a different warning flag. 1502 DiagID = S.getLangOpts().CPlusPlus20 1503 ? diag::warn_conditional_mixed_enum_types_cxx20 1504 : diag::warn_conditional_mixed_enum_types; 1505 } else if (ACK == Sema::ACK_Comparison) { 1506 // Comparison expressions are separated out because they have 1507 // historically had a different warning flag. 1508 DiagID = S.getLangOpts().CPlusPlus20 1509 ? diag::warn_comparison_mixed_enum_types_cxx20 1510 : diag::warn_comparison_mixed_enum_types; 1511 } else { 1512 DiagID = S.getLangOpts().CPlusPlus20 1513 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1514 : diag::warn_arith_conv_mixed_enum_types; 1515 } 1516 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1517 << (int)ACK << L << R; 1518 } 1519 } 1520 1521 /// UsualArithmeticConversions - Performs various conversions that are common to 1522 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1523 /// routine returns the first non-arithmetic type found. The client is 1524 /// responsible for emitting appropriate error diagnostics. 1525 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1526 SourceLocation Loc, 1527 ArithConvKind ACK) { 1528 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1529 1530 if (ACK != ACK_CompAssign) { 1531 LHS = UsualUnaryConversions(LHS.get()); 1532 if (LHS.isInvalid()) 1533 return QualType(); 1534 } 1535 1536 RHS = UsualUnaryConversions(RHS.get()); 1537 if (RHS.isInvalid()) 1538 return QualType(); 1539 1540 // For conversion purposes, we ignore any qualifiers. 1541 // For example, "const float" and "float" are equivalent. 1542 QualType LHSType = 1543 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1544 QualType RHSType = 1545 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1546 1547 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1548 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1549 LHSType = AtomicLHS->getValueType(); 1550 1551 // If both types are identical, no conversion is needed. 1552 if (LHSType == RHSType) 1553 return LHSType; 1554 1555 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1556 // The caller can deal with this (e.g. pointer + int). 1557 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1558 return QualType(); 1559 1560 // Apply unary and bitfield promotions to the LHS's type. 1561 QualType LHSUnpromotedType = LHSType; 1562 if (LHSType->isPromotableIntegerType()) 1563 LHSType = Context.getPromotedIntegerType(LHSType); 1564 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1565 if (!LHSBitfieldPromoteTy.isNull()) 1566 LHSType = LHSBitfieldPromoteTy; 1567 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1568 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1569 1570 // If both types are identical, no conversion is needed. 1571 if (LHSType == RHSType) 1572 return LHSType; 1573 1574 // At this point, we have two different arithmetic types. 1575 1576 // Diagnose attempts to convert between __ibm128, __float128 and long double 1577 // where such conversions currently can't be handled. 1578 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1579 return QualType(); 1580 1581 // Handle complex types first (C99 6.3.1.8p1). 1582 if (LHSType->isComplexType() || RHSType->isComplexType()) 1583 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1584 ACK == ACK_CompAssign); 1585 1586 // Now handle "real" floating types (i.e. float, double, long double). 1587 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1588 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1589 ACK == ACK_CompAssign); 1590 1591 // Handle GCC complex int extension. 1592 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1593 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1594 ACK == ACK_CompAssign); 1595 1596 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1597 return handleFixedPointConversion(*this, LHSType, RHSType); 1598 1599 // Finally, we have two differing integer types. 1600 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1601 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1602 } 1603 1604 //===----------------------------------------------------------------------===// 1605 // Semantic Analysis for various Expression Types 1606 //===----------------------------------------------------------------------===// 1607 1608 1609 ExprResult 1610 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1611 SourceLocation DefaultLoc, 1612 SourceLocation RParenLoc, 1613 Expr *ControllingExpr, 1614 ArrayRef<ParsedType> ArgTypes, 1615 ArrayRef<Expr *> ArgExprs) { 1616 unsigned NumAssocs = ArgTypes.size(); 1617 assert(NumAssocs == ArgExprs.size()); 1618 1619 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1620 for (unsigned i = 0; i < NumAssocs; ++i) { 1621 if (ArgTypes[i]) 1622 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1623 else 1624 Types[i] = nullptr; 1625 } 1626 1627 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1628 ControllingExpr, 1629 llvm::makeArrayRef(Types, NumAssocs), 1630 ArgExprs); 1631 delete [] Types; 1632 return ER; 1633 } 1634 1635 ExprResult 1636 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1637 SourceLocation DefaultLoc, 1638 SourceLocation RParenLoc, 1639 Expr *ControllingExpr, 1640 ArrayRef<TypeSourceInfo *> Types, 1641 ArrayRef<Expr *> Exprs) { 1642 unsigned NumAssocs = Types.size(); 1643 assert(NumAssocs == Exprs.size()); 1644 1645 // Decay and strip qualifiers for the controlling expression type, and handle 1646 // placeholder type replacement. See committee discussion from WG14 DR423. 1647 { 1648 EnterExpressionEvaluationContext Unevaluated( 1649 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1650 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1651 if (R.isInvalid()) 1652 return ExprError(); 1653 ControllingExpr = R.get(); 1654 } 1655 1656 bool TypeErrorFound = false, 1657 IsResultDependent = ControllingExpr->isTypeDependent(), 1658 ContainsUnexpandedParameterPack 1659 = ControllingExpr->containsUnexpandedParameterPack(); 1660 1661 // The controlling expression is an unevaluated operand, so side effects are 1662 // likely unintended. 1663 if (!inTemplateInstantiation() && !IsResultDependent && 1664 ControllingExpr->HasSideEffects(Context, false)) 1665 Diag(ControllingExpr->getExprLoc(), 1666 diag::warn_side_effects_unevaluated_context); 1667 1668 for (unsigned i = 0; i < NumAssocs; ++i) { 1669 if (Exprs[i]->containsUnexpandedParameterPack()) 1670 ContainsUnexpandedParameterPack = true; 1671 1672 if (Types[i]) { 1673 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1674 ContainsUnexpandedParameterPack = true; 1675 1676 if (Types[i]->getType()->isDependentType()) { 1677 IsResultDependent = true; 1678 } else { 1679 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1680 // complete object type other than a variably modified type." 1681 unsigned D = 0; 1682 if (Types[i]->getType()->isIncompleteType()) 1683 D = diag::err_assoc_type_incomplete; 1684 else if (!Types[i]->getType()->isObjectType()) 1685 D = diag::err_assoc_type_nonobject; 1686 else if (Types[i]->getType()->isVariablyModifiedType()) 1687 D = diag::err_assoc_type_variably_modified; 1688 1689 if (D != 0) { 1690 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1691 << Types[i]->getTypeLoc().getSourceRange() 1692 << Types[i]->getType(); 1693 TypeErrorFound = true; 1694 } 1695 1696 // C11 6.5.1.1p2 "No two generic associations in the same generic 1697 // selection shall specify compatible types." 1698 for (unsigned j = i+1; j < NumAssocs; ++j) 1699 if (Types[j] && !Types[j]->getType()->isDependentType() && 1700 Context.typesAreCompatible(Types[i]->getType(), 1701 Types[j]->getType())) { 1702 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1703 diag::err_assoc_compatible_types) 1704 << Types[j]->getTypeLoc().getSourceRange() 1705 << Types[j]->getType() 1706 << Types[i]->getType(); 1707 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1708 diag::note_compat_assoc) 1709 << Types[i]->getTypeLoc().getSourceRange() 1710 << Types[i]->getType(); 1711 TypeErrorFound = true; 1712 } 1713 } 1714 } 1715 } 1716 if (TypeErrorFound) 1717 return ExprError(); 1718 1719 // If we determined that the generic selection is result-dependent, don't 1720 // try to compute the result expression. 1721 if (IsResultDependent) 1722 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1723 Exprs, DefaultLoc, RParenLoc, 1724 ContainsUnexpandedParameterPack); 1725 1726 SmallVector<unsigned, 1> CompatIndices; 1727 unsigned DefaultIndex = -1U; 1728 for (unsigned i = 0; i < NumAssocs; ++i) { 1729 if (!Types[i]) 1730 DefaultIndex = i; 1731 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1732 Types[i]->getType())) 1733 CompatIndices.push_back(i); 1734 } 1735 1736 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1737 // type compatible with at most one of the types named in its generic 1738 // association list." 1739 if (CompatIndices.size() > 1) { 1740 // We strip parens here because the controlling expression is typically 1741 // parenthesized in macro definitions. 1742 ControllingExpr = ControllingExpr->IgnoreParens(); 1743 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1744 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1745 << (unsigned)CompatIndices.size(); 1746 for (unsigned I : CompatIndices) { 1747 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1748 diag::note_compat_assoc) 1749 << Types[I]->getTypeLoc().getSourceRange() 1750 << Types[I]->getType(); 1751 } 1752 return ExprError(); 1753 } 1754 1755 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1756 // its controlling expression shall have type compatible with exactly one of 1757 // the types named in its generic association list." 1758 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1759 // We strip parens here because the controlling expression is typically 1760 // parenthesized in macro definitions. 1761 ControllingExpr = ControllingExpr->IgnoreParens(); 1762 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1763 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1764 return ExprError(); 1765 } 1766 1767 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1768 // type name that is compatible with the type of the controlling expression, 1769 // then the result expression of the generic selection is the expression 1770 // in that generic association. Otherwise, the result expression of the 1771 // generic selection is the expression in the default generic association." 1772 unsigned ResultIndex = 1773 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1774 1775 return GenericSelectionExpr::Create( 1776 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1777 ContainsUnexpandedParameterPack, ResultIndex); 1778 } 1779 1780 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1781 /// location of the token and the offset of the ud-suffix within it. 1782 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1783 unsigned Offset) { 1784 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1785 S.getLangOpts()); 1786 } 1787 1788 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1789 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1790 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1791 IdentifierInfo *UDSuffix, 1792 SourceLocation UDSuffixLoc, 1793 ArrayRef<Expr*> Args, 1794 SourceLocation LitEndLoc) { 1795 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1796 1797 QualType ArgTy[2]; 1798 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1799 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1800 if (ArgTy[ArgIdx]->isArrayType()) 1801 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1802 } 1803 1804 DeclarationName OpName = 1805 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1806 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1807 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1808 1809 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1810 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1811 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1812 /*AllowStringTemplatePack*/ false, 1813 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1814 return ExprError(); 1815 1816 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1817 } 1818 1819 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1820 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1821 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1822 /// multiple tokens. However, the common case is that StringToks points to one 1823 /// string. 1824 /// 1825 ExprResult 1826 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1827 assert(!StringToks.empty() && "Must have at least one string!"); 1828 1829 StringLiteralParser Literal(StringToks, PP); 1830 if (Literal.hadError) 1831 return ExprError(); 1832 1833 SmallVector<SourceLocation, 4> StringTokLocs; 1834 for (const Token &Tok : StringToks) 1835 StringTokLocs.push_back(Tok.getLocation()); 1836 1837 QualType CharTy = Context.CharTy; 1838 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1839 if (Literal.isWide()) { 1840 CharTy = Context.getWideCharType(); 1841 Kind = StringLiteral::Wide; 1842 } else if (Literal.isUTF8()) { 1843 if (getLangOpts().Char8) 1844 CharTy = Context.Char8Ty; 1845 Kind = StringLiteral::UTF8; 1846 } else if (Literal.isUTF16()) { 1847 CharTy = Context.Char16Ty; 1848 Kind = StringLiteral::UTF16; 1849 } else if (Literal.isUTF32()) { 1850 CharTy = Context.Char32Ty; 1851 Kind = StringLiteral::UTF32; 1852 } else if (Literal.isPascal()) { 1853 CharTy = Context.UnsignedCharTy; 1854 } 1855 1856 // Warn on initializing an array of char from a u8 string literal; this 1857 // becomes ill-formed in C++2a. 1858 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1859 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1860 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1861 1862 // Create removals for all 'u8' prefixes in the string literal(s). This 1863 // ensures C++2a compatibility (but may change the program behavior when 1864 // built by non-Clang compilers for which the execution character set is 1865 // not always UTF-8). 1866 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1867 SourceLocation RemovalDiagLoc; 1868 for (const Token &Tok : StringToks) { 1869 if (Tok.getKind() == tok::utf8_string_literal) { 1870 if (RemovalDiagLoc.isInvalid()) 1871 RemovalDiagLoc = Tok.getLocation(); 1872 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1873 Tok.getLocation(), 1874 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1875 getSourceManager(), getLangOpts()))); 1876 } 1877 } 1878 Diag(RemovalDiagLoc, RemovalDiag); 1879 } 1880 1881 QualType StrTy = 1882 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1883 1884 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1885 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1886 Kind, Literal.Pascal, StrTy, 1887 &StringTokLocs[0], 1888 StringTokLocs.size()); 1889 if (Literal.getUDSuffix().empty()) 1890 return Lit; 1891 1892 // We're building a user-defined literal. 1893 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1894 SourceLocation UDSuffixLoc = 1895 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1896 Literal.getUDSuffixOffset()); 1897 1898 // Make sure we're allowed user-defined literals here. 1899 if (!UDLScope) 1900 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1901 1902 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1903 // operator "" X (str, len) 1904 QualType SizeType = Context.getSizeType(); 1905 1906 DeclarationName OpName = 1907 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1908 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1909 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1910 1911 QualType ArgTy[] = { 1912 Context.getArrayDecayedType(StrTy), SizeType 1913 }; 1914 1915 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1916 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1917 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1918 /*AllowStringTemplatePack*/ true, 1919 /*DiagnoseMissing*/ true, Lit)) { 1920 1921 case LOLR_Cooked: { 1922 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1923 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1924 StringTokLocs[0]); 1925 Expr *Args[] = { Lit, LenArg }; 1926 1927 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1928 } 1929 1930 case LOLR_Template: { 1931 TemplateArgumentListInfo ExplicitArgs; 1932 TemplateArgument Arg(Lit); 1933 TemplateArgumentLocInfo ArgInfo(Lit); 1934 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1935 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1936 &ExplicitArgs); 1937 } 1938 1939 case LOLR_StringTemplatePack: { 1940 TemplateArgumentListInfo ExplicitArgs; 1941 1942 unsigned CharBits = Context.getIntWidth(CharTy); 1943 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1944 llvm::APSInt Value(CharBits, CharIsUnsigned); 1945 1946 TemplateArgument TypeArg(CharTy); 1947 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1948 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1949 1950 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1951 Value = Lit->getCodeUnit(I); 1952 TemplateArgument Arg(Context, Value, CharTy); 1953 TemplateArgumentLocInfo ArgInfo; 1954 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1955 } 1956 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1957 &ExplicitArgs); 1958 } 1959 case LOLR_Raw: 1960 case LOLR_ErrorNoDiagnostic: 1961 llvm_unreachable("unexpected literal operator lookup result"); 1962 case LOLR_Error: 1963 return ExprError(); 1964 } 1965 llvm_unreachable("unexpected literal operator lookup result"); 1966 } 1967 1968 DeclRefExpr * 1969 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1970 SourceLocation Loc, 1971 const CXXScopeSpec *SS) { 1972 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1973 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1974 } 1975 1976 DeclRefExpr * 1977 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1978 const DeclarationNameInfo &NameInfo, 1979 const CXXScopeSpec *SS, NamedDecl *FoundD, 1980 SourceLocation TemplateKWLoc, 1981 const TemplateArgumentListInfo *TemplateArgs) { 1982 NestedNameSpecifierLoc NNS = 1983 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1984 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1985 TemplateArgs); 1986 } 1987 1988 // CUDA/HIP: Check whether a captured reference variable is referencing a 1989 // host variable in a device or host device lambda. 1990 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1991 VarDecl *VD) { 1992 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1993 return false; 1994 assert(VD->getType()->isReferenceType()); 1995 1996 // Check whether the reference variable is referencing a host variable. 1997 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1998 if (!DRE) 1999 return false; 2000 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 2001 if (!Referee || !Referee->hasGlobalStorage() || 2002 Referee->hasAttr<CUDADeviceAttr>()) 2003 return false; 2004 2005 // Check whether the current function is a device or host device lambda. 2006 // Check whether the reference variable is a capture by getDeclContext() 2007 // since refersToEnclosingVariableOrCapture() is not ready at this point. 2008 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 2009 if (MD && MD->getParent()->isLambda() && 2010 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 2011 VD->getDeclContext() != MD) 2012 return true; 2013 2014 return false; 2015 } 2016 2017 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 2018 // A declaration named in an unevaluated operand never constitutes an odr-use. 2019 if (isUnevaluatedContext()) 2020 return NOUR_Unevaluated; 2021 2022 // C++2a [basic.def.odr]p4: 2023 // A variable x whose name appears as a potentially-evaluated expression e 2024 // is odr-used by e unless [...] x is a reference that is usable in 2025 // constant expressions. 2026 // CUDA/HIP: 2027 // If a reference variable referencing a host variable is captured in a 2028 // device or host device lambda, the value of the referee must be copied 2029 // to the capture and the reference variable must be treated as odr-use 2030 // since the value of the referee is not known at compile time and must 2031 // be loaded from the captured. 2032 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2033 if (VD->getType()->isReferenceType() && 2034 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 2035 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 2036 VD->isUsableInConstantExpressions(Context)) 2037 return NOUR_Constant; 2038 } 2039 2040 // All remaining non-variable cases constitute an odr-use. For variables, we 2041 // need to wait and see how the expression is used. 2042 return NOUR_None; 2043 } 2044 2045 /// BuildDeclRefExpr - Build an expression that references a 2046 /// declaration that does not require a closure capture. 2047 DeclRefExpr * 2048 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2049 const DeclarationNameInfo &NameInfo, 2050 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2051 SourceLocation TemplateKWLoc, 2052 const TemplateArgumentListInfo *TemplateArgs) { 2053 bool RefersToCapturedVariable = 2054 isa<VarDecl>(D) && 2055 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2056 2057 DeclRefExpr *E = DeclRefExpr::Create( 2058 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2059 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2060 MarkDeclRefReferenced(E); 2061 2062 // C++ [except.spec]p17: 2063 // An exception-specification is considered to be needed when: 2064 // - in an expression, the function is the unique lookup result or 2065 // the selected member of a set of overloaded functions. 2066 // 2067 // We delay doing this until after we've built the function reference and 2068 // marked it as used so that: 2069 // a) if the function is defaulted, we get errors from defining it before / 2070 // instead of errors from computing its exception specification, and 2071 // b) if the function is a defaulted comparison, we can use the body we 2072 // build when defining it as input to the exception specification 2073 // computation rather than computing a new body. 2074 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2075 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2076 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2077 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2078 } 2079 } 2080 2081 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2082 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2083 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2084 getCurFunction()->recordUseOfWeak(E); 2085 2086 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2087 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2088 FD = IFD->getAnonField(); 2089 if (FD) { 2090 UnusedPrivateFields.remove(FD); 2091 // Just in case we're building an illegal pointer-to-member. 2092 if (FD->isBitField()) 2093 E->setObjectKind(OK_BitField); 2094 } 2095 2096 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2097 // designates a bit-field. 2098 if (auto *BD = dyn_cast<BindingDecl>(D)) 2099 if (auto *BE = BD->getBinding()) 2100 E->setObjectKind(BE->getObjectKind()); 2101 2102 return E; 2103 } 2104 2105 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2106 /// possibly a list of template arguments. 2107 /// 2108 /// If this produces template arguments, it is permitted to call 2109 /// DecomposeTemplateName. 2110 /// 2111 /// This actually loses a lot of source location information for 2112 /// non-standard name kinds; we should consider preserving that in 2113 /// some way. 2114 void 2115 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2116 TemplateArgumentListInfo &Buffer, 2117 DeclarationNameInfo &NameInfo, 2118 const TemplateArgumentListInfo *&TemplateArgs) { 2119 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2120 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2121 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2122 2123 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2124 Id.TemplateId->NumArgs); 2125 translateTemplateArguments(TemplateArgsPtr, Buffer); 2126 2127 TemplateName TName = Id.TemplateId->Template.get(); 2128 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2129 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2130 TemplateArgs = &Buffer; 2131 } else { 2132 NameInfo = GetNameFromUnqualifiedId(Id); 2133 TemplateArgs = nullptr; 2134 } 2135 } 2136 2137 static void emitEmptyLookupTypoDiagnostic( 2138 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2139 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2140 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2141 DeclContext *Ctx = 2142 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2143 if (!TC) { 2144 // Emit a special diagnostic for failed member lookups. 2145 // FIXME: computing the declaration context might fail here (?) 2146 if (Ctx) 2147 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2148 << SS.getRange(); 2149 else 2150 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2151 return; 2152 } 2153 2154 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2155 bool DroppedSpecifier = 2156 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2157 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2158 ? diag::note_implicit_param_decl 2159 : diag::note_previous_decl; 2160 if (!Ctx) 2161 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2162 SemaRef.PDiag(NoteID)); 2163 else 2164 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2165 << Typo << Ctx << DroppedSpecifier 2166 << SS.getRange(), 2167 SemaRef.PDiag(NoteID)); 2168 } 2169 2170 /// Diagnose a lookup that found results in an enclosing class during error 2171 /// recovery. This usually indicates that the results were found in a dependent 2172 /// base class that could not be searched as part of a template definition. 2173 /// Always issues a diagnostic (though this may be only a warning in MS 2174 /// compatibility mode). 2175 /// 2176 /// Return \c true if the error is unrecoverable, or \c false if the caller 2177 /// should attempt to recover using these lookup results. 2178 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2179 // During a default argument instantiation the CurContext points 2180 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2181 // function parameter list, hence add an explicit check. 2182 bool isDefaultArgument = 2183 !CodeSynthesisContexts.empty() && 2184 CodeSynthesisContexts.back().Kind == 2185 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2186 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2187 bool isInstance = CurMethod && CurMethod->isInstance() && 2188 R.getNamingClass() == CurMethod->getParent() && 2189 !isDefaultArgument; 2190 2191 // There are two ways we can find a class-scope declaration during template 2192 // instantiation that we did not find in the template definition: if it is a 2193 // member of a dependent base class, or if it is declared after the point of 2194 // use in the same class. Distinguish these by comparing the class in which 2195 // the member was found to the naming class of the lookup. 2196 unsigned DiagID = diag::err_found_in_dependent_base; 2197 unsigned NoteID = diag::note_member_declared_at; 2198 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2199 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2200 : diag::err_found_later_in_class; 2201 } else if (getLangOpts().MSVCCompat) { 2202 DiagID = diag::ext_found_in_dependent_base; 2203 NoteID = diag::note_dependent_member_use; 2204 } 2205 2206 if (isInstance) { 2207 // Give a code modification hint to insert 'this->'. 2208 Diag(R.getNameLoc(), DiagID) 2209 << R.getLookupName() 2210 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2211 CheckCXXThisCapture(R.getNameLoc()); 2212 } else { 2213 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2214 // they're not shadowed). 2215 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2216 } 2217 2218 for (NamedDecl *D : R) 2219 Diag(D->getLocation(), NoteID); 2220 2221 // Return true if we are inside a default argument instantiation 2222 // and the found name refers to an instance member function, otherwise 2223 // the caller will try to create an implicit member call and this is wrong 2224 // for default arguments. 2225 // 2226 // FIXME: Is this special case necessary? We could allow the caller to 2227 // diagnose this. 2228 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2229 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2230 return true; 2231 } 2232 2233 // Tell the callee to try to recover. 2234 return false; 2235 } 2236 2237 /// Diagnose an empty lookup. 2238 /// 2239 /// \return false if new lookup candidates were found 2240 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2241 CorrectionCandidateCallback &CCC, 2242 TemplateArgumentListInfo *ExplicitTemplateArgs, 2243 ArrayRef<Expr *> Args, TypoExpr **Out) { 2244 DeclarationName Name = R.getLookupName(); 2245 2246 unsigned diagnostic = diag::err_undeclared_var_use; 2247 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2248 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2249 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2250 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2251 diagnostic = diag::err_undeclared_use; 2252 diagnostic_suggest = diag::err_undeclared_use_suggest; 2253 } 2254 2255 // If the original lookup was an unqualified lookup, fake an 2256 // unqualified lookup. This is useful when (for example) the 2257 // original lookup would not have found something because it was a 2258 // dependent name. 2259 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2260 while (DC) { 2261 if (isa<CXXRecordDecl>(DC)) { 2262 LookupQualifiedName(R, DC); 2263 2264 if (!R.empty()) { 2265 // Don't give errors about ambiguities in this lookup. 2266 R.suppressDiagnostics(); 2267 2268 // If there's a best viable function among the results, only mention 2269 // that one in the notes. 2270 OverloadCandidateSet Candidates(R.getNameLoc(), 2271 OverloadCandidateSet::CSK_Normal); 2272 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2273 OverloadCandidateSet::iterator Best; 2274 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2275 OR_Success) { 2276 R.clear(); 2277 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2278 R.resolveKind(); 2279 } 2280 2281 return DiagnoseDependentMemberLookup(R); 2282 } 2283 2284 R.clear(); 2285 } 2286 2287 DC = DC->getLookupParent(); 2288 } 2289 2290 // We didn't find anything, so try to correct for a typo. 2291 TypoCorrection Corrected; 2292 if (S && Out) { 2293 SourceLocation TypoLoc = R.getNameLoc(); 2294 assert(!ExplicitTemplateArgs && 2295 "Diagnosing an empty lookup with explicit template args!"); 2296 *Out = CorrectTypoDelayed( 2297 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2298 [=](const TypoCorrection &TC) { 2299 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2300 diagnostic, diagnostic_suggest); 2301 }, 2302 nullptr, CTK_ErrorRecovery); 2303 if (*Out) 2304 return true; 2305 } else if (S && 2306 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2307 S, &SS, CCC, CTK_ErrorRecovery))) { 2308 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2309 bool DroppedSpecifier = 2310 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2311 R.setLookupName(Corrected.getCorrection()); 2312 2313 bool AcceptableWithRecovery = false; 2314 bool AcceptableWithoutRecovery = false; 2315 NamedDecl *ND = Corrected.getFoundDecl(); 2316 if (ND) { 2317 if (Corrected.isOverloaded()) { 2318 OverloadCandidateSet OCS(R.getNameLoc(), 2319 OverloadCandidateSet::CSK_Normal); 2320 OverloadCandidateSet::iterator Best; 2321 for (NamedDecl *CD : Corrected) { 2322 if (FunctionTemplateDecl *FTD = 2323 dyn_cast<FunctionTemplateDecl>(CD)) 2324 AddTemplateOverloadCandidate( 2325 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2326 Args, OCS); 2327 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2328 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2329 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2330 Args, OCS); 2331 } 2332 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2333 case OR_Success: 2334 ND = Best->FoundDecl; 2335 Corrected.setCorrectionDecl(ND); 2336 break; 2337 default: 2338 // FIXME: Arbitrarily pick the first declaration for the note. 2339 Corrected.setCorrectionDecl(ND); 2340 break; 2341 } 2342 } 2343 R.addDecl(ND); 2344 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2345 CXXRecordDecl *Record = nullptr; 2346 if (Corrected.getCorrectionSpecifier()) { 2347 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2348 Record = Ty->getAsCXXRecordDecl(); 2349 } 2350 if (!Record) 2351 Record = cast<CXXRecordDecl>( 2352 ND->getDeclContext()->getRedeclContext()); 2353 R.setNamingClass(Record); 2354 } 2355 2356 auto *UnderlyingND = ND->getUnderlyingDecl(); 2357 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2358 isa<FunctionTemplateDecl>(UnderlyingND); 2359 // FIXME: If we ended up with a typo for a type name or 2360 // Objective-C class name, we're in trouble because the parser 2361 // is in the wrong place to recover. Suggest the typo 2362 // correction, but don't make it a fix-it since we're not going 2363 // to recover well anyway. 2364 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2365 getAsTypeTemplateDecl(UnderlyingND) || 2366 isa<ObjCInterfaceDecl>(UnderlyingND); 2367 } else { 2368 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2369 // because we aren't able to recover. 2370 AcceptableWithoutRecovery = true; 2371 } 2372 2373 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2374 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2375 ? diag::note_implicit_param_decl 2376 : diag::note_previous_decl; 2377 if (SS.isEmpty()) 2378 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2379 PDiag(NoteID), AcceptableWithRecovery); 2380 else 2381 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2382 << Name << computeDeclContext(SS, false) 2383 << DroppedSpecifier << SS.getRange(), 2384 PDiag(NoteID), AcceptableWithRecovery); 2385 2386 // Tell the callee whether to try to recover. 2387 return !AcceptableWithRecovery; 2388 } 2389 } 2390 R.clear(); 2391 2392 // Emit a special diagnostic for failed member lookups. 2393 // FIXME: computing the declaration context might fail here (?) 2394 if (!SS.isEmpty()) { 2395 Diag(R.getNameLoc(), diag::err_no_member) 2396 << Name << computeDeclContext(SS, false) 2397 << SS.getRange(); 2398 return true; 2399 } 2400 2401 // Give up, we can't recover. 2402 Diag(R.getNameLoc(), diagnostic) << Name; 2403 return true; 2404 } 2405 2406 /// In Microsoft mode, if we are inside a template class whose parent class has 2407 /// dependent base classes, and we can't resolve an unqualified identifier, then 2408 /// assume the identifier is a member of a dependent base class. We can only 2409 /// recover successfully in static methods, instance methods, and other contexts 2410 /// where 'this' is available. This doesn't precisely match MSVC's 2411 /// instantiation model, but it's close enough. 2412 static Expr * 2413 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2414 DeclarationNameInfo &NameInfo, 2415 SourceLocation TemplateKWLoc, 2416 const TemplateArgumentListInfo *TemplateArgs) { 2417 // Only try to recover from lookup into dependent bases in static methods or 2418 // contexts where 'this' is available. 2419 QualType ThisType = S.getCurrentThisType(); 2420 const CXXRecordDecl *RD = nullptr; 2421 if (!ThisType.isNull()) 2422 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2423 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2424 RD = MD->getParent(); 2425 if (!RD || !RD->hasAnyDependentBases()) 2426 return nullptr; 2427 2428 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2429 // is available, suggest inserting 'this->' as a fixit. 2430 SourceLocation Loc = NameInfo.getLoc(); 2431 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2432 DB << NameInfo.getName() << RD; 2433 2434 if (!ThisType.isNull()) { 2435 DB << FixItHint::CreateInsertion(Loc, "this->"); 2436 return CXXDependentScopeMemberExpr::Create( 2437 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2438 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2439 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2440 } 2441 2442 // Synthesize a fake NNS that points to the derived class. This will 2443 // perform name lookup during template instantiation. 2444 CXXScopeSpec SS; 2445 auto *NNS = 2446 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2447 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2448 return DependentScopeDeclRefExpr::Create( 2449 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2450 TemplateArgs); 2451 } 2452 2453 ExprResult 2454 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2455 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2456 bool HasTrailingLParen, bool IsAddressOfOperand, 2457 CorrectionCandidateCallback *CCC, 2458 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2459 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2460 "cannot be direct & operand and have a trailing lparen"); 2461 if (SS.isInvalid()) 2462 return ExprError(); 2463 2464 TemplateArgumentListInfo TemplateArgsBuffer; 2465 2466 // Decompose the UnqualifiedId into the following data. 2467 DeclarationNameInfo NameInfo; 2468 const TemplateArgumentListInfo *TemplateArgs; 2469 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2470 2471 DeclarationName Name = NameInfo.getName(); 2472 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2473 SourceLocation NameLoc = NameInfo.getLoc(); 2474 2475 if (II && II->isEditorPlaceholder()) { 2476 // FIXME: When typed placeholders are supported we can create a typed 2477 // placeholder expression node. 2478 return ExprError(); 2479 } 2480 2481 // C++ [temp.dep.expr]p3: 2482 // An id-expression is type-dependent if it contains: 2483 // -- an identifier that was declared with a dependent type, 2484 // (note: handled after lookup) 2485 // -- a template-id that is dependent, 2486 // (note: handled in BuildTemplateIdExpr) 2487 // -- a conversion-function-id that specifies a dependent type, 2488 // -- a nested-name-specifier that contains a class-name that 2489 // names a dependent type. 2490 // Determine whether this is a member of an unknown specialization; 2491 // we need to handle these differently. 2492 bool DependentID = false; 2493 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2494 Name.getCXXNameType()->isDependentType()) { 2495 DependentID = true; 2496 } else if (SS.isSet()) { 2497 if (DeclContext *DC = computeDeclContext(SS, false)) { 2498 if (RequireCompleteDeclContext(SS, DC)) 2499 return ExprError(); 2500 } else { 2501 DependentID = true; 2502 } 2503 } 2504 2505 if (DependentID) 2506 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2507 IsAddressOfOperand, TemplateArgs); 2508 2509 // Perform the required lookup. 2510 LookupResult R(*this, NameInfo, 2511 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2512 ? LookupObjCImplicitSelfParam 2513 : LookupOrdinaryName); 2514 if (TemplateKWLoc.isValid() || TemplateArgs) { 2515 // Lookup the template name again to correctly establish the context in 2516 // which it was found. This is really unfortunate as we already did the 2517 // lookup to determine that it was a template name in the first place. If 2518 // this becomes a performance hit, we can work harder to preserve those 2519 // results until we get here but it's likely not worth it. 2520 bool MemberOfUnknownSpecialization; 2521 AssumedTemplateKind AssumedTemplate; 2522 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2523 MemberOfUnknownSpecialization, TemplateKWLoc, 2524 &AssumedTemplate)) 2525 return ExprError(); 2526 2527 if (MemberOfUnknownSpecialization || 2528 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2529 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2530 IsAddressOfOperand, TemplateArgs); 2531 } else { 2532 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2533 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2534 2535 // If the result might be in a dependent base class, this is a dependent 2536 // id-expression. 2537 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2538 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2539 IsAddressOfOperand, TemplateArgs); 2540 2541 // If this reference is in an Objective-C method, then we need to do 2542 // some special Objective-C lookup, too. 2543 if (IvarLookupFollowUp) { 2544 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2545 if (E.isInvalid()) 2546 return ExprError(); 2547 2548 if (Expr *Ex = E.getAs<Expr>()) 2549 return Ex; 2550 } 2551 } 2552 2553 if (R.isAmbiguous()) 2554 return ExprError(); 2555 2556 // This could be an implicitly declared function reference if the language 2557 // mode allows it as a feature. 2558 if (R.empty() && HasTrailingLParen && II && 2559 getLangOpts().implicitFunctionsAllowed()) { 2560 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2561 if (D) R.addDecl(D); 2562 } 2563 2564 // Determine whether this name might be a candidate for 2565 // argument-dependent lookup. 2566 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2567 2568 if (R.empty() && !ADL) { 2569 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2570 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2571 TemplateKWLoc, TemplateArgs)) 2572 return E; 2573 } 2574 2575 // Don't diagnose an empty lookup for inline assembly. 2576 if (IsInlineAsmIdentifier) 2577 return ExprError(); 2578 2579 // If this name wasn't predeclared and if this is not a function 2580 // call, diagnose the problem. 2581 TypoExpr *TE = nullptr; 2582 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2583 : nullptr); 2584 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2585 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2586 "Typo correction callback misconfigured"); 2587 if (CCC) { 2588 // Make sure the callback knows what the typo being diagnosed is. 2589 CCC->setTypoName(II); 2590 if (SS.isValid()) 2591 CCC->setTypoNNS(SS.getScopeRep()); 2592 } 2593 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2594 // a template name, but we happen to have always already looked up the name 2595 // before we get here if it must be a template name. 2596 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2597 None, &TE)) { 2598 if (TE && KeywordReplacement) { 2599 auto &State = getTypoExprState(TE); 2600 auto BestTC = State.Consumer->getNextCorrection(); 2601 if (BestTC.isKeyword()) { 2602 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2603 if (State.DiagHandler) 2604 State.DiagHandler(BestTC); 2605 KeywordReplacement->startToken(); 2606 KeywordReplacement->setKind(II->getTokenID()); 2607 KeywordReplacement->setIdentifierInfo(II); 2608 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2609 // Clean up the state associated with the TypoExpr, since it has 2610 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2611 clearDelayedTypo(TE); 2612 // Signal that a correction to a keyword was performed by returning a 2613 // valid-but-null ExprResult. 2614 return (Expr*)nullptr; 2615 } 2616 State.Consumer->resetCorrectionStream(); 2617 } 2618 return TE ? TE : ExprError(); 2619 } 2620 2621 assert(!R.empty() && 2622 "DiagnoseEmptyLookup returned false but added no results"); 2623 2624 // If we found an Objective-C instance variable, let 2625 // LookupInObjCMethod build the appropriate expression to 2626 // reference the ivar. 2627 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2628 R.clear(); 2629 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2630 // In a hopelessly buggy code, Objective-C instance variable 2631 // lookup fails and no expression will be built to reference it. 2632 if (!E.isInvalid() && !E.get()) 2633 return ExprError(); 2634 return E; 2635 } 2636 } 2637 2638 // This is guaranteed from this point on. 2639 assert(!R.empty() || ADL); 2640 2641 // Check whether this might be a C++ implicit instance member access. 2642 // C++ [class.mfct.non-static]p3: 2643 // When an id-expression that is not part of a class member access 2644 // syntax and not used to form a pointer to member is used in the 2645 // body of a non-static member function of class X, if name lookup 2646 // resolves the name in the id-expression to a non-static non-type 2647 // member of some class C, the id-expression is transformed into a 2648 // class member access expression using (*this) as the 2649 // postfix-expression to the left of the . operator. 2650 // 2651 // But we don't actually need to do this for '&' operands if R 2652 // resolved to a function or overloaded function set, because the 2653 // expression is ill-formed if it actually works out to be a 2654 // non-static member function: 2655 // 2656 // C++ [expr.ref]p4: 2657 // Otherwise, if E1.E2 refers to a non-static member function. . . 2658 // [t]he expression can be used only as the left-hand operand of a 2659 // member function call. 2660 // 2661 // There are other safeguards against such uses, but it's important 2662 // to get this right here so that we don't end up making a 2663 // spuriously dependent expression if we're inside a dependent 2664 // instance method. 2665 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2666 bool MightBeImplicitMember; 2667 if (!IsAddressOfOperand) 2668 MightBeImplicitMember = true; 2669 else if (!SS.isEmpty()) 2670 MightBeImplicitMember = false; 2671 else if (R.isOverloadedResult()) 2672 MightBeImplicitMember = false; 2673 else if (R.isUnresolvableResult()) 2674 MightBeImplicitMember = true; 2675 else 2676 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2677 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2678 isa<MSPropertyDecl>(R.getFoundDecl()); 2679 2680 if (MightBeImplicitMember) 2681 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2682 R, TemplateArgs, S); 2683 } 2684 2685 if (TemplateArgs || TemplateKWLoc.isValid()) { 2686 2687 // In C++1y, if this is a variable template id, then check it 2688 // in BuildTemplateIdExpr(). 2689 // The single lookup result must be a variable template declaration. 2690 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2691 Id.TemplateId->Kind == TNK_Var_template) { 2692 assert(R.getAsSingle<VarTemplateDecl>() && 2693 "There should only be one declaration found."); 2694 } 2695 2696 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2697 } 2698 2699 return BuildDeclarationNameExpr(SS, R, ADL); 2700 } 2701 2702 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2703 /// declaration name, generally during template instantiation. 2704 /// There's a large number of things which don't need to be done along 2705 /// this path. 2706 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2707 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2708 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2709 DeclContext *DC = computeDeclContext(SS, false); 2710 if (!DC) 2711 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2712 NameInfo, /*TemplateArgs=*/nullptr); 2713 2714 if (RequireCompleteDeclContext(SS, DC)) 2715 return ExprError(); 2716 2717 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2718 LookupQualifiedName(R, DC); 2719 2720 if (R.isAmbiguous()) 2721 return ExprError(); 2722 2723 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2724 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2725 NameInfo, /*TemplateArgs=*/nullptr); 2726 2727 if (R.empty()) { 2728 // Don't diagnose problems with invalid record decl, the secondary no_member 2729 // diagnostic during template instantiation is likely bogus, e.g. if a class 2730 // is invalid because it's derived from an invalid base class, then missing 2731 // members were likely supposed to be inherited. 2732 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2733 if (CD->isInvalidDecl()) 2734 return ExprError(); 2735 Diag(NameInfo.getLoc(), diag::err_no_member) 2736 << NameInfo.getName() << DC << SS.getRange(); 2737 return ExprError(); 2738 } 2739 2740 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2741 // Diagnose a missing typename if this resolved unambiguously to a type in 2742 // a dependent context. If we can recover with a type, downgrade this to 2743 // a warning in Microsoft compatibility mode. 2744 unsigned DiagID = diag::err_typename_missing; 2745 if (RecoveryTSI && getLangOpts().MSVCCompat) 2746 DiagID = diag::ext_typename_missing; 2747 SourceLocation Loc = SS.getBeginLoc(); 2748 auto D = Diag(Loc, DiagID); 2749 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2750 << SourceRange(Loc, NameInfo.getEndLoc()); 2751 2752 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2753 // context. 2754 if (!RecoveryTSI) 2755 return ExprError(); 2756 2757 // Only issue the fixit if we're prepared to recover. 2758 D << FixItHint::CreateInsertion(Loc, "typename "); 2759 2760 // Recover by pretending this was an elaborated type. 2761 QualType Ty = Context.getTypeDeclType(TD); 2762 TypeLocBuilder TLB; 2763 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2764 2765 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2766 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2767 QTL.setElaboratedKeywordLoc(SourceLocation()); 2768 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2769 2770 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2771 2772 return ExprEmpty(); 2773 } 2774 2775 // Defend against this resolving to an implicit member access. We usually 2776 // won't get here if this might be a legitimate a class member (we end up in 2777 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2778 // a pointer-to-member or in an unevaluated context in C++11. 2779 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2780 return BuildPossibleImplicitMemberExpr(SS, 2781 /*TemplateKWLoc=*/SourceLocation(), 2782 R, /*TemplateArgs=*/nullptr, S); 2783 2784 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2785 } 2786 2787 /// The parser has read a name in, and Sema has detected that we're currently 2788 /// inside an ObjC method. Perform some additional checks and determine if we 2789 /// should form a reference to an ivar. 2790 /// 2791 /// Ideally, most of this would be done by lookup, but there's 2792 /// actually quite a lot of extra work involved. 2793 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2794 IdentifierInfo *II) { 2795 SourceLocation Loc = Lookup.getNameLoc(); 2796 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2797 2798 // Check for error condition which is already reported. 2799 if (!CurMethod) 2800 return DeclResult(true); 2801 2802 // There are two cases to handle here. 1) scoped lookup could have failed, 2803 // in which case we should look for an ivar. 2) scoped lookup could have 2804 // found a decl, but that decl is outside the current instance method (i.e. 2805 // a global variable). In these two cases, we do a lookup for an ivar with 2806 // this name, if the lookup sucedes, we replace it our current decl. 2807 2808 // If we're in a class method, we don't normally want to look for 2809 // ivars. But if we don't find anything else, and there's an 2810 // ivar, that's an error. 2811 bool IsClassMethod = CurMethod->isClassMethod(); 2812 2813 bool LookForIvars; 2814 if (Lookup.empty()) 2815 LookForIvars = true; 2816 else if (IsClassMethod) 2817 LookForIvars = false; 2818 else 2819 LookForIvars = (Lookup.isSingleResult() && 2820 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2821 ObjCInterfaceDecl *IFace = nullptr; 2822 if (LookForIvars) { 2823 IFace = CurMethod->getClassInterface(); 2824 ObjCInterfaceDecl *ClassDeclared; 2825 ObjCIvarDecl *IV = nullptr; 2826 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2827 // Diagnose using an ivar in a class method. 2828 if (IsClassMethod) { 2829 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2830 return DeclResult(true); 2831 } 2832 2833 // Diagnose the use of an ivar outside of the declaring class. 2834 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2835 !declaresSameEntity(ClassDeclared, IFace) && 2836 !getLangOpts().DebuggerSupport) 2837 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2838 2839 // Success. 2840 return IV; 2841 } 2842 } else if (CurMethod->isInstanceMethod()) { 2843 // We should warn if a local variable hides an ivar. 2844 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2845 ObjCInterfaceDecl *ClassDeclared; 2846 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2847 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2848 declaresSameEntity(IFace, ClassDeclared)) 2849 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2850 } 2851 } 2852 } else if (Lookup.isSingleResult() && 2853 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2854 // If accessing a stand-alone ivar in a class method, this is an error. 2855 if (const ObjCIvarDecl *IV = 2856 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2857 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2858 return DeclResult(true); 2859 } 2860 } 2861 2862 // Didn't encounter an error, didn't find an ivar. 2863 return DeclResult(false); 2864 } 2865 2866 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2867 ObjCIvarDecl *IV) { 2868 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2869 assert(CurMethod && CurMethod->isInstanceMethod() && 2870 "should not reference ivar from this context"); 2871 2872 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2873 assert(IFace && "should not reference ivar from this context"); 2874 2875 // If we're referencing an invalid decl, just return this as a silent 2876 // error node. The error diagnostic was already emitted on the decl. 2877 if (IV->isInvalidDecl()) 2878 return ExprError(); 2879 2880 // Check if referencing a field with __attribute__((deprecated)). 2881 if (DiagnoseUseOfDecl(IV, Loc)) 2882 return ExprError(); 2883 2884 // FIXME: This should use a new expr for a direct reference, don't 2885 // turn this into Self->ivar, just return a BareIVarExpr or something. 2886 IdentifierInfo &II = Context.Idents.get("self"); 2887 UnqualifiedId SelfName; 2888 SelfName.setImplicitSelfParam(&II); 2889 CXXScopeSpec SelfScopeSpec; 2890 SourceLocation TemplateKWLoc; 2891 ExprResult SelfExpr = 2892 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2893 /*HasTrailingLParen=*/false, 2894 /*IsAddressOfOperand=*/false); 2895 if (SelfExpr.isInvalid()) 2896 return ExprError(); 2897 2898 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2899 if (SelfExpr.isInvalid()) 2900 return ExprError(); 2901 2902 MarkAnyDeclReferenced(Loc, IV, true); 2903 2904 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2905 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2906 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2907 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2908 2909 ObjCIvarRefExpr *Result = new (Context) 2910 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2911 IV->getLocation(), SelfExpr.get(), true, true); 2912 2913 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2914 if (!isUnevaluatedContext() && 2915 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2916 getCurFunction()->recordUseOfWeak(Result); 2917 } 2918 if (getLangOpts().ObjCAutoRefCount) 2919 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2920 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2921 2922 return Result; 2923 } 2924 2925 /// The parser has read a name in, and Sema has detected that we're currently 2926 /// inside an ObjC method. Perform some additional checks and determine if we 2927 /// should form a reference to an ivar. If so, build an expression referencing 2928 /// that ivar. 2929 ExprResult 2930 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2931 IdentifierInfo *II, bool AllowBuiltinCreation) { 2932 // FIXME: Integrate this lookup step into LookupParsedName. 2933 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2934 if (Ivar.isInvalid()) 2935 return ExprError(); 2936 if (Ivar.isUsable()) 2937 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2938 cast<ObjCIvarDecl>(Ivar.get())); 2939 2940 if (Lookup.empty() && II && AllowBuiltinCreation) 2941 LookupBuiltin(Lookup); 2942 2943 // Sentinel value saying that we didn't do anything special. 2944 return ExprResult(false); 2945 } 2946 2947 /// Cast a base object to a member's actual type. 2948 /// 2949 /// There are two relevant checks: 2950 /// 2951 /// C++ [class.access.base]p7: 2952 /// 2953 /// If a class member access operator [...] is used to access a non-static 2954 /// data member or non-static member function, the reference is ill-formed if 2955 /// the left operand [...] cannot be implicitly converted to a pointer to the 2956 /// naming class of the right operand. 2957 /// 2958 /// C++ [expr.ref]p7: 2959 /// 2960 /// If E2 is a non-static data member or a non-static member function, the 2961 /// program is ill-formed if the class of which E2 is directly a member is an 2962 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2963 /// 2964 /// Note that the latter check does not consider access; the access of the 2965 /// "real" base class is checked as appropriate when checking the access of the 2966 /// member name. 2967 ExprResult 2968 Sema::PerformObjectMemberConversion(Expr *From, 2969 NestedNameSpecifier *Qualifier, 2970 NamedDecl *FoundDecl, 2971 NamedDecl *Member) { 2972 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2973 if (!RD) 2974 return From; 2975 2976 QualType DestRecordType; 2977 QualType DestType; 2978 QualType FromRecordType; 2979 QualType FromType = From->getType(); 2980 bool PointerConversions = false; 2981 if (isa<FieldDecl>(Member)) { 2982 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2983 auto FromPtrType = FromType->getAs<PointerType>(); 2984 DestRecordType = Context.getAddrSpaceQualType( 2985 DestRecordType, FromPtrType 2986 ? FromType->getPointeeType().getAddressSpace() 2987 : FromType.getAddressSpace()); 2988 2989 if (FromPtrType) { 2990 DestType = Context.getPointerType(DestRecordType); 2991 FromRecordType = FromPtrType->getPointeeType(); 2992 PointerConversions = true; 2993 } else { 2994 DestType = DestRecordType; 2995 FromRecordType = FromType; 2996 } 2997 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2998 if (Method->isStatic()) 2999 return From; 3000 3001 DestType = Method->getThisType(); 3002 DestRecordType = DestType->getPointeeType(); 3003 3004 if (FromType->getAs<PointerType>()) { 3005 FromRecordType = FromType->getPointeeType(); 3006 PointerConversions = true; 3007 } else { 3008 FromRecordType = FromType; 3009 DestType = DestRecordType; 3010 } 3011 3012 LangAS FromAS = FromRecordType.getAddressSpace(); 3013 LangAS DestAS = DestRecordType.getAddressSpace(); 3014 if (FromAS != DestAS) { 3015 QualType FromRecordTypeWithoutAS = 3016 Context.removeAddrSpaceQualType(FromRecordType); 3017 QualType FromTypeWithDestAS = 3018 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 3019 if (PointerConversions) 3020 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 3021 From = ImpCastExprToType(From, FromTypeWithDestAS, 3022 CK_AddressSpaceConversion, From->getValueKind()) 3023 .get(); 3024 } 3025 } else { 3026 // No conversion necessary. 3027 return From; 3028 } 3029 3030 if (DestType->isDependentType() || FromType->isDependentType()) 3031 return From; 3032 3033 // If the unqualified types are the same, no conversion is necessary. 3034 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3035 return From; 3036 3037 SourceRange FromRange = From->getSourceRange(); 3038 SourceLocation FromLoc = FromRange.getBegin(); 3039 3040 ExprValueKind VK = From->getValueKind(); 3041 3042 // C++ [class.member.lookup]p8: 3043 // [...] Ambiguities can often be resolved by qualifying a name with its 3044 // class name. 3045 // 3046 // If the member was a qualified name and the qualified referred to a 3047 // specific base subobject type, we'll cast to that intermediate type 3048 // first and then to the object in which the member is declared. That allows 3049 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3050 // 3051 // class Base { public: int x; }; 3052 // class Derived1 : public Base { }; 3053 // class Derived2 : public Base { }; 3054 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3055 // 3056 // void VeryDerived::f() { 3057 // x = 17; // error: ambiguous base subobjects 3058 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3059 // } 3060 if (Qualifier && Qualifier->getAsType()) { 3061 QualType QType = QualType(Qualifier->getAsType(), 0); 3062 assert(QType->isRecordType() && "lookup done with non-record type"); 3063 3064 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0); 3065 3066 // In C++98, the qualifier type doesn't actually have to be a base 3067 // type of the object type, in which case we just ignore it. 3068 // Otherwise build the appropriate casts. 3069 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3070 CXXCastPath BasePath; 3071 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3072 FromLoc, FromRange, &BasePath)) 3073 return ExprError(); 3074 3075 if (PointerConversions) 3076 QType = Context.getPointerType(QType); 3077 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3078 VK, &BasePath).get(); 3079 3080 FromType = QType; 3081 FromRecordType = QRecordType; 3082 3083 // If the qualifier type was the same as the destination type, 3084 // we're done. 3085 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3086 return From; 3087 } 3088 } 3089 3090 CXXCastPath BasePath; 3091 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3092 FromLoc, FromRange, &BasePath, 3093 /*IgnoreAccess=*/true)) 3094 return ExprError(); 3095 3096 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3097 VK, &BasePath); 3098 } 3099 3100 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3101 const LookupResult &R, 3102 bool HasTrailingLParen) { 3103 // Only when used directly as the postfix-expression of a call. 3104 if (!HasTrailingLParen) 3105 return false; 3106 3107 // Never if a scope specifier was provided. 3108 if (SS.isSet()) 3109 return false; 3110 3111 // Only in C++ or ObjC++. 3112 if (!getLangOpts().CPlusPlus) 3113 return false; 3114 3115 // Turn off ADL when we find certain kinds of declarations during 3116 // normal lookup: 3117 for (NamedDecl *D : R) { 3118 // C++0x [basic.lookup.argdep]p3: 3119 // -- a declaration of a class member 3120 // Since using decls preserve this property, we check this on the 3121 // original decl. 3122 if (D->isCXXClassMember()) 3123 return false; 3124 3125 // C++0x [basic.lookup.argdep]p3: 3126 // -- a block-scope function declaration that is not a 3127 // using-declaration 3128 // NOTE: we also trigger this for function templates (in fact, we 3129 // don't check the decl type at all, since all other decl types 3130 // turn off ADL anyway). 3131 if (isa<UsingShadowDecl>(D)) 3132 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3133 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3134 return false; 3135 3136 // C++0x [basic.lookup.argdep]p3: 3137 // -- a declaration that is neither a function or a function 3138 // template 3139 // And also for builtin functions. 3140 if (isa<FunctionDecl>(D)) { 3141 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3142 3143 // But also builtin functions. 3144 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3145 return false; 3146 } else if (!isa<FunctionTemplateDecl>(D)) 3147 return false; 3148 } 3149 3150 return true; 3151 } 3152 3153 3154 /// Diagnoses obvious problems with the use of the given declaration 3155 /// as an expression. This is only actually called for lookups that 3156 /// were not overloaded, and it doesn't promise that the declaration 3157 /// will in fact be used. 3158 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3159 if (D->isInvalidDecl()) 3160 return true; 3161 3162 if (isa<TypedefNameDecl>(D)) { 3163 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3164 return true; 3165 } 3166 3167 if (isa<ObjCInterfaceDecl>(D)) { 3168 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3169 return true; 3170 } 3171 3172 if (isa<NamespaceDecl>(D)) { 3173 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3174 return true; 3175 } 3176 3177 return false; 3178 } 3179 3180 // Certain multiversion types should be treated as overloaded even when there is 3181 // only one result. 3182 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3183 assert(R.isSingleResult() && "Expected only a single result"); 3184 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3185 return FD && 3186 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3187 } 3188 3189 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3190 LookupResult &R, bool NeedsADL, 3191 bool AcceptInvalidDecl) { 3192 // If this is a single, fully-resolved result and we don't need ADL, 3193 // just build an ordinary singleton decl ref. 3194 if (!NeedsADL && R.isSingleResult() && 3195 !R.getAsSingle<FunctionTemplateDecl>() && 3196 !ShouldLookupResultBeMultiVersionOverload(R)) 3197 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3198 R.getRepresentativeDecl(), nullptr, 3199 AcceptInvalidDecl); 3200 3201 // We only need to check the declaration if there's exactly one 3202 // result, because in the overloaded case the results can only be 3203 // functions and function templates. 3204 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3205 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3206 return ExprError(); 3207 3208 // Otherwise, just build an unresolved lookup expression. Suppress 3209 // any lookup-related diagnostics; we'll hash these out later, when 3210 // we've picked a target. 3211 R.suppressDiagnostics(); 3212 3213 UnresolvedLookupExpr *ULE 3214 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3215 SS.getWithLocInContext(Context), 3216 R.getLookupNameInfo(), 3217 NeedsADL, R.isOverloadedResult(), 3218 R.begin(), R.end()); 3219 3220 return ULE; 3221 } 3222 3223 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3224 ValueDecl *var); 3225 3226 /// Complete semantic analysis for a reference to the given declaration. 3227 ExprResult Sema::BuildDeclarationNameExpr( 3228 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3229 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3230 bool AcceptInvalidDecl) { 3231 assert(D && "Cannot refer to a NULL declaration"); 3232 assert(!isa<FunctionTemplateDecl>(D) && 3233 "Cannot refer unambiguously to a function template"); 3234 3235 SourceLocation Loc = NameInfo.getLoc(); 3236 if (CheckDeclInExpr(*this, Loc, D)) { 3237 // Recovery from invalid cases (e.g. D is an invalid Decl). 3238 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up 3239 // diagnostics, as invalid decls use int as a fallback type. 3240 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {}); 3241 } 3242 3243 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3244 // Specifically diagnose references to class templates that are missing 3245 // a template argument list. 3246 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3247 return ExprError(); 3248 } 3249 3250 // Make sure that we're referring to a value. 3251 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { 3252 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange(); 3253 Diag(D->getLocation(), diag::note_declared_at); 3254 return ExprError(); 3255 } 3256 3257 // Check whether this declaration can be used. Note that we suppress 3258 // this check when we're going to perform argument-dependent lookup 3259 // on this function name, because this might not be the function 3260 // that overload resolution actually selects. 3261 if (DiagnoseUseOfDecl(D, Loc)) 3262 return ExprError(); 3263 3264 auto *VD = cast<ValueDecl>(D); 3265 3266 // Only create DeclRefExpr's for valid Decl's. 3267 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3268 return ExprError(); 3269 3270 // Handle members of anonymous structs and unions. If we got here, 3271 // and the reference is to a class member indirect field, then this 3272 // must be the subject of a pointer-to-member expression. 3273 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3274 if (!indirectField->isCXXClassMember()) 3275 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3276 indirectField); 3277 3278 QualType type = VD->getType(); 3279 if (type.isNull()) 3280 return ExprError(); 3281 ExprValueKind valueKind = VK_PRValue; 3282 3283 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3284 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3285 // is expanded by some outer '...' in the context of the use. 3286 type = type.getNonPackExpansionType(); 3287 3288 switch (D->getKind()) { 3289 // Ignore all the non-ValueDecl kinds. 3290 #define ABSTRACT_DECL(kind) 3291 #define VALUE(type, base) 3292 #define DECL(type, base) case Decl::type: 3293 #include "clang/AST/DeclNodes.inc" 3294 llvm_unreachable("invalid value decl kind"); 3295 3296 // These shouldn't make it here. 3297 case Decl::ObjCAtDefsField: 3298 llvm_unreachable("forming non-member reference to ivar?"); 3299 3300 // Enum constants are always r-values and never references. 3301 // Unresolved using declarations are dependent. 3302 case Decl::EnumConstant: 3303 case Decl::UnresolvedUsingValue: 3304 case Decl::OMPDeclareReduction: 3305 case Decl::OMPDeclareMapper: 3306 valueKind = VK_PRValue; 3307 break; 3308 3309 // Fields and indirect fields that got here must be for 3310 // pointer-to-member expressions; we just call them l-values for 3311 // internal consistency, because this subexpression doesn't really 3312 // exist in the high-level semantics. 3313 case Decl::Field: 3314 case Decl::IndirectField: 3315 case Decl::ObjCIvar: 3316 assert(getLangOpts().CPlusPlus && "building reference to field in C?"); 3317 3318 // These can't have reference type in well-formed programs, but 3319 // for internal consistency we do this anyway. 3320 type = type.getNonReferenceType(); 3321 valueKind = VK_LValue; 3322 break; 3323 3324 // Non-type template parameters are either l-values or r-values 3325 // depending on the type. 3326 case Decl::NonTypeTemplateParm: { 3327 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3328 type = reftype->getPointeeType(); 3329 valueKind = VK_LValue; // even if the parameter is an r-value reference 3330 break; 3331 } 3332 3333 // [expr.prim.id.unqual]p2: 3334 // If the entity is a template parameter object for a template 3335 // parameter of type T, the type of the expression is const T. 3336 // [...] The expression is an lvalue if the entity is a [...] template 3337 // parameter object. 3338 if (type->isRecordType()) { 3339 type = type.getUnqualifiedType().withConst(); 3340 valueKind = VK_LValue; 3341 break; 3342 } 3343 3344 // For non-references, we need to strip qualifiers just in case 3345 // the template parameter was declared as 'const int' or whatever. 3346 valueKind = VK_PRValue; 3347 type = type.getUnqualifiedType(); 3348 break; 3349 } 3350 3351 case Decl::Var: 3352 case Decl::VarTemplateSpecialization: 3353 case Decl::VarTemplatePartialSpecialization: 3354 case Decl::Decomposition: 3355 case Decl::OMPCapturedExpr: 3356 // In C, "extern void blah;" is valid and is an r-value. 3357 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && 3358 type->isVoidType()) { 3359 valueKind = VK_PRValue; 3360 break; 3361 } 3362 LLVM_FALLTHROUGH; 3363 3364 case Decl::ImplicitParam: 3365 case Decl::ParmVar: { 3366 // These are always l-values. 3367 valueKind = VK_LValue; 3368 type = type.getNonReferenceType(); 3369 3370 // FIXME: Does the addition of const really only apply in 3371 // potentially-evaluated contexts? Since the variable isn't actually 3372 // captured in an unevaluated context, it seems that the answer is no. 3373 if (!isUnevaluatedContext()) { 3374 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3375 if (!CapturedType.isNull()) 3376 type = CapturedType; 3377 } 3378 3379 break; 3380 } 3381 3382 case Decl::Binding: { 3383 // These are always lvalues. 3384 valueKind = VK_LValue; 3385 type = type.getNonReferenceType(); 3386 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3387 // decides how that's supposed to work. 3388 auto *BD = cast<BindingDecl>(VD); 3389 if (BD->getDeclContext() != CurContext) { 3390 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3391 if (DD && DD->hasLocalStorage()) 3392 diagnoseUncapturableValueReference(*this, Loc, BD); 3393 } 3394 break; 3395 } 3396 3397 case Decl::Function: { 3398 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3399 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) { 3400 type = Context.BuiltinFnTy; 3401 valueKind = VK_PRValue; 3402 break; 3403 } 3404 } 3405 3406 const FunctionType *fty = type->castAs<FunctionType>(); 3407 3408 // If we're referring to a function with an __unknown_anytype 3409 // result type, make the entire expression __unknown_anytype. 3410 if (fty->getReturnType() == Context.UnknownAnyTy) { 3411 type = Context.UnknownAnyTy; 3412 valueKind = VK_PRValue; 3413 break; 3414 } 3415 3416 // Functions are l-values in C++. 3417 if (getLangOpts().CPlusPlus) { 3418 valueKind = VK_LValue; 3419 break; 3420 } 3421 3422 // C99 DR 316 says that, if a function type comes from a 3423 // function definition (without a prototype), that type is only 3424 // used for checking compatibility. Therefore, when referencing 3425 // the function, we pretend that we don't have the full function 3426 // type. 3427 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty)) 3428 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3429 fty->getExtInfo()); 3430 3431 // Functions are r-values in C. 3432 valueKind = VK_PRValue; 3433 break; 3434 } 3435 3436 case Decl::CXXDeductionGuide: 3437 llvm_unreachable("building reference to deduction guide"); 3438 3439 case Decl::MSProperty: 3440 case Decl::MSGuid: 3441 case Decl::TemplateParamObject: 3442 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3443 // capture in OpenMP, or duplicated between host and device? 3444 valueKind = VK_LValue; 3445 break; 3446 3447 case Decl::UnnamedGlobalConstant: 3448 valueKind = VK_LValue; 3449 break; 3450 3451 case Decl::CXXMethod: 3452 // If we're referring to a method with an __unknown_anytype 3453 // result type, make the entire expression __unknown_anytype. 3454 // This should only be possible with a type written directly. 3455 if (const FunctionProtoType *proto = 3456 dyn_cast<FunctionProtoType>(VD->getType())) 3457 if (proto->getReturnType() == Context.UnknownAnyTy) { 3458 type = Context.UnknownAnyTy; 3459 valueKind = VK_PRValue; 3460 break; 3461 } 3462 3463 // C++ methods are l-values if static, r-values if non-static. 3464 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3465 valueKind = VK_LValue; 3466 break; 3467 } 3468 LLVM_FALLTHROUGH; 3469 3470 case Decl::CXXConversion: 3471 case Decl::CXXDestructor: 3472 case Decl::CXXConstructor: 3473 valueKind = VK_PRValue; 3474 break; 3475 } 3476 3477 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3478 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3479 TemplateArgs); 3480 } 3481 3482 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3483 SmallString<32> &Target) { 3484 Target.resize(CharByteWidth * (Source.size() + 1)); 3485 char *ResultPtr = &Target[0]; 3486 const llvm::UTF8 *ErrorPtr; 3487 bool success = 3488 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3489 (void)success; 3490 assert(success); 3491 Target.resize(ResultPtr - &Target[0]); 3492 } 3493 3494 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3495 PredefinedExpr::IdentKind IK) { 3496 // Pick the current block, lambda, captured statement or function. 3497 Decl *currentDecl = nullptr; 3498 if (const BlockScopeInfo *BSI = getCurBlock()) 3499 currentDecl = BSI->TheDecl; 3500 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3501 currentDecl = LSI->CallOperator; 3502 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3503 currentDecl = CSI->TheCapturedDecl; 3504 else 3505 currentDecl = getCurFunctionOrMethodDecl(); 3506 3507 if (!currentDecl) { 3508 Diag(Loc, diag::ext_predef_outside_function); 3509 currentDecl = Context.getTranslationUnitDecl(); 3510 } 3511 3512 QualType ResTy; 3513 StringLiteral *SL = nullptr; 3514 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3515 ResTy = Context.DependentTy; 3516 else { 3517 // Pre-defined identifiers are of type char[x], where x is the length of 3518 // the string. 3519 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3520 unsigned Length = Str.length(); 3521 3522 llvm::APInt LengthI(32, Length + 1); 3523 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3524 ResTy = 3525 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3526 SmallString<32> RawChars; 3527 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3528 Str, RawChars); 3529 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3530 ArrayType::Normal, 3531 /*IndexTypeQuals*/ 0); 3532 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3533 /*Pascal*/ false, ResTy, Loc); 3534 } else { 3535 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3536 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3537 ArrayType::Normal, 3538 /*IndexTypeQuals*/ 0); 3539 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3540 /*Pascal*/ false, ResTy, Loc); 3541 } 3542 } 3543 3544 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3545 } 3546 3547 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3548 SourceLocation LParen, 3549 SourceLocation RParen, 3550 TypeSourceInfo *TSI) { 3551 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); 3552 } 3553 3554 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3555 SourceLocation LParen, 3556 SourceLocation RParen, 3557 ParsedType ParsedTy) { 3558 TypeSourceInfo *TSI = nullptr; 3559 QualType Ty = GetTypeFromParser(ParsedTy, &TSI); 3560 3561 if (Ty.isNull()) 3562 return ExprError(); 3563 if (!TSI) 3564 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); 3565 3566 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); 3567 } 3568 3569 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3570 PredefinedExpr::IdentKind IK; 3571 3572 switch (Kind) { 3573 default: llvm_unreachable("Unknown simple primary expr!"); 3574 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3575 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3576 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3577 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3578 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3579 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3580 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3581 } 3582 3583 return BuildPredefinedExpr(Loc, IK); 3584 } 3585 3586 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3587 SmallString<16> CharBuffer; 3588 bool Invalid = false; 3589 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3590 if (Invalid) 3591 return ExprError(); 3592 3593 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3594 PP, Tok.getKind()); 3595 if (Literal.hadError()) 3596 return ExprError(); 3597 3598 QualType Ty; 3599 if (Literal.isWide()) 3600 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3601 else if (Literal.isUTF8() && getLangOpts().C2x) 3602 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C2x 3603 else if (Literal.isUTF8() && getLangOpts().Char8) 3604 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3605 else if (Literal.isUTF16()) 3606 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3607 else if (Literal.isUTF32()) 3608 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3609 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3610 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3611 else 3612 Ty = Context.CharTy; // 'x' -> char in C++; 3613 // u8'x' -> char in C11-C17 and in C++ without char8_t. 3614 3615 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3616 if (Literal.isWide()) 3617 Kind = CharacterLiteral::Wide; 3618 else if (Literal.isUTF16()) 3619 Kind = CharacterLiteral::UTF16; 3620 else if (Literal.isUTF32()) 3621 Kind = CharacterLiteral::UTF32; 3622 else if (Literal.isUTF8()) 3623 Kind = CharacterLiteral::UTF8; 3624 3625 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3626 Tok.getLocation()); 3627 3628 if (Literal.getUDSuffix().empty()) 3629 return Lit; 3630 3631 // We're building a user-defined literal. 3632 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3633 SourceLocation UDSuffixLoc = 3634 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3635 3636 // Make sure we're allowed user-defined literals here. 3637 if (!UDLScope) 3638 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3639 3640 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3641 // operator "" X (ch) 3642 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3643 Lit, Tok.getLocation()); 3644 } 3645 3646 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3647 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3648 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3649 Context.IntTy, Loc); 3650 } 3651 3652 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3653 QualType Ty, SourceLocation Loc) { 3654 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3655 3656 using llvm::APFloat; 3657 APFloat Val(Format); 3658 3659 APFloat::opStatus result = Literal.GetFloatValue(Val); 3660 3661 // Overflow is always an error, but underflow is only an error if 3662 // we underflowed to zero (APFloat reports denormals as underflow). 3663 if ((result & APFloat::opOverflow) || 3664 ((result & APFloat::opUnderflow) && Val.isZero())) { 3665 unsigned diagnostic; 3666 SmallString<20> buffer; 3667 if (result & APFloat::opOverflow) { 3668 diagnostic = diag::warn_float_overflow; 3669 APFloat::getLargest(Format).toString(buffer); 3670 } else { 3671 diagnostic = diag::warn_float_underflow; 3672 APFloat::getSmallest(Format).toString(buffer); 3673 } 3674 3675 S.Diag(Loc, diagnostic) 3676 << Ty 3677 << StringRef(buffer.data(), buffer.size()); 3678 } 3679 3680 bool isExact = (result == APFloat::opOK); 3681 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3682 } 3683 3684 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3685 assert(E && "Invalid expression"); 3686 3687 if (E->isValueDependent()) 3688 return false; 3689 3690 QualType QT = E->getType(); 3691 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3692 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3693 return true; 3694 } 3695 3696 llvm::APSInt ValueAPS; 3697 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3698 3699 if (R.isInvalid()) 3700 return true; 3701 3702 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3703 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3704 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3705 << toString(ValueAPS, 10) << ValueIsPositive; 3706 return true; 3707 } 3708 3709 return false; 3710 } 3711 3712 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3713 // Fast path for a single digit (which is quite common). A single digit 3714 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3715 if (Tok.getLength() == 1) { 3716 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3717 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3718 } 3719 3720 SmallString<128> SpellingBuffer; 3721 // NumericLiteralParser wants to overread by one character. Add padding to 3722 // the buffer in case the token is copied to the buffer. If getSpelling() 3723 // returns a StringRef to the memory buffer, it should have a null char at 3724 // the EOF, so it is also safe. 3725 SpellingBuffer.resize(Tok.getLength() + 1); 3726 3727 // Get the spelling of the token, which eliminates trigraphs, etc. 3728 bool Invalid = false; 3729 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3730 if (Invalid) 3731 return ExprError(); 3732 3733 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3734 PP.getSourceManager(), PP.getLangOpts(), 3735 PP.getTargetInfo(), PP.getDiagnostics()); 3736 if (Literal.hadError) 3737 return ExprError(); 3738 3739 if (Literal.hasUDSuffix()) { 3740 // We're building a user-defined literal. 3741 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3742 SourceLocation UDSuffixLoc = 3743 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3744 3745 // Make sure we're allowed user-defined literals here. 3746 if (!UDLScope) 3747 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3748 3749 QualType CookedTy; 3750 if (Literal.isFloatingLiteral()) { 3751 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3752 // long double, the literal is treated as a call of the form 3753 // operator "" X (f L) 3754 CookedTy = Context.LongDoubleTy; 3755 } else { 3756 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3757 // unsigned long long, the literal is treated as a call of the form 3758 // operator "" X (n ULL) 3759 CookedTy = Context.UnsignedLongLongTy; 3760 } 3761 3762 DeclarationName OpName = 3763 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3764 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3765 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3766 3767 SourceLocation TokLoc = Tok.getLocation(); 3768 3769 // Perform literal operator lookup to determine if we're building a raw 3770 // literal or a cooked one. 3771 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3772 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3773 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3774 /*AllowStringTemplatePack*/ false, 3775 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3776 case LOLR_ErrorNoDiagnostic: 3777 // Lookup failure for imaginary constants isn't fatal, there's still the 3778 // GNU extension producing _Complex types. 3779 break; 3780 case LOLR_Error: 3781 return ExprError(); 3782 case LOLR_Cooked: { 3783 Expr *Lit; 3784 if (Literal.isFloatingLiteral()) { 3785 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3786 } else { 3787 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3788 if (Literal.GetIntegerValue(ResultVal)) 3789 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3790 << /* Unsigned */ 1; 3791 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3792 Tok.getLocation()); 3793 } 3794 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3795 } 3796 3797 case LOLR_Raw: { 3798 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3799 // literal is treated as a call of the form 3800 // operator "" X ("n") 3801 unsigned Length = Literal.getUDSuffixOffset(); 3802 QualType StrTy = Context.getConstantArrayType( 3803 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3804 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3805 Expr *Lit = StringLiteral::Create( 3806 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3807 /*Pascal*/false, StrTy, &TokLoc, 1); 3808 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3809 } 3810 3811 case LOLR_Template: { 3812 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3813 // template), L is treated as a call fo the form 3814 // operator "" X <'c1', 'c2', ... 'ck'>() 3815 // where n is the source character sequence c1 c2 ... ck. 3816 TemplateArgumentListInfo ExplicitArgs; 3817 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3818 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3819 llvm::APSInt Value(CharBits, CharIsUnsigned); 3820 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3821 Value = TokSpelling[I]; 3822 TemplateArgument Arg(Context, Value, Context.CharTy); 3823 TemplateArgumentLocInfo ArgInfo; 3824 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3825 } 3826 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3827 &ExplicitArgs); 3828 } 3829 case LOLR_StringTemplatePack: 3830 llvm_unreachable("unexpected literal operator lookup result"); 3831 } 3832 } 3833 3834 Expr *Res; 3835 3836 if (Literal.isFixedPointLiteral()) { 3837 QualType Ty; 3838 3839 if (Literal.isAccum) { 3840 if (Literal.isHalf) { 3841 Ty = Context.ShortAccumTy; 3842 } else if (Literal.isLong) { 3843 Ty = Context.LongAccumTy; 3844 } else { 3845 Ty = Context.AccumTy; 3846 } 3847 } else if (Literal.isFract) { 3848 if (Literal.isHalf) { 3849 Ty = Context.ShortFractTy; 3850 } else if (Literal.isLong) { 3851 Ty = Context.LongFractTy; 3852 } else { 3853 Ty = Context.FractTy; 3854 } 3855 } 3856 3857 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3858 3859 bool isSigned = !Literal.isUnsigned; 3860 unsigned scale = Context.getFixedPointScale(Ty); 3861 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3862 3863 llvm::APInt Val(bit_width, 0, isSigned); 3864 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3865 bool ValIsZero = Val.isZero() && !Overflowed; 3866 3867 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3868 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3869 // Clause 6.4.4 - The value of a constant shall be in the range of 3870 // representable values for its type, with exception for constants of a 3871 // fract type with a value of exactly 1; such a constant shall denote 3872 // the maximal value for the type. 3873 --Val; 3874 else if (Val.ugt(MaxVal) || Overflowed) 3875 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3876 3877 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3878 Tok.getLocation(), scale); 3879 } else if (Literal.isFloatingLiteral()) { 3880 QualType Ty; 3881 if (Literal.isHalf){ 3882 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3883 Ty = Context.HalfTy; 3884 else { 3885 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3886 return ExprError(); 3887 } 3888 } else if (Literal.isFloat) 3889 Ty = Context.FloatTy; 3890 else if (Literal.isLong) 3891 Ty = Context.LongDoubleTy; 3892 else if (Literal.isFloat16) 3893 Ty = Context.Float16Ty; 3894 else if (Literal.isFloat128) 3895 Ty = Context.Float128Ty; 3896 else 3897 Ty = Context.DoubleTy; 3898 3899 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3900 3901 if (Ty == Context.DoubleTy) { 3902 if (getLangOpts().SinglePrecisionConstants) { 3903 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3904 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3905 } 3906 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3907 "cl_khr_fp64", getLangOpts())) { 3908 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3909 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) 3910 << (getLangOpts().getOpenCLCompatibleVersion() >= 300); 3911 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3912 } 3913 } 3914 } else if (!Literal.isIntegerLiteral()) { 3915 return ExprError(); 3916 } else { 3917 QualType Ty; 3918 3919 // 'long long' is a C99 or C++11 feature. 3920 if (!getLangOpts().C99 && Literal.isLongLong) { 3921 if (getLangOpts().CPlusPlus) 3922 Diag(Tok.getLocation(), 3923 getLangOpts().CPlusPlus11 ? 3924 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3925 else 3926 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3927 } 3928 3929 // 'z/uz' literals are a C++2b feature. 3930 if (Literal.isSizeT) 3931 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3932 ? getLangOpts().CPlusPlus2b 3933 ? diag::warn_cxx20_compat_size_t_suffix 3934 : diag::ext_cxx2b_size_t_suffix 3935 : diag::err_cxx2b_size_t_suffix); 3936 3937 // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++, 3938 // but we do not currently support the suffix in C++ mode because it's not 3939 // entirely clear whether WG21 will prefer this suffix to return a library 3940 // type such as std::bit_int instead of returning a _BitInt. 3941 if (Literal.isBitInt && !getLangOpts().CPlusPlus) 3942 PP.Diag(Tok.getLocation(), getLangOpts().C2x 3943 ? diag::warn_c2x_compat_bitint_suffix 3944 : diag::ext_c2x_bitint_suffix); 3945 3946 // Get the value in the widest-possible width. What is "widest" depends on 3947 // whether the literal is a bit-precise integer or not. For a bit-precise 3948 // integer type, try to scan the source to determine how many bits are 3949 // needed to represent the value. This may seem a bit expensive, but trying 3950 // to get the integer value from an overly-wide APInt is *extremely* 3951 // expensive, so the naive approach of assuming 3952 // llvm::IntegerType::MAX_INT_BITS is a big performance hit. 3953 unsigned BitsNeeded = 3954 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded( 3955 Literal.getLiteralDigits(), Literal.getRadix()) 3956 : Context.getTargetInfo().getIntMaxTWidth(); 3957 llvm::APInt ResultVal(BitsNeeded, 0); 3958 3959 if (Literal.GetIntegerValue(ResultVal)) { 3960 // If this value didn't fit into uintmax_t, error and force to ull. 3961 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3962 << /* Unsigned */ 1; 3963 Ty = Context.UnsignedLongLongTy; 3964 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3965 "long long is not intmax_t?"); 3966 } else { 3967 // If this value fits into a ULL, try to figure out what else it fits into 3968 // according to the rules of C99 6.4.4.1p5. 3969 3970 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3971 // be an unsigned int. 3972 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3973 3974 // Check from smallest to largest, picking the smallest type we can. 3975 unsigned Width = 0; 3976 3977 // Microsoft specific integer suffixes are explicitly sized. 3978 if (Literal.MicrosoftInteger) { 3979 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3980 Width = 8; 3981 Ty = Context.CharTy; 3982 } else { 3983 Width = Literal.MicrosoftInteger; 3984 Ty = Context.getIntTypeForBitwidth(Width, 3985 /*Signed=*/!Literal.isUnsigned); 3986 } 3987 } 3988 3989 // Bit-precise integer literals are automagically-sized based on the 3990 // width required by the literal. 3991 if (Literal.isBitInt) { 3992 // The signed version has one more bit for the sign value. There are no 3993 // zero-width bit-precise integers, even if the literal value is 0. 3994 Width = std::max(ResultVal.getActiveBits(), 1u) + 3995 (Literal.isUnsigned ? 0u : 1u); 3996 3997 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH, 3998 // and reset the type to the largest supported width. 3999 unsigned int MaxBitIntWidth = 4000 Context.getTargetInfo().getMaxBitIntWidth(); 4001 if (Width > MaxBitIntWidth) { 4002 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 4003 << Literal.isUnsigned; 4004 Width = MaxBitIntWidth; 4005 } 4006 4007 // Reset the result value to the smaller APInt and select the correct 4008 // type to be used. Note, we zext even for signed values because the 4009 // literal itself is always an unsigned value (a preceeding - is a 4010 // unary operator, not part of the literal). 4011 ResultVal = ResultVal.zextOrTrunc(Width); 4012 Ty = Context.getBitIntType(Literal.isUnsigned, Width); 4013 } 4014 4015 // Check C++2b size_t literals. 4016 if (Literal.isSizeT) { 4017 assert(!Literal.MicrosoftInteger && 4018 "size_t literals can't be Microsoft literals"); 4019 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 4020 Context.getTargetInfo().getSizeType()); 4021 4022 // Does it fit in size_t? 4023 if (ResultVal.isIntN(SizeTSize)) { 4024 // Does it fit in ssize_t? 4025 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 4026 Ty = Context.getSignedSizeType(); 4027 else if (AllowUnsigned) 4028 Ty = Context.getSizeType(); 4029 Width = SizeTSize; 4030 } 4031 } 4032 4033 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 4034 !Literal.isSizeT) { 4035 // Are int/unsigned possibilities? 4036 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 4037 4038 // Does it fit in a unsigned int? 4039 if (ResultVal.isIntN(IntSize)) { 4040 // Does it fit in a signed int? 4041 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 4042 Ty = Context.IntTy; 4043 else if (AllowUnsigned) 4044 Ty = Context.UnsignedIntTy; 4045 Width = IntSize; 4046 } 4047 } 4048 4049 // Are long/unsigned long possibilities? 4050 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 4051 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 4052 4053 // Does it fit in a unsigned long? 4054 if (ResultVal.isIntN(LongSize)) { 4055 // Does it fit in a signed long? 4056 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 4057 Ty = Context.LongTy; 4058 else if (AllowUnsigned) 4059 Ty = Context.UnsignedLongTy; 4060 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 4061 // is compatible. 4062 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 4063 const unsigned LongLongSize = 4064 Context.getTargetInfo().getLongLongWidth(); 4065 Diag(Tok.getLocation(), 4066 getLangOpts().CPlusPlus 4067 ? Literal.isLong 4068 ? diag::warn_old_implicitly_unsigned_long_cxx 4069 : /*C++98 UB*/ diag:: 4070 ext_old_implicitly_unsigned_long_cxx 4071 : diag::warn_old_implicitly_unsigned_long) 4072 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 4073 : /*will be ill-formed*/ 1); 4074 Ty = Context.UnsignedLongTy; 4075 } 4076 Width = LongSize; 4077 } 4078 } 4079 4080 // Check long long if needed. 4081 if (Ty.isNull() && !Literal.isSizeT) { 4082 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 4083 4084 // Does it fit in a unsigned long long? 4085 if (ResultVal.isIntN(LongLongSize)) { 4086 // Does it fit in a signed long long? 4087 // To be compatible with MSVC, hex integer literals ending with the 4088 // LL or i64 suffix are always signed in Microsoft mode. 4089 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 4090 (getLangOpts().MSVCCompat && Literal.isLongLong))) 4091 Ty = Context.LongLongTy; 4092 else if (AllowUnsigned) 4093 Ty = Context.UnsignedLongLongTy; 4094 Width = LongLongSize; 4095 } 4096 } 4097 4098 // If we still couldn't decide a type, we either have 'size_t' literal 4099 // that is out of range, or a decimal literal that does not fit in a 4100 // signed long long and has no U suffix. 4101 if (Ty.isNull()) { 4102 if (Literal.isSizeT) 4103 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 4104 << Literal.isUnsigned; 4105 else 4106 Diag(Tok.getLocation(), 4107 diag::ext_integer_literal_too_large_for_signed); 4108 Ty = Context.UnsignedLongLongTy; 4109 Width = Context.getTargetInfo().getLongLongWidth(); 4110 } 4111 4112 if (ResultVal.getBitWidth() != Width) 4113 ResultVal = ResultVal.trunc(Width); 4114 } 4115 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 4116 } 4117 4118 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 4119 if (Literal.isImaginary) { 4120 Res = new (Context) ImaginaryLiteral(Res, 4121 Context.getComplexType(Res->getType())); 4122 4123 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4124 } 4125 return Res; 4126 } 4127 4128 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4129 assert(E && "ActOnParenExpr() missing expr"); 4130 QualType ExprTy = E->getType(); 4131 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && 4132 !E->isLValue() && ExprTy->hasFloatingRepresentation()) 4133 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); 4134 return new (Context) ParenExpr(L, R, E); 4135 } 4136 4137 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4138 SourceLocation Loc, 4139 SourceRange ArgRange) { 4140 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4141 // scalar or vector data type argument..." 4142 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4143 // type (C99 6.2.5p18) or void. 4144 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4145 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4146 << T << ArgRange; 4147 return true; 4148 } 4149 4150 assert((T->isVoidType() || !T->isIncompleteType()) && 4151 "Scalar types should always be complete"); 4152 return false; 4153 } 4154 4155 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4156 SourceLocation Loc, 4157 SourceRange ArgRange, 4158 UnaryExprOrTypeTrait TraitKind) { 4159 // Invalid types must be hard errors for SFINAE in C++. 4160 if (S.LangOpts.CPlusPlus) 4161 return true; 4162 4163 // C99 6.5.3.4p1: 4164 if (T->isFunctionType() && 4165 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4166 TraitKind == UETT_PreferredAlignOf)) { 4167 // sizeof(function)/alignof(function) is allowed as an extension. 4168 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4169 << getTraitSpelling(TraitKind) << ArgRange; 4170 return false; 4171 } 4172 4173 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4174 // this is an error (OpenCL v1.1 s6.3.k) 4175 if (T->isVoidType()) { 4176 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4177 : diag::ext_sizeof_alignof_void_type; 4178 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4179 return false; 4180 } 4181 4182 return true; 4183 } 4184 4185 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4186 SourceLocation Loc, 4187 SourceRange ArgRange, 4188 UnaryExprOrTypeTrait TraitKind) { 4189 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4190 // runtime doesn't allow it. 4191 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4192 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4193 << T << (TraitKind == UETT_SizeOf) 4194 << ArgRange; 4195 return true; 4196 } 4197 4198 return false; 4199 } 4200 4201 /// Check whether E is a pointer from a decayed array type (the decayed 4202 /// pointer type is equal to T) and emit a warning if it is. 4203 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4204 Expr *E) { 4205 // Don't warn if the operation changed the type. 4206 if (T != E->getType()) 4207 return; 4208 4209 // Now look for array decays. 4210 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4211 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4212 return; 4213 4214 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4215 << ICE->getType() 4216 << ICE->getSubExpr()->getType(); 4217 } 4218 4219 /// Check the constraints on expression operands to unary type expression 4220 /// and type traits. 4221 /// 4222 /// Completes any types necessary and validates the constraints on the operand 4223 /// expression. The logic mostly mirrors the type-based overload, but may modify 4224 /// the expression as it completes the type for that expression through template 4225 /// instantiation, etc. 4226 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4227 UnaryExprOrTypeTrait ExprKind) { 4228 QualType ExprTy = E->getType(); 4229 assert(!ExprTy->isReferenceType()); 4230 4231 bool IsUnevaluatedOperand = 4232 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4233 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4234 if (IsUnevaluatedOperand) { 4235 ExprResult Result = CheckUnevaluatedOperand(E); 4236 if (Result.isInvalid()) 4237 return true; 4238 E = Result.get(); 4239 } 4240 4241 // The operand for sizeof and alignof is in an unevaluated expression context, 4242 // so side effects could result in unintended consequences. 4243 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4244 // used to build SFINAE gadgets. 4245 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4246 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4247 !E->isInstantiationDependent() && 4248 E->HasSideEffects(Context, false)) 4249 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4250 4251 if (ExprKind == UETT_VecStep) 4252 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4253 E->getSourceRange()); 4254 4255 // Explicitly list some types as extensions. 4256 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4257 E->getSourceRange(), ExprKind)) 4258 return false; 4259 4260 // 'alignof' applied to an expression only requires the base element type of 4261 // the expression to be complete. 'sizeof' requires the expression's type to 4262 // be complete (and will attempt to complete it if it's an array of unknown 4263 // bound). 4264 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4265 if (RequireCompleteSizedType( 4266 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4267 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4268 getTraitSpelling(ExprKind), E->getSourceRange())) 4269 return true; 4270 } else { 4271 if (RequireCompleteSizedExprType( 4272 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4273 getTraitSpelling(ExprKind), E->getSourceRange())) 4274 return true; 4275 } 4276 4277 // Completing the expression's type may have changed it. 4278 ExprTy = E->getType(); 4279 assert(!ExprTy->isReferenceType()); 4280 4281 if (ExprTy->isFunctionType()) { 4282 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4283 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4284 return true; 4285 } 4286 4287 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4288 E->getSourceRange(), ExprKind)) 4289 return true; 4290 4291 if (ExprKind == UETT_SizeOf) { 4292 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4293 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4294 QualType OType = PVD->getOriginalType(); 4295 QualType Type = PVD->getType(); 4296 if (Type->isPointerType() && OType->isArrayType()) { 4297 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4298 << Type << OType; 4299 Diag(PVD->getLocation(), diag::note_declared_at); 4300 } 4301 } 4302 } 4303 4304 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4305 // decays into a pointer and returns an unintended result. This is most 4306 // likely a typo for "sizeof(array) op x". 4307 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4308 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4309 BO->getLHS()); 4310 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4311 BO->getRHS()); 4312 } 4313 } 4314 4315 return false; 4316 } 4317 4318 /// Check the constraints on operands to unary expression and type 4319 /// traits. 4320 /// 4321 /// This will complete any types necessary, and validate the various constraints 4322 /// on those operands. 4323 /// 4324 /// The UsualUnaryConversions() function is *not* called by this routine. 4325 /// C99 6.3.2.1p[2-4] all state: 4326 /// Except when it is the operand of the sizeof operator ... 4327 /// 4328 /// C++ [expr.sizeof]p4 4329 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4330 /// standard conversions are not applied to the operand of sizeof. 4331 /// 4332 /// This policy is followed for all of the unary trait expressions. 4333 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4334 SourceLocation OpLoc, 4335 SourceRange ExprRange, 4336 UnaryExprOrTypeTrait ExprKind) { 4337 if (ExprType->isDependentType()) 4338 return false; 4339 4340 // C++ [expr.sizeof]p2: 4341 // When applied to a reference or a reference type, the result 4342 // is the size of the referenced type. 4343 // C++11 [expr.alignof]p3: 4344 // When alignof is applied to a reference type, the result 4345 // shall be the alignment of the referenced type. 4346 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4347 ExprType = Ref->getPointeeType(); 4348 4349 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4350 // When alignof or _Alignof is applied to an array type, the result 4351 // is the alignment of the element type. 4352 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4353 ExprKind == UETT_OpenMPRequiredSimdAlign) 4354 ExprType = Context.getBaseElementType(ExprType); 4355 4356 if (ExprKind == UETT_VecStep) 4357 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4358 4359 // Explicitly list some types as extensions. 4360 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4361 ExprKind)) 4362 return false; 4363 4364 if (RequireCompleteSizedType( 4365 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4366 getTraitSpelling(ExprKind), ExprRange)) 4367 return true; 4368 4369 if (ExprType->isFunctionType()) { 4370 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4371 << getTraitSpelling(ExprKind) << ExprRange; 4372 return true; 4373 } 4374 4375 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4376 ExprKind)) 4377 return true; 4378 4379 return false; 4380 } 4381 4382 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4383 // Cannot know anything else if the expression is dependent. 4384 if (E->isTypeDependent()) 4385 return false; 4386 4387 if (E->getObjectKind() == OK_BitField) { 4388 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4389 << 1 << E->getSourceRange(); 4390 return true; 4391 } 4392 4393 ValueDecl *D = nullptr; 4394 Expr *Inner = E->IgnoreParens(); 4395 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4396 D = DRE->getDecl(); 4397 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4398 D = ME->getMemberDecl(); 4399 } 4400 4401 // If it's a field, require the containing struct to have a 4402 // complete definition so that we can compute the layout. 4403 // 4404 // This can happen in C++11 onwards, either by naming the member 4405 // in a way that is not transformed into a member access expression 4406 // (in an unevaluated operand, for instance), or by naming the member 4407 // in a trailing-return-type. 4408 // 4409 // For the record, since __alignof__ on expressions is a GCC 4410 // extension, GCC seems to permit this but always gives the 4411 // nonsensical answer 0. 4412 // 4413 // We don't really need the layout here --- we could instead just 4414 // directly check for all the appropriate alignment-lowing 4415 // attributes --- but that would require duplicating a lot of 4416 // logic that just isn't worth duplicating for such a marginal 4417 // use-case. 4418 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4419 // Fast path this check, since we at least know the record has a 4420 // definition if we can find a member of it. 4421 if (!FD->getParent()->isCompleteDefinition()) { 4422 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4423 << E->getSourceRange(); 4424 return true; 4425 } 4426 4427 // Otherwise, if it's a field, and the field doesn't have 4428 // reference type, then it must have a complete type (or be a 4429 // flexible array member, which we explicitly want to 4430 // white-list anyway), which makes the following checks trivial. 4431 if (!FD->getType()->isReferenceType()) 4432 return false; 4433 } 4434 4435 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4436 } 4437 4438 bool Sema::CheckVecStepExpr(Expr *E) { 4439 E = E->IgnoreParens(); 4440 4441 // Cannot know anything else if the expression is dependent. 4442 if (E->isTypeDependent()) 4443 return false; 4444 4445 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4446 } 4447 4448 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4449 CapturingScopeInfo *CSI) { 4450 assert(T->isVariablyModifiedType()); 4451 assert(CSI != nullptr); 4452 4453 // We're going to walk down into the type and look for VLA expressions. 4454 do { 4455 const Type *Ty = T.getTypePtr(); 4456 switch (Ty->getTypeClass()) { 4457 #define TYPE(Class, Base) 4458 #define ABSTRACT_TYPE(Class, Base) 4459 #define NON_CANONICAL_TYPE(Class, Base) 4460 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4461 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4462 #include "clang/AST/TypeNodes.inc" 4463 T = QualType(); 4464 break; 4465 // These types are never variably-modified. 4466 case Type::Builtin: 4467 case Type::Complex: 4468 case Type::Vector: 4469 case Type::ExtVector: 4470 case Type::ConstantMatrix: 4471 case Type::Record: 4472 case Type::Enum: 4473 case Type::Elaborated: 4474 case Type::TemplateSpecialization: 4475 case Type::ObjCObject: 4476 case Type::ObjCInterface: 4477 case Type::ObjCObjectPointer: 4478 case Type::ObjCTypeParam: 4479 case Type::Pipe: 4480 case Type::BitInt: 4481 llvm_unreachable("type class is never variably-modified!"); 4482 case Type::Adjusted: 4483 T = cast<AdjustedType>(Ty)->getOriginalType(); 4484 break; 4485 case Type::Decayed: 4486 T = cast<DecayedType>(Ty)->getPointeeType(); 4487 break; 4488 case Type::Pointer: 4489 T = cast<PointerType>(Ty)->getPointeeType(); 4490 break; 4491 case Type::BlockPointer: 4492 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4493 break; 4494 case Type::LValueReference: 4495 case Type::RValueReference: 4496 T = cast<ReferenceType>(Ty)->getPointeeType(); 4497 break; 4498 case Type::MemberPointer: 4499 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4500 break; 4501 case Type::ConstantArray: 4502 case Type::IncompleteArray: 4503 // Losing element qualification here is fine. 4504 T = cast<ArrayType>(Ty)->getElementType(); 4505 break; 4506 case Type::VariableArray: { 4507 // Losing element qualification here is fine. 4508 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4509 4510 // Unknown size indication requires no size computation. 4511 // Otherwise, evaluate and record it. 4512 auto Size = VAT->getSizeExpr(); 4513 if (Size && !CSI->isVLATypeCaptured(VAT) && 4514 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4515 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4516 4517 T = VAT->getElementType(); 4518 break; 4519 } 4520 case Type::FunctionProto: 4521 case Type::FunctionNoProto: 4522 T = cast<FunctionType>(Ty)->getReturnType(); 4523 break; 4524 case Type::Paren: 4525 case Type::TypeOf: 4526 case Type::UnaryTransform: 4527 case Type::Attributed: 4528 case Type::BTFTagAttributed: 4529 case Type::SubstTemplateTypeParm: 4530 case Type::MacroQualified: 4531 // Keep walking after single level desugaring. 4532 T = T.getSingleStepDesugaredType(Context); 4533 break; 4534 case Type::Typedef: 4535 T = cast<TypedefType>(Ty)->desugar(); 4536 break; 4537 case Type::Decltype: 4538 T = cast<DecltypeType>(Ty)->desugar(); 4539 break; 4540 case Type::Using: 4541 T = cast<UsingType>(Ty)->desugar(); 4542 break; 4543 case Type::Auto: 4544 case Type::DeducedTemplateSpecialization: 4545 T = cast<DeducedType>(Ty)->getDeducedType(); 4546 break; 4547 case Type::TypeOfExpr: 4548 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4549 break; 4550 case Type::Atomic: 4551 T = cast<AtomicType>(Ty)->getValueType(); 4552 break; 4553 } 4554 } while (!T.isNull() && T->isVariablyModifiedType()); 4555 } 4556 4557 /// Build a sizeof or alignof expression given a type operand. 4558 ExprResult 4559 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4560 SourceLocation OpLoc, 4561 UnaryExprOrTypeTrait ExprKind, 4562 SourceRange R) { 4563 if (!TInfo) 4564 return ExprError(); 4565 4566 QualType T = TInfo->getType(); 4567 4568 if (!T->isDependentType() && 4569 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4570 return ExprError(); 4571 4572 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4573 if (auto *TT = T->getAs<TypedefType>()) { 4574 for (auto I = FunctionScopes.rbegin(), 4575 E = std::prev(FunctionScopes.rend()); 4576 I != E; ++I) { 4577 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4578 if (CSI == nullptr) 4579 break; 4580 DeclContext *DC = nullptr; 4581 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4582 DC = LSI->CallOperator; 4583 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4584 DC = CRSI->TheCapturedDecl; 4585 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4586 DC = BSI->TheDecl; 4587 if (DC) { 4588 if (DC->containsDecl(TT->getDecl())) 4589 break; 4590 captureVariablyModifiedType(Context, T, CSI); 4591 } 4592 } 4593 } 4594 } 4595 4596 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4597 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf && 4598 TInfo->getType()->isVariablyModifiedType()) 4599 TInfo = TransformToPotentiallyEvaluated(TInfo); 4600 4601 return new (Context) UnaryExprOrTypeTraitExpr( 4602 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4603 } 4604 4605 /// Build a sizeof or alignof expression given an expression 4606 /// operand. 4607 ExprResult 4608 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4609 UnaryExprOrTypeTrait ExprKind) { 4610 ExprResult PE = CheckPlaceholderExpr(E); 4611 if (PE.isInvalid()) 4612 return ExprError(); 4613 4614 E = PE.get(); 4615 4616 // Verify that the operand is valid. 4617 bool isInvalid = false; 4618 if (E->isTypeDependent()) { 4619 // Delay type-checking for type-dependent expressions. 4620 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4621 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4622 } else if (ExprKind == UETT_VecStep) { 4623 isInvalid = CheckVecStepExpr(E); 4624 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4625 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4626 isInvalid = true; 4627 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4628 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4629 isInvalid = true; 4630 } else { 4631 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4632 } 4633 4634 if (isInvalid) 4635 return ExprError(); 4636 4637 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4638 PE = TransformToPotentiallyEvaluated(E); 4639 if (PE.isInvalid()) return ExprError(); 4640 E = PE.get(); 4641 } 4642 4643 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4644 return new (Context) UnaryExprOrTypeTraitExpr( 4645 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4646 } 4647 4648 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4649 /// expr and the same for @c alignof and @c __alignof 4650 /// Note that the ArgRange is invalid if isType is false. 4651 ExprResult 4652 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4653 UnaryExprOrTypeTrait ExprKind, bool IsType, 4654 void *TyOrEx, SourceRange ArgRange) { 4655 // If error parsing type, ignore. 4656 if (!TyOrEx) return ExprError(); 4657 4658 if (IsType) { 4659 TypeSourceInfo *TInfo; 4660 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4661 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4662 } 4663 4664 Expr *ArgEx = (Expr *)TyOrEx; 4665 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4666 return Result; 4667 } 4668 4669 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4670 bool IsReal) { 4671 if (V.get()->isTypeDependent()) 4672 return S.Context.DependentTy; 4673 4674 // _Real and _Imag are only l-values for normal l-values. 4675 if (V.get()->getObjectKind() != OK_Ordinary) { 4676 V = S.DefaultLvalueConversion(V.get()); 4677 if (V.isInvalid()) 4678 return QualType(); 4679 } 4680 4681 // These operators return the element type of a complex type. 4682 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4683 return CT->getElementType(); 4684 4685 // Otherwise they pass through real integer and floating point types here. 4686 if (V.get()->getType()->isArithmeticType()) 4687 return V.get()->getType(); 4688 4689 // Test for placeholders. 4690 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4691 if (PR.isInvalid()) return QualType(); 4692 if (PR.get() != V.get()) { 4693 V = PR; 4694 return CheckRealImagOperand(S, V, Loc, IsReal); 4695 } 4696 4697 // Reject anything else. 4698 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4699 << (IsReal ? "__real" : "__imag"); 4700 return QualType(); 4701 } 4702 4703 4704 4705 ExprResult 4706 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4707 tok::TokenKind Kind, Expr *Input) { 4708 UnaryOperatorKind Opc; 4709 switch (Kind) { 4710 default: llvm_unreachable("Unknown unary op!"); 4711 case tok::plusplus: Opc = UO_PostInc; break; 4712 case tok::minusminus: Opc = UO_PostDec; break; 4713 } 4714 4715 // Since this might is a postfix expression, get rid of ParenListExprs. 4716 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4717 if (Result.isInvalid()) return ExprError(); 4718 Input = Result.get(); 4719 4720 return BuildUnaryOp(S, OpLoc, Opc, Input); 4721 } 4722 4723 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4724 /// 4725 /// \return true on error 4726 static bool checkArithmeticOnObjCPointer(Sema &S, 4727 SourceLocation opLoc, 4728 Expr *op) { 4729 assert(op->getType()->isObjCObjectPointerType()); 4730 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4731 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4732 return false; 4733 4734 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4735 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4736 << op->getSourceRange(); 4737 return true; 4738 } 4739 4740 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4741 auto *BaseNoParens = Base->IgnoreParens(); 4742 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4743 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4744 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4745 } 4746 4747 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent. 4748 // Typically this is DependentTy, but can sometimes be more precise. 4749 // 4750 // There are cases when we could determine a non-dependent type: 4751 // - LHS and RHS may have non-dependent types despite being type-dependent 4752 // (e.g. unbounded array static members of the current instantiation) 4753 // - one may be a dependent-sized array with known element type 4754 // - one may be a dependent-typed valid index (enum in current instantiation) 4755 // 4756 // We *always* return a dependent type, in such cases it is DependentTy. 4757 // This avoids creating type-dependent expressions with non-dependent types. 4758 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275 4759 static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, 4760 const ASTContext &Ctx) { 4761 assert(LHS->isTypeDependent() || RHS->isTypeDependent()); 4762 QualType LTy = LHS->getType(), RTy = RHS->getType(); 4763 QualType Result = Ctx.DependentTy; 4764 if (RTy->isIntegralOrUnscopedEnumerationType()) { 4765 if (const PointerType *PT = LTy->getAs<PointerType>()) 4766 Result = PT->getPointeeType(); 4767 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe()) 4768 Result = AT->getElementType(); 4769 } else if (LTy->isIntegralOrUnscopedEnumerationType()) { 4770 if (const PointerType *PT = RTy->getAs<PointerType>()) 4771 Result = PT->getPointeeType(); 4772 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe()) 4773 Result = AT->getElementType(); 4774 } 4775 // Ensure we return a dependent type. 4776 return Result->isDependentType() ? Result : Ctx.DependentTy; 4777 } 4778 4779 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args); 4780 4781 ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, 4782 SourceLocation lbLoc, 4783 MultiExprArg ArgExprs, 4784 SourceLocation rbLoc) { 4785 4786 if (base && !base->getType().isNull() && 4787 base->hasPlaceholderType(BuiltinType::OMPArraySection)) 4788 return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(), 4789 SourceLocation(), /*Length*/ nullptr, 4790 /*Stride=*/nullptr, rbLoc); 4791 4792 // Since this might be a postfix expression, get rid of ParenListExprs. 4793 if (isa<ParenListExpr>(base)) { 4794 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4795 if (result.isInvalid()) 4796 return ExprError(); 4797 base = result.get(); 4798 } 4799 4800 // Check if base and idx form a MatrixSubscriptExpr. 4801 // 4802 // Helper to check for comma expressions, which are not allowed as indices for 4803 // matrix subscript expressions. 4804 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4805 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4806 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4807 << SourceRange(base->getBeginLoc(), rbLoc); 4808 return true; 4809 } 4810 return false; 4811 }; 4812 // The matrix subscript operator ([][])is considered a single operator. 4813 // Separating the index expressions by parenthesis is not allowed. 4814 if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) && 4815 !isa<MatrixSubscriptExpr>(base)) { 4816 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4817 << SourceRange(base->getBeginLoc(), rbLoc); 4818 return ExprError(); 4819 } 4820 // If the base is a MatrixSubscriptExpr, try to create a new 4821 // MatrixSubscriptExpr. 4822 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4823 if (matSubscriptE) { 4824 assert(ArgExprs.size() == 1); 4825 if (CheckAndReportCommaError(ArgExprs.front())) 4826 return ExprError(); 4827 4828 assert(matSubscriptE->isIncomplete() && 4829 "base has to be an incomplete matrix subscript"); 4830 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(), 4831 matSubscriptE->getRowIdx(), 4832 ArgExprs.front(), rbLoc); 4833 } 4834 4835 // Handle any non-overload placeholder types in the base and index 4836 // expressions. We can't handle overloads here because the other 4837 // operand might be an overloadable type, in which case the overload 4838 // resolution for the operator overload should get the first crack 4839 // at the overload. 4840 bool IsMSPropertySubscript = false; 4841 if (base->getType()->isNonOverloadPlaceholderType()) { 4842 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4843 if (!IsMSPropertySubscript) { 4844 ExprResult result = CheckPlaceholderExpr(base); 4845 if (result.isInvalid()) 4846 return ExprError(); 4847 base = result.get(); 4848 } 4849 } 4850 4851 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4852 if (base->getType()->isMatrixType()) { 4853 assert(ArgExprs.size() == 1); 4854 if (CheckAndReportCommaError(ArgExprs.front())) 4855 return ExprError(); 4856 4857 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr, 4858 rbLoc); 4859 } 4860 4861 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) { 4862 Expr *idx = ArgExprs[0]; 4863 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4864 (isa<CXXOperatorCallExpr>(idx) && 4865 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) { 4866 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4867 << SourceRange(base->getBeginLoc(), rbLoc); 4868 } 4869 } 4870 4871 if (ArgExprs.size() == 1 && 4872 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) { 4873 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]); 4874 if (result.isInvalid()) 4875 return ExprError(); 4876 ArgExprs[0] = result.get(); 4877 } else { 4878 if (checkArgsForPlaceholders(*this, ArgExprs)) 4879 return ExprError(); 4880 } 4881 4882 // Build an unanalyzed expression if either operand is type-dependent. 4883 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 && 4884 (base->isTypeDependent() || 4885 Expr::hasAnyTypeDependentArguments(ArgExprs))) { 4886 return new (Context) ArraySubscriptExpr( 4887 base, ArgExprs.front(), 4888 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()), 4889 VK_LValue, OK_Ordinary, rbLoc); 4890 } 4891 4892 // MSDN, property (C++) 4893 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4894 // This attribute can also be used in the declaration of an empty array in a 4895 // class or structure definition. For example: 4896 // __declspec(property(get=GetX, put=PutX)) int x[]; 4897 // The above statement indicates that x[] can be used with one or more array 4898 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4899 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4900 if (IsMSPropertySubscript) { 4901 assert(ArgExprs.size() == 1); 4902 // Build MS property subscript expression if base is MS property reference 4903 // or MS property subscript. 4904 return new (Context) 4905 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy, 4906 VK_LValue, OK_Ordinary, rbLoc); 4907 } 4908 4909 // Use C++ overloaded-operator rules if either operand has record 4910 // type. The spec says to do this if either type is *overloadable*, 4911 // but enum types can't declare subscript operators or conversion 4912 // operators, so there's nothing interesting for overload resolution 4913 // to do if there aren't any record types involved. 4914 // 4915 // ObjC pointers have their own subscripting logic that is not tied 4916 // to overload resolution and so should not take this path. 4917 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() && 4918 ((base->getType()->isRecordType() || 4919 (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) { 4920 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs); 4921 } 4922 4923 ExprResult Res = 4924 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc); 4925 4926 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4927 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4928 4929 return Res; 4930 } 4931 4932 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4933 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4934 InitializationKind Kind = 4935 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4936 InitializationSequence InitSeq(*this, Entity, Kind, E); 4937 return InitSeq.Perform(*this, Entity, Kind, E); 4938 } 4939 4940 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4941 Expr *ColumnIdx, 4942 SourceLocation RBLoc) { 4943 ExprResult BaseR = CheckPlaceholderExpr(Base); 4944 if (BaseR.isInvalid()) 4945 return BaseR; 4946 Base = BaseR.get(); 4947 4948 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4949 if (RowR.isInvalid()) 4950 return RowR; 4951 RowIdx = RowR.get(); 4952 4953 if (!ColumnIdx) 4954 return new (Context) MatrixSubscriptExpr( 4955 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4956 4957 // Build an unanalyzed expression if any of the operands is type-dependent. 4958 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4959 ColumnIdx->isTypeDependent()) 4960 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4961 Context.DependentTy, RBLoc); 4962 4963 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4964 if (ColumnR.isInvalid()) 4965 return ColumnR; 4966 ColumnIdx = ColumnR.get(); 4967 4968 // Check that IndexExpr is an integer expression. If it is a constant 4969 // expression, check that it is less than Dim (= the number of elements in the 4970 // corresponding dimension). 4971 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4972 bool IsColumnIdx) -> Expr * { 4973 if (!IndexExpr->getType()->isIntegerType() && 4974 !IndexExpr->isTypeDependent()) { 4975 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4976 << IsColumnIdx; 4977 return nullptr; 4978 } 4979 4980 if (Optional<llvm::APSInt> Idx = 4981 IndexExpr->getIntegerConstantExpr(Context)) { 4982 if ((*Idx < 0 || *Idx >= Dim)) { 4983 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4984 << IsColumnIdx << Dim; 4985 return nullptr; 4986 } 4987 } 4988 4989 ExprResult ConvExpr = 4990 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4991 assert(!ConvExpr.isInvalid() && 4992 "should be able to convert any integer type to size type"); 4993 return ConvExpr.get(); 4994 }; 4995 4996 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4997 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4998 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4999 if (!RowIdx || !ColumnIdx) 5000 return ExprError(); 5001 5002 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 5003 MTy->getElementType(), RBLoc); 5004 } 5005 5006 void Sema::CheckAddressOfNoDeref(const Expr *E) { 5007 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 5008 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 5009 5010 // For expressions like `&(*s).b`, the base is recorded and what should be 5011 // checked. 5012 const MemberExpr *Member = nullptr; 5013 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 5014 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 5015 5016 LastRecord.PossibleDerefs.erase(StrippedExpr); 5017 } 5018 5019 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 5020 if (isUnevaluatedContext()) 5021 return; 5022 5023 QualType ResultTy = E->getType(); 5024 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 5025 5026 // Bail if the element is an array since it is not memory access. 5027 if (isa<ArrayType>(ResultTy)) 5028 return; 5029 5030 if (ResultTy->hasAttr(attr::NoDeref)) { 5031 LastRecord.PossibleDerefs.insert(E); 5032 return; 5033 } 5034 5035 // Check if the base type is a pointer to a member access of a struct 5036 // marked with noderef. 5037 const Expr *Base = E->getBase(); 5038 QualType BaseTy = Base->getType(); 5039 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 5040 // Not a pointer access 5041 return; 5042 5043 const MemberExpr *Member = nullptr; 5044 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 5045 Member->isArrow()) 5046 Base = Member->getBase(); 5047 5048 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 5049 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 5050 LastRecord.PossibleDerefs.insert(E); 5051 } 5052 } 5053 5054 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 5055 Expr *LowerBound, 5056 SourceLocation ColonLocFirst, 5057 SourceLocation ColonLocSecond, 5058 Expr *Length, Expr *Stride, 5059 SourceLocation RBLoc) { 5060 if (Base->hasPlaceholderType() && 5061 !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) { 5062 ExprResult Result = CheckPlaceholderExpr(Base); 5063 if (Result.isInvalid()) 5064 return ExprError(); 5065 Base = Result.get(); 5066 } 5067 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 5068 ExprResult Result = CheckPlaceholderExpr(LowerBound); 5069 if (Result.isInvalid()) 5070 return ExprError(); 5071 Result = DefaultLvalueConversion(Result.get()); 5072 if (Result.isInvalid()) 5073 return ExprError(); 5074 LowerBound = Result.get(); 5075 } 5076 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 5077 ExprResult Result = CheckPlaceholderExpr(Length); 5078 if (Result.isInvalid()) 5079 return ExprError(); 5080 Result = DefaultLvalueConversion(Result.get()); 5081 if (Result.isInvalid()) 5082 return ExprError(); 5083 Length = Result.get(); 5084 } 5085 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 5086 ExprResult Result = CheckPlaceholderExpr(Stride); 5087 if (Result.isInvalid()) 5088 return ExprError(); 5089 Result = DefaultLvalueConversion(Result.get()); 5090 if (Result.isInvalid()) 5091 return ExprError(); 5092 Stride = Result.get(); 5093 } 5094 5095 // Build an unanalyzed expression if either operand is type-dependent. 5096 if (Base->isTypeDependent() || 5097 (LowerBound && 5098 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 5099 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 5100 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 5101 return new (Context) OMPArraySectionExpr( 5102 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 5103 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5104 } 5105 5106 // Perform default conversions. 5107 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 5108 QualType ResultTy; 5109 if (OriginalTy->isAnyPointerType()) { 5110 ResultTy = OriginalTy->getPointeeType(); 5111 } else if (OriginalTy->isArrayType()) { 5112 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 5113 } else { 5114 return ExprError( 5115 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 5116 << Base->getSourceRange()); 5117 } 5118 // C99 6.5.2.1p1 5119 if (LowerBound) { 5120 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 5121 LowerBound); 5122 if (Res.isInvalid()) 5123 return ExprError(Diag(LowerBound->getExprLoc(), 5124 diag::err_omp_typecheck_section_not_integer) 5125 << 0 << LowerBound->getSourceRange()); 5126 LowerBound = Res.get(); 5127 5128 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5129 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5130 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 5131 << 0 << LowerBound->getSourceRange(); 5132 } 5133 if (Length) { 5134 auto Res = 5135 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 5136 if (Res.isInvalid()) 5137 return ExprError(Diag(Length->getExprLoc(), 5138 diag::err_omp_typecheck_section_not_integer) 5139 << 1 << Length->getSourceRange()); 5140 Length = Res.get(); 5141 5142 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5143 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5144 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 5145 << 1 << Length->getSourceRange(); 5146 } 5147 if (Stride) { 5148 ExprResult Res = 5149 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 5150 if (Res.isInvalid()) 5151 return ExprError(Diag(Stride->getExprLoc(), 5152 diag::err_omp_typecheck_section_not_integer) 5153 << 1 << Stride->getSourceRange()); 5154 Stride = Res.get(); 5155 5156 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5157 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5158 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5159 << 1 << Stride->getSourceRange(); 5160 } 5161 5162 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5163 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5164 // type. Note that functions are not objects, and that (in C99 parlance) 5165 // incomplete types are not object types. 5166 if (ResultTy->isFunctionType()) { 5167 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5168 << ResultTy << Base->getSourceRange(); 5169 return ExprError(); 5170 } 5171 5172 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5173 diag::err_omp_section_incomplete_type, Base)) 5174 return ExprError(); 5175 5176 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5177 Expr::EvalResult Result; 5178 if (LowerBound->EvaluateAsInt(Result, Context)) { 5179 // OpenMP 5.0, [2.1.5 Array Sections] 5180 // The array section must be a subset of the original array. 5181 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5182 if (LowerBoundValue.isNegative()) { 5183 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5184 << LowerBound->getSourceRange(); 5185 return ExprError(); 5186 } 5187 } 5188 } 5189 5190 if (Length) { 5191 Expr::EvalResult Result; 5192 if (Length->EvaluateAsInt(Result, Context)) { 5193 // OpenMP 5.0, [2.1.5 Array Sections] 5194 // The length must evaluate to non-negative integers. 5195 llvm::APSInt LengthValue = Result.Val.getInt(); 5196 if (LengthValue.isNegative()) { 5197 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5198 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5199 << Length->getSourceRange(); 5200 return ExprError(); 5201 } 5202 } 5203 } else if (ColonLocFirst.isValid() && 5204 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5205 !OriginalTy->isVariableArrayType()))) { 5206 // OpenMP 5.0, [2.1.5 Array Sections] 5207 // When the size of the array dimension is not known, the length must be 5208 // specified explicitly. 5209 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5210 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5211 return ExprError(); 5212 } 5213 5214 if (Stride) { 5215 Expr::EvalResult Result; 5216 if (Stride->EvaluateAsInt(Result, Context)) { 5217 // OpenMP 5.0, [2.1.5 Array Sections] 5218 // The stride must evaluate to a positive integer. 5219 llvm::APSInt StrideValue = Result.Val.getInt(); 5220 if (!StrideValue.isStrictlyPositive()) { 5221 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5222 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5223 << Stride->getSourceRange(); 5224 return ExprError(); 5225 } 5226 } 5227 } 5228 5229 if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) { 5230 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5231 if (Result.isInvalid()) 5232 return ExprError(); 5233 Base = Result.get(); 5234 } 5235 return new (Context) OMPArraySectionExpr( 5236 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5237 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5238 } 5239 5240 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5241 SourceLocation RParenLoc, 5242 ArrayRef<Expr *> Dims, 5243 ArrayRef<SourceRange> Brackets) { 5244 if (Base->hasPlaceholderType()) { 5245 ExprResult Result = CheckPlaceholderExpr(Base); 5246 if (Result.isInvalid()) 5247 return ExprError(); 5248 Result = DefaultLvalueConversion(Result.get()); 5249 if (Result.isInvalid()) 5250 return ExprError(); 5251 Base = Result.get(); 5252 } 5253 QualType BaseTy = Base->getType(); 5254 // Delay analysis of the types/expressions if instantiation/specialization is 5255 // required. 5256 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5257 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5258 LParenLoc, RParenLoc, Dims, Brackets); 5259 if (!BaseTy->isPointerType() || 5260 (!Base->isTypeDependent() && 5261 BaseTy->getPointeeType()->isIncompleteType())) 5262 return ExprError(Diag(Base->getExprLoc(), 5263 diag::err_omp_non_pointer_type_array_shaping_base) 5264 << Base->getSourceRange()); 5265 5266 SmallVector<Expr *, 4> NewDims; 5267 bool ErrorFound = false; 5268 for (Expr *Dim : Dims) { 5269 if (Dim->hasPlaceholderType()) { 5270 ExprResult Result = CheckPlaceholderExpr(Dim); 5271 if (Result.isInvalid()) { 5272 ErrorFound = true; 5273 continue; 5274 } 5275 Result = DefaultLvalueConversion(Result.get()); 5276 if (Result.isInvalid()) { 5277 ErrorFound = true; 5278 continue; 5279 } 5280 Dim = Result.get(); 5281 } 5282 if (!Dim->isTypeDependent()) { 5283 ExprResult Result = 5284 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5285 if (Result.isInvalid()) { 5286 ErrorFound = true; 5287 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5288 << Dim->getSourceRange(); 5289 continue; 5290 } 5291 Dim = Result.get(); 5292 Expr::EvalResult EvResult; 5293 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5294 // OpenMP 5.0, [2.1.4 Array Shaping] 5295 // Each si is an integral type expression that must evaluate to a 5296 // positive integer. 5297 llvm::APSInt Value = EvResult.Val.getInt(); 5298 if (!Value.isStrictlyPositive()) { 5299 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5300 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5301 << Dim->getSourceRange(); 5302 ErrorFound = true; 5303 continue; 5304 } 5305 } 5306 } 5307 NewDims.push_back(Dim); 5308 } 5309 if (ErrorFound) 5310 return ExprError(); 5311 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5312 LParenLoc, RParenLoc, NewDims, Brackets); 5313 } 5314 5315 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5316 SourceLocation LLoc, SourceLocation RLoc, 5317 ArrayRef<OMPIteratorData> Data) { 5318 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5319 bool IsCorrect = true; 5320 for (const OMPIteratorData &D : Data) { 5321 TypeSourceInfo *TInfo = nullptr; 5322 SourceLocation StartLoc; 5323 QualType DeclTy; 5324 if (!D.Type.getAsOpaquePtr()) { 5325 // OpenMP 5.0, 2.1.6 Iterators 5326 // In an iterator-specifier, if the iterator-type is not specified then 5327 // the type of that iterator is of int type. 5328 DeclTy = Context.IntTy; 5329 StartLoc = D.DeclIdentLoc; 5330 } else { 5331 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5332 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5333 } 5334 5335 bool IsDeclTyDependent = DeclTy->isDependentType() || 5336 DeclTy->containsUnexpandedParameterPack() || 5337 DeclTy->isInstantiationDependentType(); 5338 if (!IsDeclTyDependent) { 5339 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5340 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5341 // The iterator-type must be an integral or pointer type. 5342 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5343 << DeclTy; 5344 IsCorrect = false; 5345 continue; 5346 } 5347 if (DeclTy.isConstant(Context)) { 5348 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5349 // The iterator-type must not be const qualified. 5350 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5351 << DeclTy; 5352 IsCorrect = false; 5353 continue; 5354 } 5355 } 5356 5357 // Iterator declaration. 5358 assert(D.DeclIdent && "Identifier expected."); 5359 // Always try to create iterator declarator to avoid extra error messages 5360 // about unknown declarations use. 5361 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5362 D.DeclIdent, DeclTy, TInfo, SC_None); 5363 VD->setImplicit(); 5364 if (S) { 5365 // Check for conflicting previous declaration. 5366 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5367 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5368 ForVisibleRedeclaration); 5369 Previous.suppressDiagnostics(); 5370 LookupName(Previous, S); 5371 5372 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5373 /*AllowInlineNamespace=*/false); 5374 if (!Previous.empty()) { 5375 NamedDecl *Old = Previous.getRepresentativeDecl(); 5376 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5377 Diag(Old->getLocation(), diag::note_previous_definition); 5378 } else { 5379 PushOnScopeChains(VD, S); 5380 } 5381 } else { 5382 CurContext->addDecl(VD); 5383 } 5384 Expr *Begin = D.Range.Begin; 5385 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5386 ExprResult BeginRes = 5387 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5388 Begin = BeginRes.get(); 5389 } 5390 Expr *End = D.Range.End; 5391 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5392 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5393 End = EndRes.get(); 5394 } 5395 Expr *Step = D.Range.Step; 5396 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5397 if (!Step->getType()->isIntegralType(Context)) { 5398 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5399 << Step << Step->getSourceRange(); 5400 IsCorrect = false; 5401 continue; 5402 } 5403 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5404 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5405 // If the step expression of a range-specification equals zero, the 5406 // behavior is unspecified. 5407 if (Result && Result->isZero()) { 5408 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5409 << Step << Step->getSourceRange(); 5410 IsCorrect = false; 5411 continue; 5412 } 5413 } 5414 if (!Begin || !End || !IsCorrect) { 5415 IsCorrect = false; 5416 continue; 5417 } 5418 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5419 IDElem.IteratorDecl = VD; 5420 IDElem.AssignmentLoc = D.AssignLoc; 5421 IDElem.Range.Begin = Begin; 5422 IDElem.Range.End = End; 5423 IDElem.Range.Step = Step; 5424 IDElem.ColonLoc = D.ColonLoc; 5425 IDElem.SecondColonLoc = D.SecColonLoc; 5426 } 5427 if (!IsCorrect) { 5428 // Invalidate all created iterator declarations if error is found. 5429 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5430 if (Decl *ID = D.IteratorDecl) 5431 ID->setInvalidDecl(); 5432 } 5433 return ExprError(); 5434 } 5435 SmallVector<OMPIteratorHelperData, 4> Helpers; 5436 if (!CurContext->isDependentContext()) { 5437 // Build number of ityeration for each iteration range. 5438 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5439 // ((Begini-Stepi-1-Endi) / -Stepi); 5440 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5441 // (Endi - Begini) 5442 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5443 D.Range.Begin); 5444 if(!Res.isUsable()) { 5445 IsCorrect = false; 5446 continue; 5447 } 5448 ExprResult St, St1; 5449 if (D.Range.Step) { 5450 St = D.Range.Step; 5451 // (Endi - Begini) + Stepi 5452 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5453 if (!Res.isUsable()) { 5454 IsCorrect = false; 5455 continue; 5456 } 5457 // (Endi - Begini) + Stepi - 1 5458 Res = 5459 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5460 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5461 if (!Res.isUsable()) { 5462 IsCorrect = false; 5463 continue; 5464 } 5465 // ((Endi - Begini) + Stepi - 1) / Stepi 5466 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5467 if (!Res.isUsable()) { 5468 IsCorrect = false; 5469 continue; 5470 } 5471 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5472 // (Begini - Endi) 5473 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5474 D.Range.Begin, D.Range.End); 5475 if (!Res1.isUsable()) { 5476 IsCorrect = false; 5477 continue; 5478 } 5479 // (Begini - Endi) - Stepi 5480 Res1 = 5481 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5482 if (!Res1.isUsable()) { 5483 IsCorrect = false; 5484 continue; 5485 } 5486 // (Begini - Endi) - Stepi - 1 5487 Res1 = 5488 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5489 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5490 if (!Res1.isUsable()) { 5491 IsCorrect = false; 5492 continue; 5493 } 5494 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5495 Res1 = 5496 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5497 if (!Res1.isUsable()) { 5498 IsCorrect = false; 5499 continue; 5500 } 5501 // Stepi > 0. 5502 ExprResult CmpRes = 5503 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5504 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5505 if (!CmpRes.isUsable()) { 5506 IsCorrect = false; 5507 continue; 5508 } 5509 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5510 Res.get(), Res1.get()); 5511 if (!Res.isUsable()) { 5512 IsCorrect = false; 5513 continue; 5514 } 5515 } 5516 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5517 if (!Res.isUsable()) { 5518 IsCorrect = false; 5519 continue; 5520 } 5521 5522 // Build counter update. 5523 // Build counter. 5524 auto *CounterVD = 5525 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5526 D.IteratorDecl->getBeginLoc(), nullptr, 5527 Res.get()->getType(), nullptr, SC_None); 5528 CounterVD->setImplicit(); 5529 ExprResult RefRes = 5530 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5531 D.IteratorDecl->getBeginLoc()); 5532 // Build counter update. 5533 // I = Begini + counter * Stepi; 5534 ExprResult UpdateRes; 5535 if (D.Range.Step) { 5536 UpdateRes = CreateBuiltinBinOp( 5537 D.AssignmentLoc, BO_Mul, 5538 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5539 } else { 5540 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5541 } 5542 if (!UpdateRes.isUsable()) { 5543 IsCorrect = false; 5544 continue; 5545 } 5546 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5547 UpdateRes.get()); 5548 if (!UpdateRes.isUsable()) { 5549 IsCorrect = false; 5550 continue; 5551 } 5552 ExprResult VDRes = 5553 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5554 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5555 D.IteratorDecl->getBeginLoc()); 5556 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5557 UpdateRes.get()); 5558 if (!UpdateRes.isUsable()) { 5559 IsCorrect = false; 5560 continue; 5561 } 5562 UpdateRes = 5563 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5564 if (!UpdateRes.isUsable()) { 5565 IsCorrect = false; 5566 continue; 5567 } 5568 ExprResult CounterUpdateRes = 5569 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5570 if (!CounterUpdateRes.isUsable()) { 5571 IsCorrect = false; 5572 continue; 5573 } 5574 CounterUpdateRes = 5575 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5576 if (!CounterUpdateRes.isUsable()) { 5577 IsCorrect = false; 5578 continue; 5579 } 5580 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5581 HD.CounterVD = CounterVD; 5582 HD.Upper = Res.get(); 5583 HD.Update = UpdateRes.get(); 5584 HD.CounterUpdate = CounterUpdateRes.get(); 5585 } 5586 } else { 5587 Helpers.assign(ID.size(), {}); 5588 } 5589 if (!IsCorrect) { 5590 // Invalidate all created iterator declarations if error is found. 5591 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5592 if (Decl *ID = D.IteratorDecl) 5593 ID->setInvalidDecl(); 5594 } 5595 return ExprError(); 5596 } 5597 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5598 LLoc, RLoc, ID, Helpers); 5599 } 5600 5601 ExprResult 5602 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5603 Expr *Idx, SourceLocation RLoc) { 5604 Expr *LHSExp = Base; 5605 Expr *RHSExp = Idx; 5606 5607 ExprValueKind VK = VK_LValue; 5608 ExprObjectKind OK = OK_Ordinary; 5609 5610 // Per C++ core issue 1213, the result is an xvalue if either operand is 5611 // a non-lvalue array, and an lvalue otherwise. 5612 if (getLangOpts().CPlusPlus11) { 5613 for (auto *Op : {LHSExp, RHSExp}) { 5614 Op = Op->IgnoreImplicit(); 5615 if (Op->getType()->isArrayType() && !Op->isLValue()) 5616 VK = VK_XValue; 5617 } 5618 } 5619 5620 // Perform default conversions. 5621 if (!LHSExp->getType()->getAs<VectorType>()) { 5622 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5623 if (Result.isInvalid()) 5624 return ExprError(); 5625 LHSExp = Result.get(); 5626 } 5627 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5628 if (Result.isInvalid()) 5629 return ExprError(); 5630 RHSExp = Result.get(); 5631 5632 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5633 5634 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5635 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5636 // in the subscript position. As a result, we need to derive the array base 5637 // and index from the expression types. 5638 Expr *BaseExpr, *IndexExpr; 5639 QualType ResultType; 5640 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5641 BaseExpr = LHSExp; 5642 IndexExpr = RHSExp; 5643 ResultType = 5644 getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext()); 5645 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5646 BaseExpr = LHSExp; 5647 IndexExpr = RHSExp; 5648 ResultType = PTy->getPointeeType(); 5649 } else if (const ObjCObjectPointerType *PTy = 5650 LHSTy->getAs<ObjCObjectPointerType>()) { 5651 BaseExpr = LHSExp; 5652 IndexExpr = RHSExp; 5653 5654 // Use custom logic if this should be the pseudo-object subscript 5655 // expression. 5656 if (!LangOpts.isSubscriptPointerArithmetic()) 5657 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5658 nullptr); 5659 5660 ResultType = PTy->getPointeeType(); 5661 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5662 // Handle the uncommon case of "123[Ptr]". 5663 BaseExpr = RHSExp; 5664 IndexExpr = LHSExp; 5665 ResultType = PTy->getPointeeType(); 5666 } else if (const ObjCObjectPointerType *PTy = 5667 RHSTy->getAs<ObjCObjectPointerType>()) { 5668 // Handle the uncommon case of "123[Ptr]". 5669 BaseExpr = RHSExp; 5670 IndexExpr = LHSExp; 5671 ResultType = PTy->getPointeeType(); 5672 if (!LangOpts.isSubscriptPointerArithmetic()) { 5673 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5674 << ResultType << BaseExpr->getSourceRange(); 5675 return ExprError(); 5676 } 5677 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5678 BaseExpr = LHSExp; // vectors: V[123] 5679 IndexExpr = RHSExp; 5680 // We apply C++ DR1213 to vector subscripting too. 5681 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5682 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5683 if (Materialized.isInvalid()) 5684 return ExprError(); 5685 LHSExp = Materialized.get(); 5686 } 5687 VK = LHSExp->getValueKind(); 5688 if (VK != VK_PRValue) 5689 OK = OK_VectorComponent; 5690 5691 ResultType = VTy->getElementType(); 5692 QualType BaseType = BaseExpr->getType(); 5693 Qualifiers BaseQuals = BaseType.getQualifiers(); 5694 Qualifiers MemberQuals = ResultType.getQualifiers(); 5695 Qualifiers Combined = BaseQuals + MemberQuals; 5696 if (Combined != MemberQuals) 5697 ResultType = Context.getQualifiedType(ResultType, Combined); 5698 } else if (LHSTy->isBuiltinType() && 5699 LHSTy->getAs<BuiltinType>()->isVLSTBuiltinType()) { 5700 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>(); 5701 if (BTy->isSVEBool()) 5702 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t) 5703 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5704 5705 BaseExpr = LHSExp; 5706 IndexExpr = RHSExp; 5707 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5708 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5709 if (Materialized.isInvalid()) 5710 return ExprError(); 5711 LHSExp = Materialized.get(); 5712 } 5713 VK = LHSExp->getValueKind(); 5714 if (VK != VK_PRValue) 5715 OK = OK_VectorComponent; 5716 5717 ResultType = BTy->getSveEltType(Context); 5718 5719 QualType BaseType = BaseExpr->getType(); 5720 Qualifiers BaseQuals = BaseType.getQualifiers(); 5721 Qualifiers MemberQuals = ResultType.getQualifiers(); 5722 Qualifiers Combined = BaseQuals + MemberQuals; 5723 if (Combined != MemberQuals) 5724 ResultType = Context.getQualifiedType(ResultType, Combined); 5725 } else if (LHSTy->isArrayType()) { 5726 // If we see an array that wasn't promoted by 5727 // DefaultFunctionArrayLvalueConversion, it must be an array that 5728 // wasn't promoted because of the C90 rule that doesn't 5729 // allow promoting non-lvalue arrays. Warn, then 5730 // force the promotion here. 5731 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5732 << LHSExp->getSourceRange(); 5733 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5734 CK_ArrayToPointerDecay).get(); 5735 LHSTy = LHSExp->getType(); 5736 5737 BaseExpr = LHSExp; 5738 IndexExpr = RHSExp; 5739 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5740 } else if (RHSTy->isArrayType()) { 5741 // Same as previous, except for 123[f().a] case 5742 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5743 << RHSExp->getSourceRange(); 5744 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5745 CK_ArrayToPointerDecay).get(); 5746 RHSTy = RHSExp->getType(); 5747 5748 BaseExpr = RHSExp; 5749 IndexExpr = LHSExp; 5750 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5751 } else { 5752 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5753 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5754 } 5755 // C99 6.5.2.1p1 5756 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5757 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5758 << IndexExpr->getSourceRange()); 5759 5760 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5761 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5762 && !IndexExpr->isTypeDependent()) 5763 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5764 5765 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5766 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5767 // type. Note that Functions are not objects, and that (in C99 parlance) 5768 // incomplete types are not object types. 5769 if (ResultType->isFunctionType()) { 5770 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5771 << ResultType << BaseExpr->getSourceRange(); 5772 return ExprError(); 5773 } 5774 5775 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5776 // GNU extension: subscripting on pointer to void 5777 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5778 << BaseExpr->getSourceRange(); 5779 5780 // C forbids expressions of unqualified void type from being l-values. 5781 // See IsCForbiddenLValueType. 5782 if (!ResultType.hasQualifiers()) 5783 VK = VK_PRValue; 5784 } else if (!ResultType->isDependentType() && 5785 RequireCompleteSizedType( 5786 LLoc, ResultType, 5787 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5788 return ExprError(); 5789 5790 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 5791 !ResultType.isCForbiddenLValueType()); 5792 5793 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5794 FunctionScopes.size() > 1) { 5795 if (auto *TT = 5796 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5797 for (auto I = FunctionScopes.rbegin(), 5798 E = std::prev(FunctionScopes.rend()); 5799 I != E; ++I) { 5800 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5801 if (CSI == nullptr) 5802 break; 5803 DeclContext *DC = nullptr; 5804 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5805 DC = LSI->CallOperator; 5806 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5807 DC = CRSI->TheCapturedDecl; 5808 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5809 DC = BSI->TheDecl; 5810 if (DC) { 5811 if (DC->containsDecl(TT->getDecl())) 5812 break; 5813 captureVariablyModifiedType( 5814 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5815 } 5816 } 5817 } 5818 } 5819 5820 return new (Context) 5821 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5822 } 5823 5824 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5825 ParmVarDecl *Param) { 5826 if (Param->hasUnparsedDefaultArg()) { 5827 // If we've already cleared out the location for the default argument, 5828 // that means we're parsing it right now. 5829 if (!UnparsedDefaultArgLocs.count(Param)) { 5830 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5831 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5832 Param->setInvalidDecl(); 5833 return true; 5834 } 5835 5836 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5837 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5838 Diag(UnparsedDefaultArgLocs[Param], 5839 diag::note_default_argument_declared_here); 5840 return true; 5841 } 5842 5843 if (Param->hasUninstantiatedDefaultArg() && 5844 InstantiateDefaultArgument(CallLoc, FD, Param)) 5845 return true; 5846 5847 assert(Param->hasInit() && "default argument but no initializer?"); 5848 5849 // If the default expression creates temporaries, we need to 5850 // push them to the current stack of expression temporaries so they'll 5851 // be properly destroyed. 5852 // FIXME: We should really be rebuilding the default argument with new 5853 // bound temporaries; see the comment in PR5810. 5854 // We don't need to do that with block decls, though, because 5855 // blocks in default argument expression can never capture anything. 5856 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5857 // Set the "needs cleanups" bit regardless of whether there are 5858 // any explicit objects. 5859 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5860 5861 // Append all the objects to the cleanup list. Right now, this 5862 // should always be a no-op, because blocks in default argument 5863 // expressions should never be able to capture anything. 5864 assert(!Init->getNumObjects() && 5865 "default argument expression has capturing blocks?"); 5866 } 5867 5868 // We already type-checked the argument, so we know it works. 5869 // Just mark all of the declarations in this potentially-evaluated expression 5870 // as being "referenced". 5871 EnterExpressionEvaluationContext EvalContext( 5872 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5873 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5874 /*SkipLocalVariables=*/true); 5875 return false; 5876 } 5877 5878 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5879 FunctionDecl *FD, ParmVarDecl *Param) { 5880 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5881 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5882 return ExprError(); 5883 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5884 } 5885 5886 Sema::VariadicCallType 5887 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5888 Expr *Fn) { 5889 if (Proto && Proto->isVariadic()) { 5890 if (isa_and_nonnull<CXXConstructorDecl>(FDecl)) 5891 return VariadicConstructor; 5892 else if (Fn && Fn->getType()->isBlockPointerType()) 5893 return VariadicBlock; 5894 else if (FDecl) { 5895 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5896 if (Method->isInstance()) 5897 return VariadicMethod; 5898 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5899 return VariadicMethod; 5900 return VariadicFunction; 5901 } 5902 return VariadicDoesNotApply; 5903 } 5904 5905 namespace { 5906 class FunctionCallCCC final : public FunctionCallFilterCCC { 5907 public: 5908 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5909 unsigned NumArgs, MemberExpr *ME) 5910 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5911 FunctionName(FuncName) {} 5912 5913 bool ValidateCandidate(const TypoCorrection &candidate) override { 5914 if (!candidate.getCorrectionSpecifier() || 5915 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5916 return false; 5917 } 5918 5919 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5920 } 5921 5922 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5923 return std::make_unique<FunctionCallCCC>(*this); 5924 } 5925 5926 private: 5927 const IdentifierInfo *const FunctionName; 5928 }; 5929 } 5930 5931 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5932 FunctionDecl *FDecl, 5933 ArrayRef<Expr *> Args) { 5934 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5935 DeclarationName FuncName = FDecl->getDeclName(); 5936 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5937 5938 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5939 if (TypoCorrection Corrected = S.CorrectTypo( 5940 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5941 S.getScopeForContext(S.CurContext), nullptr, CCC, 5942 Sema::CTK_ErrorRecovery)) { 5943 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5944 if (Corrected.isOverloaded()) { 5945 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5946 OverloadCandidateSet::iterator Best; 5947 for (NamedDecl *CD : Corrected) { 5948 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5949 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5950 OCS); 5951 } 5952 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5953 case OR_Success: 5954 ND = Best->FoundDecl; 5955 Corrected.setCorrectionDecl(ND); 5956 break; 5957 default: 5958 break; 5959 } 5960 } 5961 ND = ND->getUnderlyingDecl(); 5962 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5963 return Corrected; 5964 } 5965 } 5966 return TypoCorrection(); 5967 } 5968 5969 /// ConvertArgumentsForCall - Converts the arguments specified in 5970 /// Args/NumArgs to the parameter types of the function FDecl with 5971 /// function prototype Proto. Call is the call expression itself, and 5972 /// Fn is the function expression. For a C++ member function, this 5973 /// routine does not attempt to convert the object argument. Returns 5974 /// true if the call is ill-formed. 5975 bool 5976 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5977 FunctionDecl *FDecl, 5978 const FunctionProtoType *Proto, 5979 ArrayRef<Expr *> Args, 5980 SourceLocation RParenLoc, 5981 bool IsExecConfig) { 5982 // Bail out early if calling a builtin with custom typechecking. 5983 if (FDecl) 5984 if (unsigned ID = FDecl->getBuiltinID()) 5985 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5986 return false; 5987 5988 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5989 // assignment, to the types of the corresponding parameter, ... 5990 unsigned NumParams = Proto->getNumParams(); 5991 bool Invalid = false; 5992 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5993 unsigned FnKind = Fn->getType()->isBlockPointerType() 5994 ? 1 /* block */ 5995 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5996 : 0 /* function */); 5997 5998 // If too few arguments are available (and we don't have default 5999 // arguments for the remaining parameters), don't make the call. 6000 if (Args.size() < NumParams) { 6001 if (Args.size() < MinArgs) { 6002 TypoCorrection TC; 6003 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 6004 unsigned diag_id = 6005 MinArgs == NumParams && !Proto->isVariadic() 6006 ? diag::err_typecheck_call_too_few_args_suggest 6007 : diag::err_typecheck_call_too_few_args_at_least_suggest; 6008 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 6009 << static_cast<unsigned>(Args.size()) 6010 << TC.getCorrectionRange()); 6011 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 6012 Diag(RParenLoc, 6013 MinArgs == NumParams && !Proto->isVariadic() 6014 ? diag::err_typecheck_call_too_few_args_one 6015 : diag::err_typecheck_call_too_few_args_at_least_one) 6016 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 6017 else 6018 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 6019 ? diag::err_typecheck_call_too_few_args 6020 : diag::err_typecheck_call_too_few_args_at_least) 6021 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 6022 << Fn->getSourceRange(); 6023 6024 // Emit the location of the prototype. 6025 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 6026 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6027 6028 return true; 6029 } 6030 // We reserve space for the default arguments when we create 6031 // the call expression, before calling ConvertArgumentsForCall. 6032 assert((Call->getNumArgs() == NumParams) && 6033 "We should have reserved space for the default arguments before!"); 6034 } 6035 6036 // If too many are passed and not variadic, error on the extras and drop 6037 // them. 6038 if (Args.size() > NumParams) { 6039 if (!Proto->isVariadic()) { 6040 TypoCorrection TC; 6041 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 6042 unsigned diag_id = 6043 MinArgs == NumParams && !Proto->isVariadic() 6044 ? diag::err_typecheck_call_too_many_args_suggest 6045 : diag::err_typecheck_call_too_many_args_at_most_suggest; 6046 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 6047 << static_cast<unsigned>(Args.size()) 6048 << TC.getCorrectionRange()); 6049 } else if (NumParams == 1 && FDecl && 6050 FDecl->getParamDecl(0)->getDeclName()) 6051 Diag(Args[NumParams]->getBeginLoc(), 6052 MinArgs == NumParams 6053 ? diag::err_typecheck_call_too_many_args_one 6054 : diag::err_typecheck_call_too_many_args_at_most_one) 6055 << FnKind << FDecl->getParamDecl(0) 6056 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 6057 << SourceRange(Args[NumParams]->getBeginLoc(), 6058 Args.back()->getEndLoc()); 6059 else 6060 Diag(Args[NumParams]->getBeginLoc(), 6061 MinArgs == NumParams 6062 ? diag::err_typecheck_call_too_many_args 6063 : diag::err_typecheck_call_too_many_args_at_most) 6064 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 6065 << Fn->getSourceRange() 6066 << SourceRange(Args[NumParams]->getBeginLoc(), 6067 Args.back()->getEndLoc()); 6068 6069 // Emit the location of the prototype. 6070 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 6071 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6072 6073 // This deletes the extra arguments. 6074 Call->shrinkNumArgs(NumParams); 6075 return true; 6076 } 6077 } 6078 SmallVector<Expr *, 8> AllArgs; 6079 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 6080 6081 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 6082 AllArgs, CallType); 6083 if (Invalid) 6084 return true; 6085 unsigned TotalNumArgs = AllArgs.size(); 6086 for (unsigned i = 0; i < TotalNumArgs; ++i) 6087 Call->setArg(i, AllArgs[i]); 6088 6089 Call->computeDependence(); 6090 return false; 6091 } 6092 6093 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 6094 const FunctionProtoType *Proto, 6095 unsigned FirstParam, ArrayRef<Expr *> Args, 6096 SmallVectorImpl<Expr *> &AllArgs, 6097 VariadicCallType CallType, bool AllowExplicit, 6098 bool IsListInitialization) { 6099 unsigned NumParams = Proto->getNumParams(); 6100 bool Invalid = false; 6101 size_t ArgIx = 0; 6102 // Continue to check argument types (even if we have too few/many args). 6103 for (unsigned i = FirstParam; i < NumParams; i++) { 6104 QualType ProtoArgType = Proto->getParamType(i); 6105 6106 Expr *Arg; 6107 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 6108 if (ArgIx < Args.size()) { 6109 Arg = Args[ArgIx++]; 6110 6111 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 6112 diag::err_call_incomplete_argument, Arg)) 6113 return true; 6114 6115 // Strip the unbridged-cast placeholder expression off, if applicable. 6116 bool CFAudited = false; 6117 if (Arg->getType() == Context.ARCUnbridgedCastTy && 6118 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 6119 (!Param || !Param->hasAttr<CFConsumedAttr>())) 6120 Arg = stripARCUnbridgedCast(Arg); 6121 else if (getLangOpts().ObjCAutoRefCount && 6122 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 6123 (!Param || !Param->hasAttr<CFConsumedAttr>())) 6124 CFAudited = true; 6125 6126 if (Proto->getExtParameterInfo(i).isNoEscape() && 6127 ProtoArgType->isBlockPointerType()) 6128 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 6129 BE->getBlockDecl()->setDoesNotEscape(); 6130 6131 InitializedEntity Entity = 6132 Param ? InitializedEntity::InitializeParameter(Context, Param, 6133 ProtoArgType) 6134 : InitializedEntity::InitializeParameter( 6135 Context, ProtoArgType, Proto->isParamConsumed(i)); 6136 6137 // Remember that parameter belongs to a CF audited API. 6138 if (CFAudited) 6139 Entity.setParameterCFAudited(); 6140 6141 ExprResult ArgE = PerformCopyInitialization( 6142 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 6143 if (ArgE.isInvalid()) 6144 return true; 6145 6146 Arg = ArgE.getAs<Expr>(); 6147 } else { 6148 assert(Param && "can't use default arguments without a known callee"); 6149 6150 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 6151 if (ArgExpr.isInvalid()) 6152 return true; 6153 6154 Arg = ArgExpr.getAs<Expr>(); 6155 } 6156 6157 // Check for array bounds violations for each argument to the call. This 6158 // check only triggers warnings when the argument isn't a more complex Expr 6159 // with its own checking, such as a BinaryOperator. 6160 CheckArrayAccess(Arg); 6161 6162 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 6163 CheckStaticArrayArgument(CallLoc, Param, Arg); 6164 6165 AllArgs.push_back(Arg); 6166 } 6167 6168 // If this is a variadic call, handle args passed through "...". 6169 if (CallType != VariadicDoesNotApply) { 6170 // Assume that extern "C" functions with variadic arguments that 6171 // return __unknown_anytype aren't *really* variadic. 6172 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 6173 FDecl->isExternC()) { 6174 for (Expr *A : Args.slice(ArgIx)) { 6175 QualType paramType; // ignored 6176 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 6177 Invalid |= arg.isInvalid(); 6178 AllArgs.push_back(arg.get()); 6179 } 6180 6181 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6182 } else { 6183 for (Expr *A : Args.slice(ArgIx)) { 6184 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6185 Invalid |= Arg.isInvalid(); 6186 AllArgs.push_back(Arg.get()); 6187 } 6188 } 6189 6190 // Check for array bounds violations. 6191 for (Expr *A : Args.slice(ArgIx)) 6192 CheckArrayAccess(A); 6193 } 6194 return Invalid; 6195 } 6196 6197 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6198 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6199 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6200 TL = DTL.getOriginalLoc(); 6201 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6202 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6203 << ATL.getLocalSourceRange(); 6204 } 6205 6206 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6207 /// array parameter, check that it is non-null, and that if it is formed by 6208 /// array-to-pointer decay, the underlying array is sufficiently large. 6209 /// 6210 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6211 /// array type derivation, then for each call to the function, the value of the 6212 /// corresponding actual argument shall provide access to the first element of 6213 /// an array with at least as many elements as specified by the size expression. 6214 void 6215 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6216 ParmVarDecl *Param, 6217 const Expr *ArgExpr) { 6218 // Static array parameters are not supported in C++. 6219 if (!Param || getLangOpts().CPlusPlus) 6220 return; 6221 6222 QualType OrigTy = Param->getOriginalType(); 6223 6224 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6225 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6226 return; 6227 6228 if (ArgExpr->isNullPointerConstant(Context, 6229 Expr::NPC_NeverValueDependent)) { 6230 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6231 DiagnoseCalleeStaticArrayParam(*this, Param); 6232 return; 6233 } 6234 6235 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6236 if (!CAT) 6237 return; 6238 6239 const ConstantArrayType *ArgCAT = 6240 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6241 if (!ArgCAT) 6242 return; 6243 6244 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6245 ArgCAT->getElementType())) { 6246 if (ArgCAT->getSize().ult(CAT->getSize())) { 6247 Diag(CallLoc, diag::warn_static_array_too_small) 6248 << ArgExpr->getSourceRange() 6249 << (unsigned)ArgCAT->getSize().getZExtValue() 6250 << (unsigned)CAT->getSize().getZExtValue() << 0; 6251 DiagnoseCalleeStaticArrayParam(*this, Param); 6252 } 6253 return; 6254 } 6255 6256 Optional<CharUnits> ArgSize = 6257 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6258 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6259 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6260 Diag(CallLoc, diag::warn_static_array_too_small) 6261 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6262 << (unsigned)ParmSize->getQuantity() << 1; 6263 DiagnoseCalleeStaticArrayParam(*this, Param); 6264 } 6265 } 6266 6267 /// Given a function expression of unknown-any type, try to rebuild it 6268 /// to have a function type. 6269 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6270 6271 /// Is the given type a placeholder that we need to lower out 6272 /// immediately during argument processing? 6273 static bool isPlaceholderToRemoveAsArg(QualType type) { 6274 // Placeholders are never sugared. 6275 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6276 if (!placeholder) return false; 6277 6278 switch (placeholder->getKind()) { 6279 // Ignore all the non-placeholder types. 6280 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6281 case BuiltinType::Id: 6282 #include "clang/Basic/OpenCLImageTypes.def" 6283 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6284 case BuiltinType::Id: 6285 #include "clang/Basic/OpenCLExtensionTypes.def" 6286 // In practice we'll never use this, since all SVE types are sugared 6287 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6288 #define SVE_TYPE(Name, Id, SingletonId) \ 6289 case BuiltinType::Id: 6290 #include "clang/Basic/AArch64SVEACLETypes.def" 6291 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6292 case BuiltinType::Id: 6293 #include "clang/Basic/PPCTypes.def" 6294 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6295 #include "clang/Basic/RISCVVTypes.def" 6296 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6297 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6298 #include "clang/AST/BuiltinTypes.def" 6299 return false; 6300 6301 // We cannot lower out overload sets; they might validly be resolved 6302 // by the call machinery. 6303 case BuiltinType::Overload: 6304 return false; 6305 6306 // Unbridged casts in ARC can be handled in some call positions and 6307 // should be left in place. 6308 case BuiltinType::ARCUnbridgedCast: 6309 return false; 6310 6311 // Pseudo-objects should be converted as soon as possible. 6312 case BuiltinType::PseudoObject: 6313 return true; 6314 6315 // The debugger mode could theoretically but currently does not try 6316 // to resolve unknown-typed arguments based on known parameter types. 6317 case BuiltinType::UnknownAny: 6318 return true; 6319 6320 // These are always invalid as call arguments and should be reported. 6321 case BuiltinType::BoundMember: 6322 case BuiltinType::BuiltinFn: 6323 case BuiltinType::IncompleteMatrixIdx: 6324 case BuiltinType::OMPArraySection: 6325 case BuiltinType::OMPArrayShaping: 6326 case BuiltinType::OMPIterator: 6327 return true; 6328 6329 } 6330 llvm_unreachable("bad builtin type kind"); 6331 } 6332 6333 /// Check an argument list for placeholders that we won't try to 6334 /// handle later. 6335 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6336 // Apply this processing to all the arguments at once instead of 6337 // dying at the first failure. 6338 bool hasInvalid = false; 6339 for (size_t i = 0, e = args.size(); i != e; i++) { 6340 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6341 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6342 if (result.isInvalid()) hasInvalid = true; 6343 else args[i] = result.get(); 6344 } 6345 } 6346 return hasInvalid; 6347 } 6348 6349 /// If a builtin function has a pointer argument with no explicit address 6350 /// space, then it should be able to accept a pointer to any address 6351 /// space as input. In order to do this, we need to replace the 6352 /// standard builtin declaration with one that uses the same address space 6353 /// as the call. 6354 /// 6355 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6356 /// it does not contain any pointer arguments without 6357 /// an address space qualifer. Otherwise the rewritten 6358 /// FunctionDecl is returned. 6359 /// TODO: Handle pointer return types. 6360 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6361 FunctionDecl *FDecl, 6362 MultiExprArg ArgExprs) { 6363 6364 QualType DeclType = FDecl->getType(); 6365 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6366 6367 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6368 ArgExprs.size() < FT->getNumParams()) 6369 return nullptr; 6370 6371 bool NeedsNewDecl = false; 6372 unsigned i = 0; 6373 SmallVector<QualType, 8> OverloadParams; 6374 6375 for (QualType ParamType : FT->param_types()) { 6376 6377 // Convert array arguments to pointer to simplify type lookup. 6378 ExprResult ArgRes = 6379 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6380 if (ArgRes.isInvalid()) 6381 return nullptr; 6382 Expr *Arg = ArgRes.get(); 6383 QualType ArgType = Arg->getType(); 6384 if (!ParamType->isPointerType() || 6385 ParamType.hasAddressSpace() || 6386 !ArgType->isPointerType() || 6387 !ArgType->getPointeeType().hasAddressSpace()) { 6388 OverloadParams.push_back(ParamType); 6389 continue; 6390 } 6391 6392 QualType PointeeType = ParamType->getPointeeType(); 6393 if (PointeeType.hasAddressSpace()) 6394 continue; 6395 6396 NeedsNewDecl = true; 6397 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6398 6399 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6400 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6401 } 6402 6403 if (!NeedsNewDecl) 6404 return nullptr; 6405 6406 FunctionProtoType::ExtProtoInfo EPI; 6407 EPI.Variadic = FT->isVariadic(); 6408 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6409 OverloadParams, EPI); 6410 DeclContext *Parent = FDecl->getParent(); 6411 FunctionDecl *OverloadDecl = FunctionDecl::Create( 6412 Context, Parent, FDecl->getLocation(), FDecl->getLocation(), 6413 FDecl->getIdentifier(), OverloadTy, 6414 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), 6415 false, 6416 /*hasPrototype=*/true); 6417 SmallVector<ParmVarDecl*, 16> Params; 6418 FT = cast<FunctionProtoType>(OverloadTy); 6419 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6420 QualType ParamType = FT->getParamType(i); 6421 ParmVarDecl *Parm = 6422 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6423 SourceLocation(), nullptr, ParamType, 6424 /*TInfo=*/nullptr, SC_None, nullptr); 6425 Parm->setScopeInfo(0, i); 6426 Params.push_back(Parm); 6427 } 6428 OverloadDecl->setParams(Params); 6429 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6430 return OverloadDecl; 6431 } 6432 6433 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6434 FunctionDecl *Callee, 6435 MultiExprArg ArgExprs) { 6436 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6437 // similar attributes) really don't like it when functions are called with an 6438 // invalid number of args. 6439 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6440 /*PartialOverloading=*/false) && 6441 !Callee->isVariadic()) 6442 return; 6443 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6444 return; 6445 6446 if (const EnableIfAttr *Attr = 6447 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6448 S.Diag(Fn->getBeginLoc(), 6449 isa<CXXMethodDecl>(Callee) 6450 ? diag::err_ovl_no_viable_member_function_in_call 6451 : diag::err_ovl_no_viable_function_in_call) 6452 << Callee << Callee->getSourceRange(); 6453 S.Diag(Callee->getLocation(), 6454 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6455 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6456 return; 6457 } 6458 } 6459 6460 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6461 const UnresolvedMemberExpr *const UME, Sema &S) { 6462 6463 const auto GetFunctionLevelDCIfCXXClass = 6464 [](Sema &S) -> const CXXRecordDecl * { 6465 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6466 if (!DC || !DC->getParent()) 6467 return nullptr; 6468 6469 // If the call to some member function was made from within a member 6470 // function body 'M' return return 'M's parent. 6471 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6472 return MD->getParent()->getCanonicalDecl(); 6473 // else the call was made from within a default member initializer of a 6474 // class, so return the class. 6475 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6476 return RD->getCanonicalDecl(); 6477 return nullptr; 6478 }; 6479 // If our DeclContext is neither a member function nor a class (in the 6480 // case of a lambda in a default member initializer), we can't have an 6481 // enclosing 'this'. 6482 6483 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6484 if (!CurParentClass) 6485 return false; 6486 6487 // The naming class for implicit member functions call is the class in which 6488 // name lookup starts. 6489 const CXXRecordDecl *const NamingClass = 6490 UME->getNamingClass()->getCanonicalDecl(); 6491 assert(NamingClass && "Must have naming class even for implicit access"); 6492 6493 // If the unresolved member functions were found in a 'naming class' that is 6494 // related (either the same or derived from) to the class that contains the 6495 // member function that itself contained the implicit member access. 6496 6497 return CurParentClass == NamingClass || 6498 CurParentClass->isDerivedFrom(NamingClass); 6499 } 6500 6501 static void 6502 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6503 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6504 6505 if (!UME) 6506 return; 6507 6508 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6509 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6510 // already been captured, or if this is an implicit member function call (if 6511 // it isn't, an attempt to capture 'this' should already have been made). 6512 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6513 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6514 return; 6515 6516 // Check if the naming class in which the unresolved members were found is 6517 // related (same as or is a base of) to the enclosing class. 6518 6519 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6520 return; 6521 6522 6523 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6524 // If the enclosing function is not dependent, then this lambda is 6525 // capture ready, so if we can capture this, do so. 6526 if (!EnclosingFunctionCtx->isDependentContext()) { 6527 // If the current lambda and all enclosing lambdas can capture 'this' - 6528 // then go ahead and capture 'this' (since our unresolved overload set 6529 // contains at least one non-static member function). 6530 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6531 S.CheckCXXThisCapture(CallLoc); 6532 } else if (S.CurContext->isDependentContext()) { 6533 // ... since this is an implicit member reference, that might potentially 6534 // involve a 'this' capture, mark 'this' for potential capture in 6535 // enclosing lambdas. 6536 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6537 CurLSI->addPotentialThisCapture(CallLoc); 6538 } 6539 } 6540 6541 // Once a call is fully resolved, warn for unqualified calls to specific 6542 // C++ standard functions, like move and forward. 6543 static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) { 6544 // We are only checking unary move and forward so exit early here. 6545 if (Call->getNumArgs() != 1) 6546 return; 6547 6548 Expr *E = Call->getCallee()->IgnoreParenImpCasts(); 6549 if (!E || isa<UnresolvedLookupExpr>(E)) 6550 return; 6551 DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E); 6552 if (!DRE || !DRE->getLocation().isValid()) 6553 return; 6554 6555 if (DRE->getQualifier()) 6556 return; 6557 6558 const FunctionDecl *FD = Call->getDirectCallee(); 6559 if (!FD) 6560 return; 6561 6562 // Only warn for some functions deemed more frequent or problematic. 6563 unsigned BuiltinID = FD->getBuiltinID(); 6564 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward) 6565 return; 6566 6567 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function) 6568 << FD->getQualifiedNameAsString() 6569 << FixItHint::CreateInsertion(DRE->getLocation(), "std::"); 6570 } 6571 6572 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6573 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6574 Expr *ExecConfig) { 6575 ExprResult Call = 6576 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6577 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6578 if (Call.isInvalid()) 6579 return Call; 6580 6581 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6582 // language modes. 6583 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6584 if (ULE->hasExplicitTemplateArgs() && 6585 ULE->decls_begin() == ULE->decls_end()) { 6586 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6587 ? diag::warn_cxx17_compat_adl_only_template_id 6588 : diag::ext_adl_only_template_id) 6589 << ULE->getName(); 6590 } 6591 } 6592 6593 if (LangOpts.OpenMP) 6594 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6595 ExecConfig); 6596 if (LangOpts.CPlusPlus) { 6597 CallExpr *CE = dyn_cast<CallExpr>(Call.get()); 6598 if (CE) 6599 DiagnosedUnqualifiedCallsToStdFunctions(*this, CE); 6600 } 6601 return Call; 6602 } 6603 6604 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6605 /// This provides the location of the left/right parens and a list of comma 6606 /// locations. 6607 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6608 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6609 Expr *ExecConfig, bool IsExecConfig, 6610 bool AllowRecovery) { 6611 // Since this might be a postfix expression, get rid of ParenListExprs. 6612 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6613 if (Result.isInvalid()) return ExprError(); 6614 Fn = Result.get(); 6615 6616 if (checkArgsForPlaceholders(*this, ArgExprs)) 6617 return ExprError(); 6618 6619 if (getLangOpts().CPlusPlus) { 6620 // If this is a pseudo-destructor expression, build the call immediately. 6621 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6622 if (!ArgExprs.empty()) { 6623 // Pseudo-destructor calls should not have any arguments. 6624 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6625 << FixItHint::CreateRemoval( 6626 SourceRange(ArgExprs.front()->getBeginLoc(), 6627 ArgExprs.back()->getEndLoc())); 6628 } 6629 6630 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6631 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6632 } 6633 if (Fn->getType() == Context.PseudoObjectTy) { 6634 ExprResult result = CheckPlaceholderExpr(Fn); 6635 if (result.isInvalid()) return ExprError(); 6636 Fn = result.get(); 6637 } 6638 6639 // Determine whether this is a dependent call inside a C++ template, 6640 // in which case we won't do any semantic analysis now. 6641 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6642 if (ExecConfig) { 6643 return CUDAKernelCallExpr::Create(Context, Fn, 6644 cast<CallExpr>(ExecConfig), ArgExprs, 6645 Context.DependentTy, VK_PRValue, 6646 RParenLoc, CurFPFeatureOverrides()); 6647 } else { 6648 6649 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6650 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6651 Fn->getBeginLoc()); 6652 6653 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6654 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6655 } 6656 } 6657 6658 // Determine whether this is a call to an object (C++ [over.call.object]). 6659 if (Fn->getType()->isRecordType()) 6660 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6661 RParenLoc); 6662 6663 if (Fn->getType() == Context.UnknownAnyTy) { 6664 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6665 if (result.isInvalid()) return ExprError(); 6666 Fn = result.get(); 6667 } 6668 6669 if (Fn->getType() == Context.BoundMemberTy) { 6670 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6671 RParenLoc, ExecConfig, IsExecConfig, 6672 AllowRecovery); 6673 } 6674 } 6675 6676 // Check for overloaded calls. This can happen even in C due to extensions. 6677 if (Fn->getType() == Context.OverloadTy) { 6678 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6679 6680 // We aren't supposed to apply this logic if there's an '&' involved. 6681 if (!find.HasFormOfMemberPointer) { 6682 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6683 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6684 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6685 OverloadExpr *ovl = find.Expression; 6686 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6687 return BuildOverloadedCallExpr( 6688 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6689 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6690 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6691 RParenLoc, ExecConfig, IsExecConfig, 6692 AllowRecovery); 6693 } 6694 } 6695 6696 // If we're directly calling a function, get the appropriate declaration. 6697 if (Fn->getType() == Context.UnknownAnyTy) { 6698 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6699 if (result.isInvalid()) return ExprError(); 6700 Fn = result.get(); 6701 } 6702 6703 Expr *NakedFn = Fn->IgnoreParens(); 6704 6705 bool CallingNDeclIndirectly = false; 6706 NamedDecl *NDecl = nullptr; 6707 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6708 if (UnOp->getOpcode() == UO_AddrOf) { 6709 CallingNDeclIndirectly = true; 6710 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6711 } 6712 } 6713 6714 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6715 NDecl = DRE->getDecl(); 6716 6717 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6718 if (FDecl && FDecl->getBuiltinID()) { 6719 // Rewrite the function decl for this builtin by replacing parameters 6720 // with no explicit address space with the address space of the arguments 6721 // in ArgExprs. 6722 if ((FDecl = 6723 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6724 NDecl = FDecl; 6725 Fn = DeclRefExpr::Create( 6726 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6727 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6728 nullptr, DRE->isNonOdrUse()); 6729 } 6730 } 6731 } else if (isa<MemberExpr>(NakedFn)) 6732 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6733 6734 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6735 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6736 FD, /*Complain=*/true, Fn->getBeginLoc())) 6737 return ExprError(); 6738 6739 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6740 6741 // If this expression is a call to a builtin function in HIP device 6742 // compilation, allow a pointer-type argument to default address space to be 6743 // passed as a pointer-type parameter to a non-default address space. 6744 // If Arg is declared in the default address space and Param is declared 6745 // in a non-default address space, perform an implicit address space cast to 6746 // the parameter type. 6747 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && 6748 FD->getBuiltinID()) { 6749 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) { 6750 ParmVarDecl *Param = FD->getParamDecl(Idx); 6751 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || 6752 !ArgExprs[Idx]->getType()->isPointerType()) 6753 continue; 6754 6755 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); 6756 auto ArgTy = ArgExprs[Idx]->getType(); 6757 auto ArgPtTy = ArgTy->getPointeeType(); 6758 auto ArgAS = ArgPtTy.getAddressSpace(); 6759 6760 // Add address space cast if target address spaces are different 6761 bool NeedImplicitASC = 6762 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling. 6763 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS 6764 // or from specific AS which has target AS matching that of Param. 6765 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS)); 6766 if (!NeedImplicitASC) 6767 continue; 6768 6769 // First, ensure that the Arg is an RValue. 6770 if (ArgExprs[Idx]->isGLValue()) { 6771 ArgExprs[Idx] = ImplicitCastExpr::Create( 6772 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx], 6773 nullptr, VK_PRValue, FPOptionsOverride()); 6774 } 6775 6776 // Construct a new arg type with address space of Param 6777 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); 6778 ArgPtQuals.setAddressSpace(ParamAS); 6779 auto NewArgPtTy = 6780 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); 6781 auto NewArgTy = 6782 Context.getQualifiedType(Context.getPointerType(NewArgPtTy), 6783 ArgTy.getQualifiers()); 6784 6785 // Finally perform an implicit address space cast 6786 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, 6787 CK_AddressSpaceConversion) 6788 .get(); 6789 } 6790 } 6791 } 6792 6793 if (Context.isDependenceAllowed() && 6794 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6795 assert(!getLangOpts().CPlusPlus); 6796 assert((Fn->containsErrors() || 6797 llvm::any_of(ArgExprs, 6798 [](clang::Expr *E) { return E->containsErrors(); })) && 6799 "should only occur in error-recovery path."); 6800 QualType ReturnType = 6801 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6802 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6803 : Context.DependentTy; 6804 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6805 Expr::getValueKindForType(ReturnType), RParenLoc, 6806 CurFPFeatureOverrides()); 6807 } 6808 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6809 ExecConfig, IsExecConfig); 6810 } 6811 6812 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id 6813 // with the specified CallArgs 6814 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 6815 MultiExprArg CallArgs) { 6816 StringRef Name = Context.BuiltinInfo.getName(Id); 6817 LookupResult R(*this, &Context.Idents.get(Name), Loc, 6818 Sema::LookupOrdinaryName); 6819 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); 6820 6821 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); 6822 assert(BuiltInDecl && "failed to find builtin declaration"); 6823 6824 ExprResult DeclRef = 6825 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); 6826 assert(DeclRef.isUsable() && "Builtin reference cannot fail"); 6827 6828 ExprResult Call = 6829 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); 6830 6831 assert(!Call.isInvalid() && "Call to builtin cannot fail!"); 6832 return Call.get(); 6833 } 6834 6835 /// Parse a __builtin_astype expression. 6836 /// 6837 /// __builtin_astype( value, dst type ) 6838 /// 6839 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6840 SourceLocation BuiltinLoc, 6841 SourceLocation RParenLoc) { 6842 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6843 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6844 } 6845 6846 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6847 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6848 SourceLocation BuiltinLoc, 6849 SourceLocation RParenLoc) { 6850 ExprValueKind VK = VK_PRValue; 6851 ExprObjectKind OK = OK_Ordinary; 6852 QualType SrcTy = E->getType(); 6853 if (!SrcTy->isDependentType() && 6854 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6855 return ExprError( 6856 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6857 << DestTy << SrcTy << E->getSourceRange()); 6858 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6859 } 6860 6861 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6862 /// provided arguments. 6863 /// 6864 /// __builtin_convertvector( value, dst type ) 6865 /// 6866 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6867 SourceLocation BuiltinLoc, 6868 SourceLocation RParenLoc) { 6869 TypeSourceInfo *TInfo; 6870 GetTypeFromParser(ParsedDestTy, &TInfo); 6871 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6872 } 6873 6874 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6875 /// i.e. an expression not of \p OverloadTy. The expression should 6876 /// unary-convert to an expression of function-pointer or 6877 /// block-pointer type. 6878 /// 6879 /// \param NDecl the declaration being called, if available 6880 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6881 SourceLocation LParenLoc, 6882 ArrayRef<Expr *> Args, 6883 SourceLocation RParenLoc, Expr *Config, 6884 bool IsExecConfig, ADLCallKind UsesADL) { 6885 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6886 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6887 6888 // Functions with 'interrupt' attribute cannot be called directly. 6889 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6890 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6891 return ExprError(); 6892 } 6893 6894 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6895 // so there's some risk when calling out to non-interrupt handler functions 6896 // that the callee might not preserve them. This is easy to diagnose here, 6897 // but can be very challenging to debug. 6898 // Likewise, X86 interrupt handlers may only call routines with attribute 6899 // no_caller_saved_registers since there is no efficient way to 6900 // save and restore the non-GPR state. 6901 if (auto *Caller = getCurFunctionDecl()) { 6902 if (Caller->hasAttr<ARMInterruptAttr>()) { 6903 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6904 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6905 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6906 if (FDecl) 6907 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6908 } 6909 } 6910 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6911 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6912 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6913 if (FDecl) 6914 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6915 } 6916 } 6917 6918 // Promote the function operand. 6919 // We special-case function promotion here because we only allow promoting 6920 // builtin functions to function pointers in the callee of a call. 6921 ExprResult Result; 6922 QualType ResultTy; 6923 if (BuiltinID && 6924 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6925 // Extract the return type from the (builtin) function pointer type. 6926 // FIXME Several builtins still have setType in 6927 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6928 // Builtins.def to ensure they are correct before removing setType calls. 6929 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6930 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6931 ResultTy = FDecl->getCallResultType(); 6932 } else { 6933 Result = CallExprUnaryConversions(Fn); 6934 ResultTy = Context.BoolTy; 6935 } 6936 if (Result.isInvalid()) 6937 return ExprError(); 6938 Fn = Result.get(); 6939 6940 // Check for a valid function type, but only if it is not a builtin which 6941 // requires custom type checking. These will be handled by 6942 // CheckBuiltinFunctionCall below just after creation of the call expression. 6943 const FunctionType *FuncT = nullptr; 6944 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6945 retry: 6946 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6947 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6948 // have type pointer to function". 6949 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6950 if (!FuncT) 6951 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6952 << Fn->getType() << Fn->getSourceRange()); 6953 } else if (const BlockPointerType *BPT = 6954 Fn->getType()->getAs<BlockPointerType>()) { 6955 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6956 } else { 6957 // Handle calls to expressions of unknown-any type. 6958 if (Fn->getType() == Context.UnknownAnyTy) { 6959 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6960 if (rewrite.isInvalid()) 6961 return ExprError(); 6962 Fn = rewrite.get(); 6963 goto retry; 6964 } 6965 6966 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6967 << Fn->getType() << Fn->getSourceRange()); 6968 } 6969 } 6970 6971 // Get the number of parameters in the function prototype, if any. 6972 // We will allocate space for max(Args.size(), NumParams) arguments 6973 // in the call expression. 6974 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6975 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6976 6977 CallExpr *TheCall; 6978 if (Config) { 6979 assert(UsesADL == ADLCallKind::NotADL && 6980 "CUDAKernelCallExpr should not use ADL"); 6981 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6982 Args, ResultTy, VK_PRValue, RParenLoc, 6983 CurFPFeatureOverrides(), NumParams); 6984 } else { 6985 TheCall = 6986 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6987 CurFPFeatureOverrides(), NumParams, UsesADL); 6988 } 6989 6990 if (!Context.isDependenceAllowed()) { 6991 // Forget about the nulled arguments since typo correction 6992 // do not handle them well. 6993 TheCall->shrinkNumArgs(Args.size()); 6994 // C cannot always handle TypoExpr nodes in builtin calls and direct 6995 // function calls as their argument checking don't necessarily handle 6996 // dependent types properly, so make sure any TypoExprs have been 6997 // dealt with. 6998 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6999 if (!Result.isUsable()) return ExprError(); 7000 CallExpr *TheOldCall = TheCall; 7001 TheCall = dyn_cast<CallExpr>(Result.get()); 7002 bool CorrectedTypos = TheCall != TheOldCall; 7003 if (!TheCall) return Result; 7004 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 7005 7006 // A new call expression node was created if some typos were corrected. 7007 // However it may not have been constructed with enough storage. In this 7008 // case, rebuild the node with enough storage. The waste of space is 7009 // immaterial since this only happens when some typos were corrected. 7010 if (CorrectedTypos && Args.size() < NumParams) { 7011 if (Config) 7012 TheCall = CUDAKernelCallExpr::Create( 7013 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 7014 RParenLoc, CurFPFeatureOverrides(), NumParams); 7015 else 7016 TheCall = 7017 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 7018 CurFPFeatureOverrides(), NumParams, UsesADL); 7019 } 7020 // We can now handle the nulled arguments for the default arguments. 7021 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 7022 } 7023 7024 // Bail out early if calling a builtin with custom type checking. 7025 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 7026 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 7027 7028 if (getLangOpts().CUDA) { 7029 if (Config) { 7030 // CUDA: Kernel calls must be to global functions 7031 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 7032 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 7033 << FDecl << Fn->getSourceRange()); 7034 7035 // CUDA: Kernel function must have 'void' return type 7036 if (!FuncT->getReturnType()->isVoidType() && 7037 !FuncT->getReturnType()->getAs<AutoType>() && 7038 !FuncT->getReturnType()->isInstantiationDependentType()) 7039 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 7040 << Fn->getType() << Fn->getSourceRange()); 7041 } else { 7042 // CUDA: Calls to global functions must be configured 7043 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 7044 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 7045 << FDecl << Fn->getSourceRange()); 7046 } 7047 } 7048 7049 // Check for a valid return type 7050 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 7051 FDecl)) 7052 return ExprError(); 7053 7054 // We know the result type of the call, set it. 7055 TheCall->setType(FuncT->getCallResultType(Context)); 7056 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 7057 7058 if (Proto) { 7059 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 7060 IsExecConfig)) 7061 return ExprError(); 7062 } else { 7063 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 7064 7065 if (FDecl) { 7066 // Check if we have too few/too many template arguments, based 7067 // on our knowledge of the function definition. 7068 const FunctionDecl *Def = nullptr; 7069 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 7070 Proto = Def->getType()->getAs<FunctionProtoType>(); 7071 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 7072 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 7073 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 7074 } 7075 7076 // If the function we're calling isn't a function prototype, but we have 7077 // a function prototype from a prior declaratiom, use that prototype. 7078 if (!FDecl->hasPrototype()) 7079 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 7080 } 7081 7082 // If we still haven't found a prototype to use but there are arguments to 7083 // the call, diagnose this as calling a function without a prototype. 7084 // However, if we found a function declaration, check to see if 7085 // -Wdeprecated-non-prototype was disabled where the function was declared. 7086 // If so, we will silence the diagnostic here on the assumption that this 7087 // interface is intentional and the user knows what they're doing. We will 7088 // also silence the diagnostic if there is a function declaration but it 7089 // was implicitly defined (the user already gets diagnostics about the 7090 // creation of the implicit function declaration, so the additional warning 7091 // is not helpful). 7092 if (!Proto && !Args.empty() && 7093 (!FDecl || (!FDecl->isImplicit() && 7094 !Diags.isIgnored(diag::warn_strict_uses_without_prototype, 7095 FDecl->getLocation())))) 7096 Diag(LParenLoc, diag::warn_strict_uses_without_prototype) 7097 << (FDecl != nullptr) << FDecl; 7098 7099 // Promote the arguments (C99 6.5.2.2p6). 7100 for (unsigned i = 0, e = Args.size(); i != e; i++) { 7101 Expr *Arg = Args[i]; 7102 7103 if (Proto && i < Proto->getNumParams()) { 7104 InitializedEntity Entity = InitializedEntity::InitializeParameter( 7105 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 7106 ExprResult ArgE = 7107 PerformCopyInitialization(Entity, SourceLocation(), Arg); 7108 if (ArgE.isInvalid()) 7109 return true; 7110 7111 Arg = ArgE.getAs<Expr>(); 7112 7113 } else { 7114 ExprResult ArgE = DefaultArgumentPromotion(Arg); 7115 7116 if (ArgE.isInvalid()) 7117 return true; 7118 7119 Arg = ArgE.getAs<Expr>(); 7120 } 7121 7122 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 7123 diag::err_call_incomplete_argument, Arg)) 7124 return ExprError(); 7125 7126 TheCall->setArg(i, Arg); 7127 } 7128 TheCall->computeDependence(); 7129 } 7130 7131 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 7132 if (!Method->isStatic()) 7133 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 7134 << Fn->getSourceRange()); 7135 7136 // Check for sentinels 7137 if (NDecl) 7138 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 7139 7140 // Warn for unions passing across security boundary (CMSE). 7141 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 7142 for (unsigned i = 0, e = Args.size(); i != e; i++) { 7143 if (const auto *RT = 7144 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 7145 if (RT->getDecl()->isOrContainsUnion()) 7146 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 7147 << 0 << i; 7148 } 7149 } 7150 } 7151 7152 // Do special checking on direct calls to functions. 7153 if (FDecl) { 7154 if (CheckFunctionCall(FDecl, TheCall, Proto)) 7155 return ExprError(); 7156 7157 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 7158 7159 if (BuiltinID) 7160 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 7161 } else if (NDecl) { 7162 if (CheckPointerCall(NDecl, TheCall, Proto)) 7163 return ExprError(); 7164 } else { 7165 if (CheckOtherCall(TheCall, Proto)) 7166 return ExprError(); 7167 } 7168 7169 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 7170 } 7171 7172 ExprResult 7173 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 7174 SourceLocation RParenLoc, Expr *InitExpr) { 7175 assert(Ty && "ActOnCompoundLiteral(): missing type"); 7176 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 7177 7178 TypeSourceInfo *TInfo; 7179 QualType literalType = GetTypeFromParser(Ty, &TInfo); 7180 if (!TInfo) 7181 TInfo = Context.getTrivialTypeSourceInfo(literalType); 7182 7183 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 7184 } 7185 7186 ExprResult 7187 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 7188 SourceLocation RParenLoc, Expr *LiteralExpr) { 7189 QualType literalType = TInfo->getType(); 7190 7191 if (literalType->isArrayType()) { 7192 if (RequireCompleteSizedType( 7193 LParenLoc, Context.getBaseElementType(literalType), 7194 diag::err_array_incomplete_or_sizeless_type, 7195 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 7196 return ExprError(); 7197 if (literalType->isVariableArrayType()) { 7198 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 7199 diag::err_variable_object_no_init)) { 7200 return ExprError(); 7201 } 7202 } 7203 } else if (!literalType->isDependentType() && 7204 RequireCompleteType(LParenLoc, literalType, 7205 diag::err_typecheck_decl_incomplete_type, 7206 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 7207 return ExprError(); 7208 7209 InitializedEntity Entity 7210 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 7211 InitializationKind Kind 7212 = InitializationKind::CreateCStyleCast(LParenLoc, 7213 SourceRange(LParenLoc, RParenLoc), 7214 /*InitList=*/true); 7215 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 7216 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 7217 &literalType); 7218 if (Result.isInvalid()) 7219 return ExprError(); 7220 LiteralExpr = Result.get(); 7221 7222 bool isFileScope = !CurContext->isFunctionOrMethod(); 7223 7224 // In C, compound literals are l-values for some reason. 7225 // For GCC compatibility, in C++, file-scope array compound literals with 7226 // constant initializers are also l-values, and compound literals are 7227 // otherwise prvalues. 7228 // 7229 // (GCC also treats C++ list-initialized file-scope array prvalues with 7230 // constant initializers as l-values, but that's non-conforming, so we don't 7231 // follow it there.) 7232 // 7233 // FIXME: It would be better to handle the lvalue cases as materializing and 7234 // lifetime-extending a temporary object, but our materialized temporaries 7235 // representation only supports lifetime extension from a variable, not "out 7236 // of thin air". 7237 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 7238 // is bound to the result of applying array-to-pointer decay to the compound 7239 // literal. 7240 // FIXME: GCC supports compound literals of reference type, which should 7241 // obviously have a value kind derived from the kind of reference involved. 7242 ExprValueKind VK = 7243 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 7244 ? VK_PRValue 7245 : VK_LValue; 7246 7247 if (isFileScope) 7248 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 7249 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 7250 Expr *Init = ILE->getInit(i); 7251 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 7252 } 7253 7254 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 7255 VK, LiteralExpr, isFileScope); 7256 if (isFileScope) { 7257 if (!LiteralExpr->isTypeDependent() && 7258 !LiteralExpr->isValueDependent() && 7259 !literalType->isDependentType()) // C99 6.5.2.5p3 7260 if (CheckForConstantInitializer(LiteralExpr, literalType)) 7261 return ExprError(); 7262 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 7263 literalType.getAddressSpace() != LangAS::Default) { 7264 // Embedded-C extensions to C99 6.5.2.5: 7265 // "If the compound literal occurs inside the body of a function, the 7266 // type name shall not be qualified by an address-space qualifier." 7267 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 7268 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 7269 return ExprError(); 7270 } 7271 7272 if (!isFileScope && !getLangOpts().CPlusPlus) { 7273 // Compound literals that have automatic storage duration are destroyed at 7274 // the end of the scope in C; in C++, they're just temporaries. 7275 7276 // Emit diagnostics if it is or contains a C union type that is non-trivial 7277 // to destruct. 7278 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 7279 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 7280 NTCUC_CompoundLiteral, NTCUK_Destruct); 7281 7282 // Diagnose jumps that enter or exit the lifetime of the compound literal. 7283 if (literalType.isDestructedType()) { 7284 Cleanup.setExprNeedsCleanups(true); 7285 ExprCleanupObjects.push_back(E); 7286 getCurFunction()->setHasBranchProtectedScope(); 7287 } 7288 } 7289 7290 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7291 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7292 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7293 E->getInitializer()->getExprLoc()); 7294 7295 return MaybeBindToTemporary(E); 7296 } 7297 7298 ExprResult 7299 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7300 SourceLocation RBraceLoc) { 7301 // Only produce each kind of designated initialization diagnostic once. 7302 SourceLocation FirstDesignator; 7303 bool DiagnosedArrayDesignator = false; 7304 bool DiagnosedNestedDesignator = false; 7305 bool DiagnosedMixedDesignator = false; 7306 7307 // Check that any designated initializers are syntactically valid in the 7308 // current language mode. 7309 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7310 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7311 if (FirstDesignator.isInvalid()) 7312 FirstDesignator = DIE->getBeginLoc(); 7313 7314 if (!getLangOpts().CPlusPlus) 7315 break; 7316 7317 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7318 DiagnosedNestedDesignator = true; 7319 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7320 << DIE->getDesignatorsSourceRange(); 7321 } 7322 7323 for (auto &Desig : DIE->designators()) { 7324 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7325 DiagnosedArrayDesignator = true; 7326 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7327 << Desig.getSourceRange(); 7328 } 7329 } 7330 7331 if (!DiagnosedMixedDesignator && 7332 !isa<DesignatedInitExpr>(InitArgList[0])) { 7333 DiagnosedMixedDesignator = true; 7334 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7335 << DIE->getSourceRange(); 7336 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7337 << InitArgList[0]->getSourceRange(); 7338 } 7339 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7340 isa<DesignatedInitExpr>(InitArgList[0])) { 7341 DiagnosedMixedDesignator = true; 7342 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7343 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7344 << DIE->getSourceRange(); 7345 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7346 << InitArgList[I]->getSourceRange(); 7347 } 7348 } 7349 7350 if (FirstDesignator.isValid()) { 7351 // Only diagnose designated initiaization as a C++20 extension if we didn't 7352 // already diagnose use of (non-C++20) C99 designator syntax. 7353 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7354 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7355 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7356 ? diag::warn_cxx17_compat_designated_init 7357 : diag::ext_cxx_designated_init); 7358 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7359 Diag(FirstDesignator, diag::ext_designated_init); 7360 } 7361 } 7362 7363 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7364 } 7365 7366 ExprResult 7367 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7368 SourceLocation RBraceLoc) { 7369 // Semantic analysis for initializers is done by ActOnDeclarator() and 7370 // CheckInitializer() - it requires knowledge of the object being initialized. 7371 7372 // Immediately handle non-overload placeholders. Overloads can be 7373 // resolved contextually, but everything else here can't. 7374 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7375 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7376 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7377 7378 // Ignore failures; dropping the entire initializer list because 7379 // of one failure would be terrible for indexing/etc. 7380 if (result.isInvalid()) continue; 7381 7382 InitArgList[I] = result.get(); 7383 } 7384 } 7385 7386 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7387 RBraceLoc); 7388 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7389 return E; 7390 } 7391 7392 /// Do an explicit extend of the given block pointer if we're in ARC. 7393 void Sema::maybeExtendBlockObject(ExprResult &E) { 7394 assert(E.get()->getType()->isBlockPointerType()); 7395 assert(E.get()->isPRValue()); 7396 7397 // Only do this in an r-value context. 7398 if (!getLangOpts().ObjCAutoRefCount) return; 7399 7400 E = ImplicitCastExpr::Create( 7401 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7402 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 7403 Cleanup.setExprNeedsCleanups(true); 7404 } 7405 7406 /// Prepare a conversion of the given expression to an ObjC object 7407 /// pointer type. 7408 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7409 QualType type = E.get()->getType(); 7410 if (type->isObjCObjectPointerType()) { 7411 return CK_BitCast; 7412 } else if (type->isBlockPointerType()) { 7413 maybeExtendBlockObject(E); 7414 return CK_BlockPointerToObjCPointerCast; 7415 } else { 7416 assert(type->isPointerType()); 7417 return CK_CPointerToObjCPointerCast; 7418 } 7419 } 7420 7421 /// Prepares for a scalar cast, performing all the necessary stages 7422 /// except the final cast and returning the kind required. 7423 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7424 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7425 // Also, callers should have filtered out the invalid cases with 7426 // pointers. Everything else should be possible. 7427 7428 QualType SrcTy = Src.get()->getType(); 7429 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7430 return CK_NoOp; 7431 7432 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7433 case Type::STK_MemberPointer: 7434 llvm_unreachable("member pointer type in C"); 7435 7436 case Type::STK_CPointer: 7437 case Type::STK_BlockPointer: 7438 case Type::STK_ObjCObjectPointer: 7439 switch (DestTy->getScalarTypeKind()) { 7440 case Type::STK_CPointer: { 7441 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7442 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7443 if (SrcAS != DestAS) 7444 return CK_AddressSpaceConversion; 7445 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7446 return CK_NoOp; 7447 return CK_BitCast; 7448 } 7449 case Type::STK_BlockPointer: 7450 return (SrcKind == Type::STK_BlockPointer 7451 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7452 case Type::STK_ObjCObjectPointer: 7453 if (SrcKind == Type::STK_ObjCObjectPointer) 7454 return CK_BitCast; 7455 if (SrcKind == Type::STK_CPointer) 7456 return CK_CPointerToObjCPointerCast; 7457 maybeExtendBlockObject(Src); 7458 return CK_BlockPointerToObjCPointerCast; 7459 case Type::STK_Bool: 7460 return CK_PointerToBoolean; 7461 case Type::STK_Integral: 7462 return CK_PointerToIntegral; 7463 case Type::STK_Floating: 7464 case Type::STK_FloatingComplex: 7465 case Type::STK_IntegralComplex: 7466 case Type::STK_MemberPointer: 7467 case Type::STK_FixedPoint: 7468 llvm_unreachable("illegal cast from pointer"); 7469 } 7470 llvm_unreachable("Should have returned before this"); 7471 7472 case Type::STK_FixedPoint: 7473 switch (DestTy->getScalarTypeKind()) { 7474 case Type::STK_FixedPoint: 7475 return CK_FixedPointCast; 7476 case Type::STK_Bool: 7477 return CK_FixedPointToBoolean; 7478 case Type::STK_Integral: 7479 return CK_FixedPointToIntegral; 7480 case Type::STK_Floating: 7481 return CK_FixedPointToFloating; 7482 case Type::STK_IntegralComplex: 7483 case Type::STK_FloatingComplex: 7484 Diag(Src.get()->getExprLoc(), 7485 diag::err_unimplemented_conversion_with_fixed_point_type) 7486 << DestTy; 7487 return CK_IntegralCast; 7488 case Type::STK_CPointer: 7489 case Type::STK_ObjCObjectPointer: 7490 case Type::STK_BlockPointer: 7491 case Type::STK_MemberPointer: 7492 llvm_unreachable("illegal cast to pointer type"); 7493 } 7494 llvm_unreachable("Should have returned before this"); 7495 7496 case Type::STK_Bool: // casting from bool is like casting from an integer 7497 case Type::STK_Integral: 7498 switch (DestTy->getScalarTypeKind()) { 7499 case Type::STK_CPointer: 7500 case Type::STK_ObjCObjectPointer: 7501 case Type::STK_BlockPointer: 7502 if (Src.get()->isNullPointerConstant(Context, 7503 Expr::NPC_ValueDependentIsNull)) 7504 return CK_NullToPointer; 7505 return CK_IntegralToPointer; 7506 case Type::STK_Bool: 7507 return CK_IntegralToBoolean; 7508 case Type::STK_Integral: 7509 return CK_IntegralCast; 7510 case Type::STK_Floating: 7511 return CK_IntegralToFloating; 7512 case Type::STK_IntegralComplex: 7513 Src = ImpCastExprToType(Src.get(), 7514 DestTy->castAs<ComplexType>()->getElementType(), 7515 CK_IntegralCast); 7516 return CK_IntegralRealToComplex; 7517 case Type::STK_FloatingComplex: 7518 Src = ImpCastExprToType(Src.get(), 7519 DestTy->castAs<ComplexType>()->getElementType(), 7520 CK_IntegralToFloating); 7521 return CK_FloatingRealToComplex; 7522 case Type::STK_MemberPointer: 7523 llvm_unreachable("member pointer type in C"); 7524 case Type::STK_FixedPoint: 7525 return CK_IntegralToFixedPoint; 7526 } 7527 llvm_unreachable("Should have returned before this"); 7528 7529 case Type::STK_Floating: 7530 switch (DestTy->getScalarTypeKind()) { 7531 case Type::STK_Floating: 7532 return CK_FloatingCast; 7533 case Type::STK_Bool: 7534 return CK_FloatingToBoolean; 7535 case Type::STK_Integral: 7536 return CK_FloatingToIntegral; 7537 case Type::STK_FloatingComplex: 7538 Src = ImpCastExprToType(Src.get(), 7539 DestTy->castAs<ComplexType>()->getElementType(), 7540 CK_FloatingCast); 7541 return CK_FloatingRealToComplex; 7542 case Type::STK_IntegralComplex: 7543 Src = ImpCastExprToType(Src.get(), 7544 DestTy->castAs<ComplexType>()->getElementType(), 7545 CK_FloatingToIntegral); 7546 return CK_IntegralRealToComplex; 7547 case Type::STK_CPointer: 7548 case Type::STK_ObjCObjectPointer: 7549 case Type::STK_BlockPointer: 7550 llvm_unreachable("valid float->pointer cast?"); 7551 case Type::STK_MemberPointer: 7552 llvm_unreachable("member pointer type in C"); 7553 case Type::STK_FixedPoint: 7554 return CK_FloatingToFixedPoint; 7555 } 7556 llvm_unreachable("Should have returned before this"); 7557 7558 case Type::STK_FloatingComplex: 7559 switch (DestTy->getScalarTypeKind()) { 7560 case Type::STK_FloatingComplex: 7561 return CK_FloatingComplexCast; 7562 case Type::STK_IntegralComplex: 7563 return CK_FloatingComplexToIntegralComplex; 7564 case Type::STK_Floating: { 7565 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7566 if (Context.hasSameType(ET, DestTy)) 7567 return CK_FloatingComplexToReal; 7568 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7569 return CK_FloatingCast; 7570 } 7571 case Type::STK_Bool: 7572 return CK_FloatingComplexToBoolean; 7573 case Type::STK_Integral: 7574 Src = ImpCastExprToType(Src.get(), 7575 SrcTy->castAs<ComplexType>()->getElementType(), 7576 CK_FloatingComplexToReal); 7577 return CK_FloatingToIntegral; 7578 case Type::STK_CPointer: 7579 case Type::STK_ObjCObjectPointer: 7580 case Type::STK_BlockPointer: 7581 llvm_unreachable("valid complex float->pointer cast?"); 7582 case Type::STK_MemberPointer: 7583 llvm_unreachable("member pointer type in C"); 7584 case Type::STK_FixedPoint: 7585 Diag(Src.get()->getExprLoc(), 7586 diag::err_unimplemented_conversion_with_fixed_point_type) 7587 << SrcTy; 7588 return CK_IntegralCast; 7589 } 7590 llvm_unreachable("Should have returned before this"); 7591 7592 case Type::STK_IntegralComplex: 7593 switch (DestTy->getScalarTypeKind()) { 7594 case Type::STK_FloatingComplex: 7595 return CK_IntegralComplexToFloatingComplex; 7596 case Type::STK_IntegralComplex: 7597 return CK_IntegralComplexCast; 7598 case Type::STK_Integral: { 7599 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7600 if (Context.hasSameType(ET, DestTy)) 7601 return CK_IntegralComplexToReal; 7602 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7603 return CK_IntegralCast; 7604 } 7605 case Type::STK_Bool: 7606 return CK_IntegralComplexToBoolean; 7607 case Type::STK_Floating: 7608 Src = ImpCastExprToType(Src.get(), 7609 SrcTy->castAs<ComplexType>()->getElementType(), 7610 CK_IntegralComplexToReal); 7611 return CK_IntegralToFloating; 7612 case Type::STK_CPointer: 7613 case Type::STK_ObjCObjectPointer: 7614 case Type::STK_BlockPointer: 7615 llvm_unreachable("valid complex int->pointer cast?"); 7616 case Type::STK_MemberPointer: 7617 llvm_unreachable("member pointer type in C"); 7618 case Type::STK_FixedPoint: 7619 Diag(Src.get()->getExprLoc(), 7620 diag::err_unimplemented_conversion_with_fixed_point_type) 7621 << SrcTy; 7622 return CK_IntegralCast; 7623 } 7624 llvm_unreachable("Should have returned before this"); 7625 } 7626 7627 llvm_unreachable("Unhandled scalar cast"); 7628 } 7629 7630 static bool breakDownVectorType(QualType type, uint64_t &len, 7631 QualType &eltType) { 7632 // Vectors are simple. 7633 if (const VectorType *vecType = type->getAs<VectorType>()) { 7634 len = vecType->getNumElements(); 7635 eltType = vecType->getElementType(); 7636 assert(eltType->isScalarType()); 7637 return true; 7638 } 7639 7640 // We allow lax conversion to and from non-vector types, but only if 7641 // they're real types (i.e. non-complex, non-pointer scalar types). 7642 if (!type->isRealType()) return false; 7643 7644 len = 1; 7645 eltType = type; 7646 return true; 7647 } 7648 7649 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7650 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7651 /// allowed? 7652 /// 7653 /// This will also return false if the two given types do not make sense from 7654 /// the perspective of SVE bitcasts. 7655 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7656 assert(srcTy->isVectorType() || destTy->isVectorType()); 7657 7658 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7659 if (!FirstType->isSizelessBuiltinType()) 7660 return false; 7661 7662 const auto *VecTy = SecondType->getAs<VectorType>(); 7663 return VecTy && 7664 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7665 }; 7666 7667 return ValidScalableConversion(srcTy, destTy) || 7668 ValidScalableConversion(destTy, srcTy); 7669 } 7670 7671 /// Are the two types matrix types and do they have the same dimensions i.e. 7672 /// do they have the same number of rows and the same number of columns? 7673 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7674 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7675 return false; 7676 7677 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7678 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7679 7680 return matSrcType->getNumRows() == matDestType->getNumRows() && 7681 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7682 } 7683 7684 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7685 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7686 7687 uint64_t SrcLen, DestLen; 7688 QualType SrcEltTy, DestEltTy; 7689 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7690 return false; 7691 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7692 return false; 7693 7694 // ASTContext::getTypeSize will return the size rounded up to a 7695 // power of 2, so instead of using that, we need to use the raw 7696 // element size multiplied by the element count. 7697 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7698 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7699 7700 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7701 } 7702 7703 /// Are the two types lax-compatible vector types? That is, given 7704 /// that one of them is a vector, do they have equal storage sizes, 7705 /// where the storage size is the number of elements times the element 7706 /// size? 7707 /// 7708 /// This will also return false if either of the types is neither a 7709 /// vector nor a real type. 7710 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7711 assert(destTy->isVectorType() || srcTy->isVectorType()); 7712 7713 // Disallow lax conversions between scalars and ExtVectors (these 7714 // conversions are allowed for other vector types because common headers 7715 // depend on them). Most scalar OP ExtVector cases are handled by the 7716 // splat path anyway, which does what we want (convert, not bitcast). 7717 // What this rules out for ExtVectors is crazy things like char4*float. 7718 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7719 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7720 7721 return areVectorTypesSameSize(srcTy, destTy); 7722 } 7723 7724 /// Is this a legal conversion between two types, one of which is 7725 /// known to be a vector type? 7726 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7727 assert(destTy->isVectorType() || srcTy->isVectorType()); 7728 7729 switch (Context.getLangOpts().getLaxVectorConversions()) { 7730 case LangOptions::LaxVectorConversionKind::None: 7731 return false; 7732 7733 case LangOptions::LaxVectorConversionKind::Integer: 7734 if (!srcTy->isIntegralOrEnumerationType()) { 7735 auto *Vec = srcTy->getAs<VectorType>(); 7736 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7737 return false; 7738 } 7739 if (!destTy->isIntegralOrEnumerationType()) { 7740 auto *Vec = destTy->getAs<VectorType>(); 7741 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7742 return false; 7743 } 7744 // OK, integer (vector) -> integer (vector) bitcast. 7745 break; 7746 7747 case LangOptions::LaxVectorConversionKind::All: 7748 break; 7749 } 7750 7751 return areLaxCompatibleVectorTypes(srcTy, destTy); 7752 } 7753 7754 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7755 CastKind &Kind) { 7756 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7757 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7758 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7759 << DestTy << SrcTy << R; 7760 } 7761 } else if (SrcTy->isMatrixType()) { 7762 return Diag(R.getBegin(), 7763 diag::err_invalid_conversion_between_matrix_and_type) 7764 << SrcTy << DestTy << R; 7765 } else if (DestTy->isMatrixType()) { 7766 return Diag(R.getBegin(), 7767 diag::err_invalid_conversion_between_matrix_and_type) 7768 << DestTy << SrcTy << R; 7769 } 7770 7771 Kind = CK_MatrixCast; 7772 return false; 7773 } 7774 7775 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7776 CastKind &Kind) { 7777 assert(VectorTy->isVectorType() && "Not a vector type!"); 7778 7779 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7780 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7781 return Diag(R.getBegin(), 7782 Ty->isVectorType() ? 7783 diag::err_invalid_conversion_between_vectors : 7784 diag::err_invalid_conversion_between_vector_and_integer) 7785 << VectorTy << Ty << R; 7786 } else 7787 return Diag(R.getBegin(), 7788 diag::err_invalid_conversion_between_vector_and_scalar) 7789 << VectorTy << Ty << R; 7790 7791 Kind = CK_BitCast; 7792 return false; 7793 } 7794 7795 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7796 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7797 7798 if (DestElemTy == SplattedExpr->getType()) 7799 return SplattedExpr; 7800 7801 assert(DestElemTy->isFloatingType() || 7802 DestElemTy->isIntegralOrEnumerationType()); 7803 7804 CastKind CK; 7805 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7806 // OpenCL requires that we convert `true` boolean expressions to -1, but 7807 // only when splatting vectors. 7808 if (DestElemTy->isFloatingType()) { 7809 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7810 // in two steps: boolean to signed integral, then to floating. 7811 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7812 CK_BooleanToSignedIntegral); 7813 SplattedExpr = CastExprRes.get(); 7814 CK = CK_IntegralToFloating; 7815 } else { 7816 CK = CK_BooleanToSignedIntegral; 7817 } 7818 } else { 7819 ExprResult CastExprRes = SplattedExpr; 7820 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7821 if (CastExprRes.isInvalid()) 7822 return ExprError(); 7823 SplattedExpr = CastExprRes.get(); 7824 } 7825 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7826 } 7827 7828 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7829 Expr *CastExpr, CastKind &Kind) { 7830 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7831 7832 QualType SrcTy = CastExpr->getType(); 7833 7834 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7835 // an ExtVectorType. 7836 // In OpenCL, casts between vectors of different types are not allowed. 7837 // (See OpenCL 6.2). 7838 if (SrcTy->isVectorType()) { 7839 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7840 (getLangOpts().OpenCL && 7841 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7842 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7843 << DestTy << SrcTy << R; 7844 return ExprError(); 7845 } 7846 Kind = CK_BitCast; 7847 return CastExpr; 7848 } 7849 7850 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7851 // conversion will take place first from scalar to elt type, and then 7852 // splat from elt type to vector. 7853 if (SrcTy->isPointerType()) 7854 return Diag(R.getBegin(), 7855 diag::err_invalid_conversion_between_vector_and_scalar) 7856 << DestTy << SrcTy << R; 7857 7858 Kind = CK_VectorSplat; 7859 return prepareVectorSplat(DestTy, CastExpr); 7860 } 7861 7862 ExprResult 7863 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7864 Declarator &D, ParsedType &Ty, 7865 SourceLocation RParenLoc, Expr *CastExpr) { 7866 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7867 "ActOnCastExpr(): missing type or expr"); 7868 7869 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7870 if (D.isInvalidType()) 7871 return ExprError(); 7872 7873 if (getLangOpts().CPlusPlus) { 7874 // Check that there are no default arguments (C++ only). 7875 CheckExtraCXXDefaultArguments(D); 7876 } else { 7877 // Make sure any TypoExprs have been dealt with. 7878 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7879 if (!Res.isUsable()) 7880 return ExprError(); 7881 CastExpr = Res.get(); 7882 } 7883 7884 checkUnusedDeclAttributes(D); 7885 7886 QualType castType = castTInfo->getType(); 7887 Ty = CreateParsedType(castType, castTInfo); 7888 7889 bool isVectorLiteral = false; 7890 7891 // Check for an altivec or OpenCL literal, 7892 // i.e. all the elements are integer constants. 7893 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7894 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7895 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7896 && castType->isVectorType() && (PE || PLE)) { 7897 if (PLE && PLE->getNumExprs() == 0) { 7898 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7899 return ExprError(); 7900 } 7901 if (PE || PLE->getNumExprs() == 1) { 7902 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7903 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7904 isVectorLiteral = true; 7905 } 7906 else 7907 isVectorLiteral = true; 7908 } 7909 7910 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7911 // then handle it as such. 7912 if (isVectorLiteral) 7913 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7914 7915 // If the Expr being casted is a ParenListExpr, handle it specially. 7916 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7917 // sequence of BinOp comma operators. 7918 if (isa<ParenListExpr>(CastExpr)) { 7919 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7920 if (Result.isInvalid()) return ExprError(); 7921 CastExpr = Result.get(); 7922 } 7923 7924 if (getLangOpts().CPlusPlus && !castType->isVoidType()) 7925 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7926 7927 CheckTollFreeBridgeCast(castType, CastExpr); 7928 7929 CheckObjCBridgeRelatedCast(castType, CastExpr); 7930 7931 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7932 7933 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7934 } 7935 7936 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7937 SourceLocation RParenLoc, Expr *E, 7938 TypeSourceInfo *TInfo) { 7939 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7940 "Expected paren or paren list expression"); 7941 7942 Expr **exprs; 7943 unsigned numExprs; 7944 Expr *subExpr; 7945 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7946 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7947 LiteralLParenLoc = PE->getLParenLoc(); 7948 LiteralRParenLoc = PE->getRParenLoc(); 7949 exprs = PE->getExprs(); 7950 numExprs = PE->getNumExprs(); 7951 } else { // isa<ParenExpr> by assertion at function entrance 7952 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7953 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7954 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7955 exprs = &subExpr; 7956 numExprs = 1; 7957 } 7958 7959 QualType Ty = TInfo->getType(); 7960 assert(Ty->isVectorType() && "Expected vector type"); 7961 7962 SmallVector<Expr *, 8> initExprs; 7963 const VectorType *VTy = Ty->castAs<VectorType>(); 7964 unsigned numElems = VTy->getNumElements(); 7965 7966 // '(...)' form of vector initialization in AltiVec: the number of 7967 // initializers must be one or must match the size of the vector. 7968 // If a single value is specified in the initializer then it will be 7969 // replicated to all the components of the vector 7970 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, 7971 VTy->getElementType())) 7972 return ExprError(); 7973 if (ShouldSplatAltivecScalarInCast(VTy)) { 7974 // The number of initializers must be one or must match the size of the 7975 // vector. If a single value is specified in the initializer then it will 7976 // be replicated to all the components of the vector 7977 if (numExprs == 1) { 7978 QualType ElemTy = VTy->getElementType(); 7979 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7980 if (Literal.isInvalid()) 7981 return ExprError(); 7982 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7983 PrepareScalarCast(Literal, ElemTy)); 7984 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7985 } 7986 else if (numExprs < numElems) { 7987 Diag(E->getExprLoc(), 7988 diag::err_incorrect_number_of_vector_initializers); 7989 return ExprError(); 7990 } 7991 else 7992 initExprs.append(exprs, exprs + numExprs); 7993 } 7994 else { 7995 // For OpenCL, when the number of initializers is a single value, 7996 // it will be replicated to all components of the vector. 7997 if (getLangOpts().OpenCL && 7998 VTy->getVectorKind() == VectorType::GenericVector && 7999 numExprs == 1) { 8000 QualType ElemTy = VTy->getElementType(); 8001 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 8002 if (Literal.isInvalid()) 8003 return ExprError(); 8004 Literal = ImpCastExprToType(Literal.get(), ElemTy, 8005 PrepareScalarCast(Literal, ElemTy)); 8006 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 8007 } 8008 8009 initExprs.append(exprs, exprs + numExprs); 8010 } 8011 // FIXME: This means that pretty-printing the final AST will produce curly 8012 // braces instead of the original commas. 8013 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 8014 initExprs, LiteralRParenLoc); 8015 initE->setType(Ty); 8016 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 8017 } 8018 8019 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 8020 /// the ParenListExpr into a sequence of comma binary operators. 8021 ExprResult 8022 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 8023 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 8024 if (!E) 8025 return OrigExpr; 8026 8027 ExprResult Result(E->getExpr(0)); 8028 8029 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 8030 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 8031 E->getExpr(i)); 8032 8033 if (Result.isInvalid()) return ExprError(); 8034 8035 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 8036 } 8037 8038 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 8039 SourceLocation R, 8040 MultiExprArg Val) { 8041 return ParenListExpr::Create(Context, L, Val, R); 8042 } 8043 8044 /// Emit a specialized diagnostic when one expression is a null pointer 8045 /// constant and the other is not a pointer. Returns true if a diagnostic is 8046 /// emitted. 8047 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 8048 SourceLocation QuestionLoc) { 8049 Expr *NullExpr = LHSExpr; 8050 Expr *NonPointerExpr = RHSExpr; 8051 Expr::NullPointerConstantKind NullKind = 8052 NullExpr->isNullPointerConstant(Context, 8053 Expr::NPC_ValueDependentIsNotNull); 8054 8055 if (NullKind == Expr::NPCK_NotNull) { 8056 NullExpr = RHSExpr; 8057 NonPointerExpr = LHSExpr; 8058 NullKind = 8059 NullExpr->isNullPointerConstant(Context, 8060 Expr::NPC_ValueDependentIsNotNull); 8061 } 8062 8063 if (NullKind == Expr::NPCK_NotNull) 8064 return false; 8065 8066 if (NullKind == Expr::NPCK_ZeroExpression) 8067 return false; 8068 8069 if (NullKind == Expr::NPCK_ZeroLiteral) { 8070 // In this case, check to make sure that we got here from a "NULL" 8071 // string in the source code. 8072 NullExpr = NullExpr->IgnoreParenImpCasts(); 8073 SourceLocation loc = NullExpr->getExprLoc(); 8074 if (!findMacroSpelling(loc, "NULL")) 8075 return false; 8076 } 8077 8078 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 8079 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 8080 << NonPointerExpr->getType() << DiagType 8081 << NonPointerExpr->getSourceRange(); 8082 return true; 8083 } 8084 8085 /// Return false if the condition expression is valid, true otherwise. 8086 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 8087 QualType CondTy = Cond->getType(); 8088 8089 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 8090 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 8091 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8092 << CondTy << Cond->getSourceRange(); 8093 return true; 8094 } 8095 8096 // C99 6.5.15p2 8097 if (CondTy->isScalarType()) return false; 8098 8099 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 8100 << CondTy << Cond->getSourceRange(); 8101 return true; 8102 } 8103 8104 /// Handle when one or both operands are void type. 8105 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 8106 ExprResult &RHS) { 8107 Expr *LHSExpr = LHS.get(); 8108 Expr *RHSExpr = RHS.get(); 8109 8110 if (!LHSExpr->getType()->isVoidType()) 8111 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 8112 << RHSExpr->getSourceRange(); 8113 if (!RHSExpr->getType()->isVoidType()) 8114 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 8115 << LHSExpr->getSourceRange(); 8116 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 8117 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 8118 return S.Context.VoidTy; 8119 } 8120 8121 /// Return false if the NullExpr can be promoted to PointerTy, 8122 /// true otherwise. 8123 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 8124 QualType PointerTy) { 8125 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 8126 !NullExpr.get()->isNullPointerConstant(S.Context, 8127 Expr::NPC_ValueDependentIsNull)) 8128 return true; 8129 8130 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 8131 return false; 8132 } 8133 8134 /// Checks compatibility between two pointers and return the resulting 8135 /// type. 8136 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 8137 ExprResult &RHS, 8138 SourceLocation Loc) { 8139 QualType LHSTy = LHS.get()->getType(); 8140 QualType RHSTy = RHS.get()->getType(); 8141 8142 if (S.Context.hasSameType(LHSTy, RHSTy)) { 8143 // Two identical pointers types are always compatible. 8144 return LHSTy; 8145 } 8146 8147 QualType lhptee, rhptee; 8148 8149 // Get the pointee types. 8150 bool IsBlockPointer = false; 8151 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 8152 lhptee = LHSBTy->getPointeeType(); 8153 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 8154 IsBlockPointer = true; 8155 } else { 8156 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8157 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8158 } 8159 8160 // C99 6.5.15p6: If both operands are pointers to compatible types or to 8161 // differently qualified versions of compatible types, the result type is 8162 // a pointer to an appropriately qualified version of the composite 8163 // type. 8164 8165 // Only CVR-qualifiers exist in the standard, and the differently-qualified 8166 // clause doesn't make sense for our extensions. E.g. address space 2 should 8167 // be incompatible with address space 3: they may live on different devices or 8168 // anything. 8169 Qualifiers lhQual = lhptee.getQualifiers(); 8170 Qualifiers rhQual = rhptee.getQualifiers(); 8171 8172 LangAS ResultAddrSpace = LangAS::Default; 8173 LangAS LAddrSpace = lhQual.getAddressSpace(); 8174 LangAS RAddrSpace = rhQual.getAddressSpace(); 8175 8176 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 8177 // spaces is disallowed. 8178 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 8179 ResultAddrSpace = LAddrSpace; 8180 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 8181 ResultAddrSpace = RAddrSpace; 8182 else { 8183 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8184 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 8185 << RHS.get()->getSourceRange(); 8186 return QualType(); 8187 } 8188 8189 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 8190 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 8191 lhQual.removeCVRQualifiers(); 8192 rhQual.removeCVRQualifiers(); 8193 8194 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 8195 // (C99 6.7.3) for address spaces. We assume that the check should behave in 8196 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 8197 // qual types are compatible iff 8198 // * corresponded types are compatible 8199 // * CVR qualifiers are equal 8200 // * address spaces are equal 8201 // Thus for conditional operator we merge CVR and address space unqualified 8202 // pointees and if there is a composite type we return a pointer to it with 8203 // merged qualifiers. 8204 LHSCastKind = 8205 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 8206 RHSCastKind = 8207 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 8208 lhQual.removeAddressSpace(); 8209 rhQual.removeAddressSpace(); 8210 8211 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 8212 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 8213 8214 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 8215 8216 if (CompositeTy.isNull()) { 8217 // In this situation, we assume void* type. No especially good 8218 // reason, but this is what gcc does, and we do have to pick 8219 // to get a consistent AST. 8220 QualType incompatTy; 8221 incompatTy = S.Context.getPointerType( 8222 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 8223 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 8224 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 8225 8226 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 8227 // for casts between types with incompatible address space qualifiers. 8228 // For the following code the compiler produces casts between global and 8229 // local address spaces of the corresponded innermost pointees: 8230 // local int *global *a; 8231 // global int *global *b; 8232 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 8233 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 8234 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8235 << RHS.get()->getSourceRange(); 8236 8237 return incompatTy; 8238 } 8239 8240 // The pointer types are compatible. 8241 // In case of OpenCL ResultTy should have the address space qualifier 8242 // which is a superset of address spaces of both the 2nd and the 3rd 8243 // operands of the conditional operator. 8244 QualType ResultTy = [&, ResultAddrSpace]() { 8245 if (S.getLangOpts().OpenCL) { 8246 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 8247 CompositeQuals.setAddressSpace(ResultAddrSpace); 8248 return S.Context 8249 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 8250 .withCVRQualifiers(MergedCVRQual); 8251 } 8252 return CompositeTy.withCVRQualifiers(MergedCVRQual); 8253 }(); 8254 if (IsBlockPointer) 8255 ResultTy = S.Context.getBlockPointerType(ResultTy); 8256 else 8257 ResultTy = S.Context.getPointerType(ResultTy); 8258 8259 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 8260 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 8261 return ResultTy; 8262 } 8263 8264 /// Return the resulting type when the operands are both block pointers. 8265 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 8266 ExprResult &LHS, 8267 ExprResult &RHS, 8268 SourceLocation Loc) { 8269 QualType LHSTy = LHS.get()->getType(); 8270 QualType RHSTy = RHS.get()->getType(); 8271 8272 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 8273 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 8274 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 8275 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8276 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8277 return destType; 8278 } 8279 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 8280 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8281 << RHS.get()->getSourceRange(); 8282 return QualType(); 8283 } 8284 8285 // We have 2 block pointer types. 8286 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8287 } 8288 8289 /// Return the resulting type when the operands are both pointers. 8290 static QualType 8291 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8292 ExprResult &RHS, 8293 SourceLocation Loc) { 8294 // get the pointer types 8295 QualType LHSTy = LHS.get()->getType(); 8296 QualType RHSTy = RHS.get()->getType(); 8297 8298 // get the "pointed to" types 8299 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8300 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8301 8302 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8303 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8304 // Figure out necessary qualifiers (C99 6.5.15p6) 8305 QualType destPointee 8306 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8307 QualType destType = S.Context.getPointerType(destPointee); 8308 // Add qualifiers if necessary. 8309 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8310 // Promote to void*. 8311 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8312 return destType; 8313 } 8314 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8315 QualType destPointee 8316 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8317 QualType destType = S.Context.getPointerType(destPointee); 8318 // Add qualifiers if necessary. 8319 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8320 // Promote to void*. 8321 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8322 return destType; 8323 } 8324 8325 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8326 } 8327 8328 /// Return false if the first expression is not an integer and the second 8329 /// expression is not a pointer, true otherwise. 8330 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8331 Expr* PointerExpr, SourceLocation Loc, 8332 bool IsIntFirstExpr) { 8333 if (!PointerExpr->getType()->isPointerType() || 8334 !Int.get()->getType()->isIntegerType()) 8335 return false; 8336 8337 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8338 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8339 8340 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8341 << Expr1->getType() << Expr2->getType() 8342 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8343 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8344 CK_IntegralToPointer); 8345 return true; 8346 } 8347 8348 /// Simple conversion between integer and floating point types. 8349 /// 8350 /// Used when handling the OpenCL conditional operator where the 8351 /// condition is a vector while the other operands are scalar. 8352 /// 8353 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8354 /// types are either integer or floating type. Between the two 8355 /// operands, the type with the higher rank is defined as the "result 8356 /// type". The other operand needs to be promoted to the same type. No 8357 /// other type promotion is allowed. We cannot use 8358 /// UsualArithmeticConversions() for this purpose, since it always 8359 /// promotes promotable types. 8360 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8361 ExprResult &RHS, 8362 SourceLocation QuestionLoc) { 8363 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8364 if (LHS.isInvalid()) 8365 return QualType(); 8366 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8367 if (RHS.isInvalid()) 8368 return QualType(); 8369 8370 // For conversion purposes, we ignore any qualifiers. 8371 // For example, "const float" and "float" are equivalent. 8372 QualType LHSType = 8373 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8374 QualType RHSType = 8375 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8376 8377 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8378 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8379 << LHSType << LHS.get()->getSourceRange(); 8380 return QualType(); 8381 } 8382 8383 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8384 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8385 << RHSType << RHS.get()->getSourceRange(); 8386 return QualType(); 8387 } 8388 8389 // If both types are identical, no conversion is needed. 8390 if (LHSType == RHSType) 8391 return LHSType; 8392 8393 // Now handle "real" floating types (i.e. float, double, long double). 8394 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8395 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8396 /*IsCompAssign = */ false); 8397 8398 // Finally, we have two differing integer types. 8399 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8400 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8401 } 8402 8403 /// Convert scalar operands to a vector that matches the 8404 /// condition in length. 8405 /// 8406 /// Used when handling the OpenCL conditional operator where the 8407 /// condition is a vector while the other operands are scalar. 8408 /// 8409 /// We first compute the "result type" for the scalar operands 8410 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8411 /// into a vector of that type where the length matches the condition 8412 /// vector type. s6.11.6 requires that the element types of the result 8413 /// and the condition must have the same number of bits. 8414 static QualType 8415 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8416 QualType CondTy, SourceLocation QuestionLoc) { 8417 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8418 if (ResTy.isNull()) return QualType(); 8419 8420 const VectorType *CV = CondTy->getAs<VectorType>(); 8421 assert(CV); 8422 8423 // Determine the vector result type 8424 unsigned NumElements = CV->getNumElements(); 8425 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8426 8427 // Ensure that all types have the same number of bits 8428 if (S.Context.getTypeSize(CV->getElementType()) 8429 != S.Context.getTypeSize(ResTy)) { 8430 // Since VectorTy is created internally, it does not pretty print 8431 // with an OpenCL name. Instead, we just print a description. 8432 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8433 SmallString<64> Str; 8434 llvm::raw_svector_ostream OS(Str); 8435 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8436 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8437 << CondTy << OS.str(); 8438 return QualType(); 8439 } 8440 8441 // Convert operands to the vector result type 8442 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8443 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8444 8445 return VectorTy; 8446 } 8447 8448 /// Return false if this is a valid OpenCL condition vector 8449 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8450 SourceLocation QuestionLoc) { 8451 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8452 // integral type. 8453 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8454 assert(CondTy); 8455 QualType EleTy = CondTy->getElementType(); 8456 if (EleTy->isIntegerType()) return false; 8457 8458 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8459 << Cond->getType() << Cond->getSourceRange(); 8460 return true; 8461 } 8462 8463 /// Return false if the vector condition type and the vector 8464 /// result type are compatible. 8465 /// 8466 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8467 /// number of elements, and their element types have the same number 8468 /// of bits. 8469 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8470 SourceLocation QuestionLoc) { 8471 const VectorType *CV = CondTy->getAs<VectorType>(); 8472 const VectorType *RV = VecResTy->getAs<VectorType>(); 8473 assert(CV && RV); 8474 8475 if (CV->getNumElements() != RV->getNumElements()) { 8476 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8477 << CondTy << VecResTy; 8478 return true; 8479 } 8480 8481 QualType CVE = CV->getElementType(); 8482 QualType RVE = RV->getElementType(); 8483 8484 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8485 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8486 << CondTy << VecResTy; 8487 return true; 8488 } 8489 8490 return false; 8491 } 8492 8493 /// Return the resulting type for the conditional operator in 8494 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8495 /// s6.3.i) when the condition is a vector type. 8496 static QualType 8497 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8498 ExprResult &LHS, ExprResult &RHS, 8499 SourceLocation QuestionLoc) { 8500 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8501 if (Cond.isInvalid()) 8502 return QualType(); 8503 QualType CondTy = Cond.get()->getType(); 8504 8505 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8506 return QualType(); 8507 8508 // If either operand is a vector then find the vector type of the 8509 // result as specified in OpenCL v1.1 s6.3.i. 8510 if (LHS.get()->getType()->isVectorType() || 8511 RHS.get()->getType()->isVectorType()) { 8512 bool IsBoolVecLang = 8513 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus; 8514 QualType VecResTy = 8515 S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8516 /*isCompAssign*/ false, 8517 /*AllowBothBool*/ true, 8518 /*AllowBoolConversions*/ false, 8519 /*AllowBooleanOperation*/ IsBoolVecLang, 8520 /*ReportInvalid*/ true); 8521 if (VecResTy.isNull()) 8522 return QualType(); 8523 // The result type must match the condition type as specified in 8524 // OpenCL v1.1 s6.11.6. 8525 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8526 return QualType(); 8527 return VecResTy; 8528 } 8529 8530 // Both operands are scalar. 8531 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8532 } 8533 8534 /// Return true if the Expr is block type 8535 static bool checkBlockType(Sema &S, const Expr *E) { 8536 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8537 QualType Ty = CE->getCallee()->getType(); 8538 if (Ty->isBlockPointerType()) { 8539 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8540 return true; 8541 } 8542 } 8543 return false; 8544 } 8545 8546 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8547 /// In that case, LHS = cond. 8548 /// C99 6.5.15 8549 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8550 ExprResult &RHS, ExprValueKind &VK, 8551 ExprObjectKind &OK, 8552 SourceLocation QuestionLoc) { 8553 8554 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8555 if (!LHSResult.isUsable()) return QualType(); 8556 LHS = LHSResult; 8557 8558 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8559 if (!RHSResult.isUsable()) return QualType(); 8560 RHS = RHSResult; 8561 8562 // C++ is sufficiently different to merit its own checker. 8563 if (getLangOpts().CPlusPlus) 8564 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8565 8566 VK = VK_PRValue; 8567 OK = OK_Ordinary; 8568 8569 if (Context.isDependenceAllowed() && 8570 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8571 RHS.get()->isTypeDependent())) { 8572 assert(!getLangOpts().CPlusPlus); 8573 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8574 RHS.get()->containsErrors()) && 8575 "should only occur in error-recovery path."); 8576 return Context.DependentTy; 8577 } 8578 8579 // The OpenCL operator with a vector condition is sufficiently 8580 // different to merit its own checker. 8581 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8582 Cond.get()->getType()->isExtVectorType()) 8583 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8584 8585 // First, check the condition. 8586 Cond = UsualUnaryConversions(Cond.get()); 8587 if (Cond.isInvalid()) 8588 return QualType(); 8589 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8590 return QualType(); 8591 8592 // Now check the two expressions. 8593 if (LHS.get()->getType()->isVectorType() || 8594 RHS.get()->getType()->isVectorType()) 8595 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false, 8596 /*AllowBothBool*/ true, 8597 /*AllowBoolConversions*/ false, 8598 /*AllowBooleanOperation*/ false, 8599 /*ReportInvalid*/ true); 8600 8601 QualType ResTy = 8602 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8603 if (LHS.isInvalid() || RHS.isInvalid()) 8604 return QualType(); 8605 8606 QualType LHSTy = LHS.get()->getType(); 8607 QualType RHSTy = RHS.get()->getType(); 8608 8609 // Diagnose attempts to convert between __ibm128, __float128 and long double 8610 // where such conversions currently can't be handled. 8611 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8612 Diag(QuestionLoc, 8613 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8614 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8615 return QualType(); 8616 } 8617 8618 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8619 // selection operator (?:). 8620 if (getLangOpts().OpenCL && 8621 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) { 8622 return QualType(); 8623 } 8624 8625 // If both operands have arithmetic type, do the usual arithmetic conversions 8626 // to find a common type: C99 6.5.15p3,5. 8627 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8628 // Disallow invalid arithmetic conversions, such as those between bit- 8629 // precise integers types of different sizes, or between a bit-precise 8630 // integer and another type. 8631 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) { 8632 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8633 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8634 << RHS.get()->getSourceRange(); 8635 return QualType(); 8636 } 8637 8638 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8639 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8640 8641 return ResTy; 8642 } 8643 8644 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8645 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8646 return LHSTy; 8647 } 8648 8649 // If both operands are the same structure or union type, the result is that 8650 // type. 8651 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8652 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8653 if (LHSRT->getDecl() == RHSRT->getDecl()) 8654 // "If both the operands have structure or union type, the result has 8655 // that type." This implies that CV qualifiers are dropped. 8656 return LHSTy.getUnqualifiedType(); 8657 // FIXME: Type of conditional expression must be complete in C mode. 8658 } 8659 8660 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8661 // The following || allows only one side to be void (a GCC-ism). 8662 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8663 return checkConditionalVoidType(*this, LHS, RHS); 8664 } 8665 8666 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8667 // the type of the other operand." 8668 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8669 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8670 8671 // All objective-c pointer type analysis is done here. 8672 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8673 QuestionLoc); 8674 if (LHS.isInvalid() || RHS.isInvalid()) 8675 return QualType(); 8676 if (!compositeType.isNull()) 8677 return compositeType; 8678 8679 8680 // Handle block pointer types. 8681 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8682 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8683 QuestionLoc); 8684 8685 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8686 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8687 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8688 QuestionLoc); 8689 8690 // GCC compatibility: soften pointer/integer mismatch. Note that 8691 // null pointers have been filtered out by this point. 8692 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8693 /*IsIntFirstExpr=*/true)) 8694 return RHSTy; 8695 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8696 /*IsIntFirstExpr=*/false)) 8697 return LHSTy; 8698 8699 // Allow ?: operations in which both operands have the same 8700 // built-in sizeless type. 8701 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) 8702 return LHSTy; 8703 8704 // Emit a better diagnostic if one of the expressions is a null pointer 8705 // constant and the other is not a pointer type. In this case, the user most 8706 // likely forgot to take the address of the other expression. 8707 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8708 return QualType(); 8709 8710 // Otherwise, the operands are not compatible. 8711 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8712 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8713 << RHS.get()->getSourceRange(); 8714 return QualType(); 8715 } 8716 8717 /// FindCompositeObjCPointerType - Helper method to find composite type of 8718 /// two objective-c pointer types of the two input expressions. 8719 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8720 SourceLocation QuestionLoc) { 8721 QualType LHSTy = LHS.get()->getType(); 8722 QualType RHSTy = RHS.get()->getType(); 8723 8724 // Handle things like Class and struct objc_class*. Here we case the result 8725 // to the pseudo-builtin, because that will be implicitly cast back to the 8726 // redefinition type if an attempt is made to access its fields. 8727 if (LHSTy->isObjCClassType() && 8728 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8729 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8730 return LHSTy; 8731 } 8732 if (RHSTy->isObjCClassType() && 8733 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8734 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8735 return RHSTy; 8736 } 8737 // And the same for struct objc_object* / id 8738 if (LHSTy->isObjCIdType() && 8739 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8740 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8741 return LHSTy; 8742 } 8743 if (RHSTy->isObjCIdType() && 8744 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8745 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8746 return RHSTy; 8747 } 8748 // And the same for struct objc_selector* / SEL 8749 if (Context.isObjCSelType(LHSTy) && 8750 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8751 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8752 return LHSTy; 8753 } 8754 if (Context.isObjCSelType(RHSTy) && 8755 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8756 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8757 return RHSTy; 8758 } 8759 // Check constraints for Objective-C object pointers types. 8760 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8761 8762 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8763 // Two identical object pointer types are always compatible. 8764 return LHSTy; 8765 } 8766 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8767 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8768 QualType compositeType = LHSTy; 8769 8770 // If both operands are interfaces and either operand can be 8771 // assigned to the other, use that type as the composite 8772 // type. This allows 8773 // xxx ? (A*) a : (B*) b 8774 // where B is a subclass of A. 8775 // 8776 // Additionally, as for assignment, if either type is 'id' 8777 // allow silent coercion. Finally, if the types are 8778 // incompatible then make sure to use 'id' as the composite 8779 // type so the result is acceptable for sending messages to. 8780 8781 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8782 // It could return the composite type. 8783 if (!(compositeType = 8784 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8785 // Nothing more to do. 8786 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8787 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8788 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8789 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8790 } else if ((LHSOPT->isObjCQualifiedIdType() || 8791 RHSOPT->isObjCQualifiedIdType()) && 8792 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8793 true)) { 8794 // Need to handle "id<xx>" explicitly. 8795 // GCC allows qualified id and any Objective-C type to devolve to 8796 // id. Currently localizing to here until clear this should be 8797 // part of ObjCQualifiedIdTypesAreCompatible. 8798 compositeType = Context.getObjCIdType(); 8799 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8800 compositeType = Context.getObjCIdType(); 8801 } else { 8802 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8803 << LHSTy << RHSTy 8804 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8805 QualType incompatTy = Context.getObjCIdType(); 8806 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8807 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8808 return incompatTy; 8809 } 8810 // The object pointer types are compatible. 8811 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8812 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8813 return compositeType; 8814 } 8815 // Check Objective-C object pointer types and 'void *' 8816 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8817 if (getLangOpts().ObjCAutoRefCount) { 8818 // ARC forbids the implicit conversion of object pointers to 'void *', 8819 // so these types are not compatible. 8820 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8821 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8822 LHS = RHS = true; 8823 return QualType(); 8824 } 8825 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8826 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8827 QualType destPointee 8828 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8829 QualType destType = Context.getPointerType(destPointee); 8830 // Add qualifiers if necessary. 8831 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8832 // Promote to void*. 8833 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8834 return destType; 8835 } 8836 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8837 if (getLangOpts().ObjCAutoRefCount) { 8838 // ARC forbids the implicit conversion of object pointers to 'void *', 8839 // so these types are not compatible. 8840 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8841 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8842 LHS = RHS = true; 8843 return QualType(); 8844 } 8845 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8846 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8847 QualType destPointee 8848 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8849 QualType destType = Context.getPointerType(destPointee); 8850 // Add qualifiers if necessary. 8851 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8852 // Promote to void*. 8853 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8854 return destType; 8855 } 8856 return QualType(); 8857 } 8858 8859 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8860 /// ParenRange in parentheses. 8861 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8862 const PartialDiagnostic &Note, 8863 SourceRange ParenRange) { 8864 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8865 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8866 EndLoc.isValid()) { 8867 Self.Diag(Loc, Note) 8868 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8869 << FixItHint::CreateInsertion(EndLoc, ")"); 8870 } else { 8871 // We can't display the parentheses, so just show the bare note. 8872 Self.Diag(Loc, Note) << ParenRange; 8873 } 8874 } 8875 8876 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8877 return BinaryOperator::isAdditiveOp(Opc) || 8878 BinaryOperator::isMultiplicativeOp(Opc) || 8879 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8880 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8881 // not any of the logical operators. Bitwise-xor is commonly used as a 8882 // logical-xor because there is no logical-xor operator. The logical 8883 // operators, including uses of xor, have a high false positive rate for 8884 // precedence warnings. 8885 } 8886 8887 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8888 /// expression, either using a built-in or overloaded operator, 8889 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8890 /// expression. 8891 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8892 Expr **RHSExprs) { 8893 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8894 E = E->IgnoreImpCasts(); 8895 E = E->IgnoreConversionOperatorSingleStep(); 8896 E = E->IgnoreImpCasts(); 8897 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8898 E = MTE->getSubExpr(); 8899 E = E->IgnoreImpCasts(); 8900 } 8901 8902 // Built-in binary operator. 8903 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8904 if (IsArithmeticOp(OP->getOpcode())) { 8905 *Opcode = OP->getOpcode(); 8906 *RHSExprs = OP->getRHS(); 8907 return true; 8908 } 8909 } 8910 8911 // Overloaded operator. 8912 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8913 if (Call->getNumArgs() != 2) 8914 return false; 8915 8916 // Make sure this is really a binary operator that is safe to pass into 8917 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8918 OverloadedOperatorKind OO = Call->getOperator(); 8919 if (OO < OO_Plus || OO > OO_Arrow || 8920 OO == OO_PlusPlus || OO == OO_MinusMinus) 8921 return false; 8922 8923 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8924 if (IsArithmeticOp(OpKind)) { 8925 *Opcode = OpKind; 8926 *RHSExprs = Call->getArg(1); 8927 return true; 8928 } 8929 } 8930 8931 return false; 8932 } 8933 8934 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8935 /// or is a logical expression such as (x==y) which has int type, but is 8936 /// commonly interpreted as boolean. 8937 static bool ExprLooksBoolean(Expr *E) { 8938 E = E->IgnoreParenImpCasts(); 8939 8940 if (E->getType()->isBooleanType()) 8941 return true; 8942 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8943 return OP->isComparisonOp() || OP->isLogicalOp(); 8944 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8945 return OP->getOpcode() == UO_LNot; 8946 if (E->getType()->isPointerType()) 8947 return true; 8948 // FIXME: What about overloaded operator calls returning "unspecified boolean 8949 // type"s (commonly pointer-to-members)? 8950 8951 return false; 8952 } 8953 8954 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8955 /// and binary operator are mixed in a way that suggests the programmer assumed 8956 /// the conditional operator has higher precedence, for example: 8957 /// "int x = a + someBinaryCondition ? 1 : 2". 8958 static void DiagnoseConditionalPrecedence(Sema &Self, 8959 SourceLocation OpLoc, 8960 Expr *Condition, 8961 Expr *LHSExpr, 8962 Expr *RHSExpr) { 8963 BinaryOperatorKind CondOpcode; 8964 Expr *CondRHS; 8965 8966 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8967 return; 8968 if (!ExprLooksBoolean(CondRHS)) 8969 return; 8970 8971 // The condition is an arithmetic binary expression, with a right- 8972 // hand side that looks boolean, so warn. 8973 8974 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8975 ? diag::warn_precedence_bitwise_conditional 8976 : diag::warn_precedence_conditional; 8977 8978 Self.Diag(OpLoc, DiagID) 8979 << Condition->getSourceRange() 8980 << BinaryOperator::getOpcodeStr(CondOpcode); 8981 8982 SuggestParentheses( 8983 Self, OpLoc, 8984 Self.PDiag(diag::note_precedence_silence) 8985 << BinaryOperator::getOpcodeStr(CondOpcode), 8986 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8987 8988 SuggestParentheses(Self, OpLoc, 8989 Self.PDiag(diag::note_precedence_conditional_first), 8990 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8991 } 8992 8993 /// Compute the nullability of a conditional expression. 8994 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8995 QualType LHSTy, QualType RHSTy, 8996 ASTContext &Ctx) { 8997 if (!ResTy->isAnyPointerType()) 8998 return ResTy; 8999 9000 auto GetNullability = [&Ctx](QualType Ty) { 9001 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 9002 if (Kind) { 9003 // For our purposes, treat _Nullable_result as _Nullable. 9004 if (*Kind == NullabilityKind::NullableResult) 9005 return NullabilityKind::Nullable; 9006 return *Kind; 9007 } 9008 return NullabilityKind::Unspecified; 9009 }; 9010 9011 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 9012 NullabilityKind MergedKind; 9013 9014 // Compute nullability of a binary conditional expression. 9015 if (IsBin) { 9016 if (LHSKind == NullabilityKind::NonNull) 9017 MergedKind = NullabilityKind::NonNull; 9018 else 9019 MergedKind = RHSKind; 9020 // Compute nullability of a normal conditional expression. 9021 } else { 9022 if (LHSKind == NullabilityKind::Nullable || 9023 RHSKind == NullabilityKind::Nullable) 9024 MergedKind = NullabilityKind::Nullable; 9025 else if (LHSKind == NullabilityKind::NonNull) 9026 MergedKind = RHSKind; 9027 else if (RHSKind == NullabilityKind::NonNull) 9028 MergedKind = LHSKind; 9029 else 9030 MergedKind = NullabilityKind::Unspecified; 9031 } 9032 9033 // Return if ResTy already has the correct nullability. 9034 if (GetNullability(ResTy) == MergedKind) 9035 return ResTy; 9036 9037 // Strip all nullability from ResTy. 9038 while (ResTy->getNullability(Ctx)) 9039 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 9040 9041 // Create a new AttributedType with the new nullability kind. 9042 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 9043 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 9044 } 9045 9046 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 9047 /// in the case of a the GNU conditional expr extension. 9048 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 9049 SourceLocation ColonLoc, 9050 Expr *CondExpr, Expr *LHSExpr, 9051 Expr *RHSExpr) { 9052 if (!Context.isDependenceAllowed()) { 9053 // C cannot handle TypoExpr nodes in the condition because it 9054 // doesn't handle dependent types properly, so make sure any TypoExprs have 9055 // been dealt with before checking the operands. 9056 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 9057 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 9058 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 9059 9060 if (!CondResult.isUsable()) 9061 return ExprError(); 9062 9063 if (LHSExpr) { 9064 if (!LHSResult.isUsable()) 9065 return ExprError(); 9066 } 9067 9068 if (!RHSResult.isUsable()) 9069 return ExprError(); 9070 9071 CondExpr = CondResult.get(); 9072 LHSExpr = LHSResult.get(); 9073 RHSExpr = RHSResult.get(); 9074 } 9075 9076 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 9077 // was the condition. 9078 OpaqueValueExpr *opaqueValue = nullptr; 9079 Expr *commonExpr = nullptr; 9080 if (!LHSExpr) { 9081 commonExpr = CondExpr; 9082 // Lower out placeholder types first. This is important so that we don't 9083 // try to capture a placeholder. This happens in few cases in C++; such 9084 // as Objective-C++'s dictionary subscripting syntax. 9085 if (commonExpr->hasPlaceholderType()) { 9086 ExprResult result = CheckPlaceholderExpr(commonExpr); 9087 if (!result.isUsable()) return ExprError(); 9088 commonExpr = result.get(); 9089 } 9090 // We usually want to apply unary conversions *before* saving, except 9091 // in the special case of a C++ l-value conditional. 9092 if (!(getLangOpts().CPlusPlus 9093 && !commonExpr->isTypeDependent() 9094 && commonExpr->getValueKind() == RHSExpr->getValueKind() 9095 && commonExpr->isGLValue() 9096 && commonExpr->isOrdinaryOrBitFieldObject() 9097 && RHSExpr->isOrdinaryOrBitFieldObject() 9098 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 9099 ExprResult commonRes = UsualUnaryConversions(commonExpr); 9100 if (commonRes.isInvalid()) 9101 return ExprError(); 9102 commonExpr = commonRes.get(); 9103 } 9104 9105 // If the common expression is a class or array prvalue, materialize it 9106 // so that we can safely refer to it multiple times. 9107 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 9108 commonExpr->getType()->isArrayType())) { 9109 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 9110 if (MatExpr.isInvalid()) 9111 return ExprError(); 9112 commonExpr = MatExpr.get(); 9113 } 9114 9115 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 9116 commonExpr->getType(), 9117 commonExpr->getValueKind(), 9118 commonExpr->getObjectKind(), 9119 commonExpr); 9120 LHSExpr = CondExpr = opaqueValue; 9121 } 9122 9123 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 9124 ExprValueKind VK = VK_PRValue; 9125 ExprObjectKind OK = OK_Ordinary; 9126 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 9127 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 9128 VK, OK, QuestionLoc); 9129 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 9130 RHS.isInvalid()) 9131 return ExprError(); 9132 9133 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 9134 RHS.get()); 9135 9136 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 9137 9138 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 9139 Context); 9140 9141 if (!commonExpr) 9142 return new (Context) 9143 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 9144 RHS.get(), result, VK, OK); 9145 9146 return new (Context) BinaryConditionalOperator( 9147 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 9148 ColonLoc, result, VK, OK); 9149 } 9150 9151 // Check if we have a conversion between incompatible cmse function pointer 9152 // types, that is, a conversion between a function pointer with the 9153 // cmse_nonsecure_call attribute and one without. 9154 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 9155 QualType ToType) { 9156 if (const auto *ToFn = 9157 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 9158 if (const auto *FromFn = 9159 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 9160 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 9161 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 9162 9163 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 9164 } 9165 } 9166 return false; 9167 } 9168 9169 // checkPointerTypesForAssignment - This is a very tricky routine (despite 9170 // being closely modeled after the C99 spec:-). The odd characteristic of this 9171 // routine is it effectively iqnores the qualifiers on the top level pointee. 9172 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 9173 // FIXME: add a couple examples in this comment. 9174 static Sema::AssignConvertType 9175 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 9176 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9177 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9178 9179 // get the "pointed to" type (ignoring qualifiers at the top level) 9180 const Type *lhptee, *rhptee; 9181 Qualifiers lhq, rhq; 9182 std::tie(lhptee, lhq) = 9183 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 9184 std::tie(rhptee, rhq) = 9185 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 9186 9187 Sema::AssignConvertType ConvTy = Sema::Compatible; 9188 9189 // C99 6.5.16.1p1: This following citation is common to constraints 9190 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 9191 // qualifiers of the type *pointed to* by the right; 9192 9193 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 9194 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 9195 lhq.compatiblyIncludesObjCLifetime(rhq)) { 9196 // Ignore lifetime for further calculation. 9197 lhq.removeObjCLifetime(); 9198 rhq.removeObjCLifetime(); 9199 } 9200 9201 if (!lhq.compatiblyIncludes(rhq)) { 9202 // Treat address-space mismatches as fatal. 9203 if (!lhq.isAddressSpaceSupersetOf(rhq)) 9204 return Sema::IncompatiblePointerDiscardsQualifiers; 9205 9206 // It's okay to add or remove GC or lifetime qualifiers when converting to 9207 // and from void*. 9208 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 9209 .compatiblyIncludes( 9210 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 9211 && (lhptee->isVoidType() || rhptee->isVoidType())) 9212 ; // keep old 9213 9214 // Treat lifetime mismatches as fatal. 9215 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 9216 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 9217 9218 // For GCC/MS compatibility, other qualifier mismatches are treated 9219 // as still compatible in C. 9220 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9221 } 9222 9223 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 9224 // incomplete type and the other is a pointer to a qualified or unqualified 9225 // version of void... 9226 if (lhptee->isVoidType()) { 9227 if (rhptee->isIncompleteOrObjectType()) 9228 return ConvTy; 9229 9230 // As an extension, we allow cast to/from void* to function pointer. 9231 assert(rhptee->isFunctionType()); 9232 return Sema::FunctionVoidPointer; 9233 } 9234 9235 if (rhptee->isVoidType()) { 9236 if (lhptee->isIncompleteOrObjectType()) 9237 return ConvTy; 9238 9239 // As an extension, we allow cast to/from void* to function pointer. 9240 assert(lhptee->isFunctionType()); 9241 return Sema::FunctionVoidPointer; 9242 } 9243 9244 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 9245 // unqualified versions of compatible types, ... 9246 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 9247 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 9248 // Check if the pointee types are compatible ignoring the sign. 9249 // We explicitly check for char so that we catch "char" vs 9250 // "unsigned char" on systems where "char" is unsigned. 9251 if (lhptee->isCharType()) 9252 ltrans = S.Context.UnsignedCharTy; 9253 else if (lhptee->hasSignedIntegerRepresentation()) 9254 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 9255 9256 if (rhptee->isCharType()) 9257 rtrans = S.Context.UnsignedCharTy; 9258 else if (rhptee->hasSignedIntegerRepresentation()) 9259 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 9260 9261 if (ltrans == rtrans) { 9262 // Types are compatible ignoring the sign. Qualifier incompatibility 9263 // takes priority over sign incompatibility because the sign 9264 // warning can be disabled. 9265 if (ConvTy != Sema::Compatible) 9266 return ConvTy; 9267 9268 return Sema::IncompatiblePointerSign; 9269 } 9270 9271 // If we are a multi-level pointer, it's possible that our issue is simply 9272 // one of qualification - e.g. char ** -> const char ** is not allowed. If 9273 // the eventual target type is the same and the pointers have the same 9274 // level of indirection, this must be the issue. 9275 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 9276 do { 9277 std::tie(lhptee, lhq) = 9278 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 9279 std::tie(rhptee, rhq) = 9280 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 9281 9282 // Inconsistent address spaces at this point is invalid, even if the 9283 // address spaces would be compatible. 9284 // FIXME: This doesn't catch address space mismatches for pointers of 9285 // different nesting levels, like: 9286 // __local int *** a; 9287 // int ** b = a; 9288 // It's not clear how to actually determine when such pointers are 9289 // invalidly incompatible. 9290 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 9291 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 9292 9293 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 9294 9295 if (lhptee == rhptee) 9296 return Sema::IncompatibleNestedPointerQualifiers; 9297 } 9298 9299 // General pointer incompatibility takes priority over qualifiers. 9300 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9301 return Sema::IncompatibleFunctionPointer; 9302 return Sema::IncompatiblePointer; 9303 } 9304 if (!S.getLangOpts().CPlusPlus && 9305 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9306 return Sema::IncompatibleFunctionPointer; 9307 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9308 return Sema::IncompatibleFunctionPointer; 9309 return ConvTy; 9310 } 9311 9312 /// checkBlockPointerTypesForAssignment - This routine determines whether two 9313 /// block pointer types are compatible or whether a block and normal pointer 9314 /// are compatible. It is more restrict than comparing two function pointer 9315 // types. 9316 static Sema::AssignConvertType 9317 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9318 QualType RHSType) { 9319 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9320 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9321 9322 QualType lhptee, rhptee; 9323 9324 // get the "pointed to" type (ignoring qualifiers at the top level) 9325 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9326 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9327 9328 // In C++, the types have to match exactly. 9329 if (S.getLangOpts().CPlusPlus) 9330 return Sema::IncompatibleBlockPointer; 9331 9332 Sema::AssignConvertType ConvTy = Sema::Compatible; 9333 9334 // For blocks we enforce that qualifiers are identical. 9335 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9336 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9337 if (S.getLangOpts().OpenCL) { 9338 LQuals.removeAddressSpace(); 9339 RQuals.removeAddressSpace(); 9340 } 9341 if (LQuals != RQuals) 9342 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9343 9344 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9345 // assignment. 9346 // The current behavior is similar to C++ lambdas. A block might be 9347 // assigned to a variable iff its return type and parameters are compatible 9348 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9349 // an assignment. Presumably it should behave in way that a function pointer 9350 // assignment does in C, so for each parameter and return type: 9351 // * CVR and address space of LHS should be a superset of CVR and address 9352 // space of RHS. 9353 // * unqualified types should be compatible. 9354 if (S.getLangOpts().OpenCL) { 9355 if (!S.Context.typesAreBlockPointerCompatible( 9356 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9357 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9358 return Sema::IncompatibleBlockPointer; 9359 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9360 return Sema::IncompatibleBlockPointer; 9361 9362 return ConvTy; 9363 } 9364 9365 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9366 /// for assignment compatibility. 9367 static Sema::AssignConvertType 9368 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9369 QualType RHSType) { 9370 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9371 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9372 9373 if (LHSType->isObjCBuiltinType()) { 9374 // Class is not compatible with ObjC object pointers. 9375 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9376 !RHSType->isObjCQualifiedClassType()) 9377 return Sema::IncompatiblePointer; 9378 return Sema::Compatible; 9379 } 9380 if (RHSType->isObjCBuiltinType()) { 9381 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9382 !LHSType->isObjCQualifiedClassType()) 9383 return Sema::IncompatiblePointer; 9384 return Sema::Compatible; 9385 } 9386 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9387 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9388 9389 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9390 // make an exception for id<P> 9391 !LHSType->isObjCQualifiedIdType()) 9392 return Sema::CompatiblePointerDiscardsQualifiers; 9393 9394 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9395 return Sema::Compatible; 9396 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9397 return Sema::IncompatibleObjCQualifiedId; 9398 return Sema::IncompatiblePointer; 9399 } 9400 9401 Sema::AssignConvertType 9402 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9403 QualType LHSType, QualType RHSType) { 9404 // Fake up an opaque expression. We don't actually care about what 9405 // cast operations are required, so if CheckAssignmentConstraints 9406 // adds casts to this they'll be wasted, but fortunately that doesn't 9407 // usually happen on valid code. 9408 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 9409 ExprResult RHSPtr = &RHSExpr; 9410 CastKind K; 9411 9412 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9413 } 9414 9415 /// This helper function returns true if QT is a vector type that has element 9416 /// type ElementType. 9417 static bool isVector(QualType QT, QualType ElementType) { 9418 if (const VectorType *VT = QT->getAs<VectorType>()) 9419 return VT->getElementType().getCanonicalType() == ElementType; 9420 return false; 9421 } 9422 9423 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9424 /// has code to accommodate several GCC extensions when type checking 9425 /// pointers. Here are some objectionable examples that GCC considers warnings: 9426 /// 9427 /// int a, *pint; 9428 /// short *pshort; 9429 /// struct foo *pfoo; 9430 /// 9431 /// pint = pshort; // warning: assignment from incompatible pointer type 9432 /// a = pint; // warning: assignment makes integer from pointer without a cast 9433 /// pint = a; // warning: assignment makes pointer from integer without a cast 9434 /// pint = pfoo; // warning: assignment from incompatible pointer type 9435 /// 9436 /// As a result, the code for dealing with pointers is more complex than the 9437 /// C99 spec dictates. 9438 /// 9439 /// Sets 'Kind' for any result kind except Incompatible. 9440 Sema::AssignConvertType 9441 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9442 CastKind &Kind, bool ConvertRHS) { 9443 QualType RHSType = RHS.get()->getType(); 9444 QualType OrigLHSType = LHSType; 9445 9446 // Get canonical types. We're not formatting these types, just comparing 9447 // them. 9448 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9449 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9450 9451 // Common case: no conversion required. 9452 if (LHSType == RHSType) { 9453 Kind = CK_NoOp; 9454 return Compatible; 9455 } 9456 9457 // If the LHS has an __auto_type, there are no additional type constraints 9458 // to be worried about. 9459 if (const auto *AT = dyn_cast<AutoType>(LHSType)) { 9460 if (AT->isGNUAutoType()) { 9461 Kind = CK_NoOp; 9462 return Compatible; 9463 } 9464 } 9465 9466 // If we have an atomic type, try a non-atomic assignment, then just add an 9467 // atomic qualification step. 9468 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9469 Sema::AssignConvertType result = 9470 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9471 if (result != Compatible) 9472 return result; 9473 if (Kind != CK_NoOp && ConvertRHS) 9474 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9475 Kind = CK_NonAtomicToAtomic; 9476 return Compatible; 9477 } 9478 9479 // If the left-hand side is a reference type, then we are in a 9480 // (rare!) case where we've allowed the use of references in C, 9481 // e.g., as a parameter type in a built-in function. In this case, 9482 // just make sure that the type referenced is compatible with the 9483 // right-hand side type. The caller is responsible for adjusting 9484 // LHSType so that the resulting expression does not have reference 9485 // type. 9486 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9487 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9488 Kind = CK_LValueBitCast; 9489 return Compatible; 9490 } 9491 return Incompatible; 9492 } 9493 9494 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9495 // to the same ExtVector type. 9496 if (LHSType->isExtVectorType()) { 9497 if (RHSType->isExtVectorType()) 9498 return Incompatible; 9499 if (RHSType->isArithmeticType()) { 9500 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9501 if (ConvertRHS) 9502 RHS = prepareVectorSplat(LHSType, RHS.get()); 9503 Kind = CK_VectorSplat; 9504 return Compatible; 9505 } 9506 } 9507 9508 // Conversions to or from vector type. 9509 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9510 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9511 // Allow assignments of an AltiVec vector type to an equivalent GCC 9512 // vector type and vice versa 9513 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9514 Kind = CK_BitCast; 9515 return Compatible; 9516 } 9517 9518 // If we are allowing lax vector conversions, and LHS and RHS are both 9519 // vectors, the total size only needs to be the same. This is a bitcast; 9520 // no bits are changed but the result type is different. 9521 if (isLaxVectorConversion(RHSType, LHSType)) { 9522 Kind = CK_BitCast; 9523 return IncompatibleVectors; 9524 } 9525 } 9526 9527 // When the RHS comes from another lax conversion (e.g. binops between 9528 // scalars and vectors) the result is canonicalized as a vector. When the 9529 // LHS is also a vector, the lax is allowed by the condition above. Handle 9530 // the case where LHS is a scalar. 9531 if (LHSType->isScalarType()) { 9532 const VectorType *VecType = RHSType->getAs<VectorType>(); 9533 if (VecType && VecType->getNumElements() == 1 && 9534 isLaxVectorConversion(RHSType, LHSType)) { 9535 ExprResult *VecExpr = &RHS; 9536 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9537 Kind = CK_BitCast; 9538 return Compatible; 9539 } 9540 } 9541 9542 // Allow assignments between fixed-length and sizeless SVE vectors. 9543 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9544 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9545 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9546 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9547 Kind = CK_BitCast; 9548 return Compatible; 9549 } 9550 9551 return Incompatible; 9552 } 9553 9554 // Diagnose attempts to convert between __ibm128, __float128 and long double 9555 // where such conversions currently can't be handled. 9556 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9557 return Incompatible; 9558 9559 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9560 // discards the imaginary part. 9561 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9562 !LHSType->getAs<ComplexType>()) 9563 return Incompatible; 9564 9565 // Arithmetic conversions. 9566 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9567 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9568 if (ConvertRHS) 9569 Kind = PrepareScalarCast(RHS, LHSType); 9570 return Compatible; 9571 } 9572 9573 // Conversions to normal pointers. 9574 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9575 // U* -> T* 9576 if (isa<PointerType>(RHSType)) { 9577 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9578 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9579 if (AddrSpaceL != AddrSpaceR) 9580 Kind = CK_AddressSpaceConversion; 9581 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9582 Kind = CK_NoOp; 9583 else 9584 Kind = CK_BitCast; 9585 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9586 } 9587 9588 // int -> T* 9589 if (RHSType->isIntegerType()) { 9590 Kind = CK_IntegralToPointer; // FIXME: null? 9591 return IntToPointer; 9592 } 9593 9594 // C pointers are not compatible with ObjC object pointers, 9595 // with two exceptions: 9596 if (isa<ObjCObjectPointerType>(RHSType)) { 9597 // - conversions to void* 9598 if (LHSPointer->getPointeeType()->isVoidType()) { 9599 Kind = CK_BitCast; 9600 return Compatible; 9601 } 9602 9603 // - conversions from 'Class' to the redefinition type 9604 if (RHSType->isObjCClassType() && 9605 Context.hasSameType(LHSType, 9606 Context.getObjCClassRedefinitionType())) { 9607 Kind = CK_BitCast; 9608 return Compatible; 9609 } 9610 9611 Kind = CK_BitCast; 9612 return IncompatiblePointer; 9613 } 9614 9615 // U^ -> void* 9616 if (RHSType->getAs<BlockPointerType>()) { 9617 if (LHSPointer->getPointeeType()->isVoidType()) { 9618 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9619 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9620 ->getPointeeType() 9621 .getAddressSpace(); 9622 Kind = 9623 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9624 return Compatible; 9625 } 9626 } 9627 9628 return Incompatible; 9629 } 9630 9631 // Conversions to block pointers. 9632 if (isa<BlockPointerType>(LHSType)) { 9633 // U^ -> T^ 9634 if (RHSType->isBlockPointerType()) { 9635 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9636 ->getPointeeType() 9637 .getAddressSpace(); 9638 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9639 ->getPointeeType() 9640 .getAddressSpace(); 9641 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9642 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9643 } 9644 9645 // int or null -> T^ 9646 if (RHSType->isIntegerType()) { 9647 Kind = CK_IntegralToPointer; // FIXME: null 9648 return IntToBlockPointer; 9649 } 9650 9651 // id -> T^ 9652 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9653 Kind = CK_AnyPointerToBlockPointerCast; 9654 return Compatible; 9655 } 9656 9657 // void* -> T^ 9658 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9659 if (RHSPT->getPointeeType()->isVoidType()) { 9660 Kind = CK_AnyPointerToBlockPointerCast; 9661 return Compatible; 9662 } 9663 9664 return Incompatible; 9665 } 9666 9667 // Conversions to Objective-C pointers. 9668 if (isa<ObjCObjectPointerType>(LHSType)) { 9669 // A* -> B* 9670 if (RHSType->isObjCObjectPointerType()) { 9671 Kind = CK_BitCast; 9672 Sema::AssignConvertType result = 9673 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9674 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9675 result == Compatible && 9676 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9677 result = IncompatibleObjCWeakRef; 9678 return result; 9679 } 9680 9681 // int or null -> A* 9682 if (RHSType->isIntegerType()) { 9683 Kind = CK_IntegralToPointer; // FIXME: null 9684 return IntToPointer; 9685 } 9686 9687 // In general, C pointers are not compatible with ObjC object pointers, 9688 // with two exceptions: 9689 if (isa<PointerType>(RHSType)) { 9690 Kind = CK_CPointerToObjCPointerCast; 9691 9692 // - conversions from 'void*' 9693 if (RHSType->isVoidPointerType()) { 9694 return Compatible; 9695 } 9696 9697 // - conversions to 'Class' from its redefinition type 9698 if (LHSType->isObjCClassType() && 9699 Context.hasSameType(RHSType, 9700 Context.getObjCClassRedefinitionType())) { 9701 return Compatible; 9702 } 9703 9704 return IncompatiblePointer; 9705 } 9706 9707 // Only under strict condition T^ is compatible with an Objective-C pointer. 9708 if (RHSType->isBlockPointerType() && 9709 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9710 if (ConvertRHS) 9711 maybeExtendBlockObject(RHS); 9712 Kind = CK_BlockPointerToObjCPointerCast; 9713 return Compatible; 9714 } 9715 9716 return Incompatible; 9717 } 9718 9719 // Conversions from pointers that are not covered by the above. 9720 if (isa<PointerType>(RHSType)) { 9721 // T* -> _Bool 9722 if (LHSType == Context.BoolTy) { 9723 Kind = CK_PointerToBoolean; 9724 return Compatible; 9725 } 9726 9727 // T* -> int 9728 if (LHSType->isIntegerType()) { 9729 Kind = CK_PointerToIntegral; 9730 return PointerToInt; 9731 } 9732 9733 return Incompatible; 9734 } 9735 9736 // Conversions from Objective-C pointers that are not covered by the above. 9737 if (isa<ObjCObjectPointerType>(RHSType)) { 9738 // T* -> _Bool 9739 if (LHSType == Context.BoolTy) { 9740 Kind = CK_PointerToBoolean; 9741 return Compatible; 9742 } 9743 9744 // T* -> int 9745 if (LHSType->isIntegerType()) { 9746 Kind = CK_PointerToIntegral; 9747 return PointerToInt; 9748 } 9749 9750 return Incompatible; 9751 } 9752 9753 // struct A -> struct B 9754 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9755 if (Context.typesAreCompatible(LHSType, RHSType)) { 9756 Kind = CK_NoOp; 9757 return Compatible; 9758 } 9759 } 9760 9761 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9762 Kind = CK_IntToOCLSampler; 9763 return Compatible; 9764 } 9765 9766 return Incompatible; 9767 } 9768 9769 /// Constructs a transparent union from an expression that is 9770 /// used to initialize the transparent union. 9771 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9772 ExprResult &EResult, QualType UnionType, 9773 FieldDecl *Field) { 9774 // Build an initializer list that designates the appropriate member 9775 // of the transparent union. 9776 Expr *E = EResult.get(); 9777 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9778 E, SourceLocation()); 9779 Initializer->setType(UnionType); 9780 Initializer->setInitializedFieldInUnion(Field); 9781 9782 // Build a compound literal constructing a value of the transparent 9783 // union type from this initializer list. 9784 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9785 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9786 VK_PRValue, Initializer, false); 9787 } 9788 9789 Sema::AssignConvertType 9790 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9791 ExprResult &RHS) { 9792 QualType RHSType = RHS.get()->getType(); 9793 9794 // If the ArgType is a Union type, we want to handle a potential 9795 // transparent_union GCC extension. 9796 const RecordType *UT = ArgType->getAsUnionType(); 9797 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9798 return Incompatible; 9799 9800 // The field to initialize within the transparent union. 9801 RecordDecl *UD = UT->getDecl(); 9802 FieldDecl *InitField = nullptr; 9803 // It's compatible if the expression matches any of the fields. 9804 for (auto *it : UD->fields()) { 9805 if (it->getType()->isPointerType()) { 9806 // If the transparent union contains a pointer type, we allow: 9807 // 1) void pointer 9808 // 2) null pointer constant 9809 if (RHSType->isPointerType()) 9810 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9811 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9812 InitField = it; 9813 break; 9814 } 9815 9816 if (RHS.get()->isNullPointerConstant(Context, 9817 Expr::NPC_ValueDependentIsNull)) { 9818 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9819 CK_NullToPointer); 9820 InitField = it; 9821 break; 9822 } 9823 } 9824 9825 CastKind Kind; 9826 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9827 == Compatible) { 9828 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9829 InitField = it; 9830 break; 9831 } 9832 } 9833 9834 if (!InitField) 9835 return Incompatible; 9836 9837 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9838 return Compatible; 9839 } 9840 9841 Sema::AssignConvertType 9842 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9843 bool Diagnose, 9844 bool DiagnoseCFAudited, 9845 bool ConvertRHS) { 9846 // We need to be able to tell the caller whether we diagnosed a problem, if 9847 // they ask us to issue diagnostics. 9848 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9849 9850 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9851 // we can't avoid *all* modifications at the moment, so we need some somewhere 9852 // to put the updated value. 9853 ExprResult LocalRHS = CallerRHS; 9854 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9855 9856 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9857 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9858 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9859 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9860 Diag(RHS.get()->getExprLoc(), 9861 diag::warn_noderef_to_dereferenceable_pointer) 9862 << RHS.get()->getSourceRange(); 9863 } 9864 } 9865 } 9866 9867 if (getLangOpts().CPlusPlus) { 9868 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9869 // C++ 5.17p3: If the left operand is not of class type, the 9870 // expression is implicitly converted (C++ 4) to the 9871 // cv-unqualified type of the left operand. 9872 QualType RHSType = RHS.get()->getType(); 9873 if (Diagnose) { 9874 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9875 AA_Assigning); 9876 } else { 9877 ImplicitConversionSequence ICS = 9878 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9879 /*SuppressUserConversions=*/false, 9880 AllowedExplicit::None, 9881 /*InOverloadResolution=*/false, 9882 /*CStyle=*/false, 9883 /*AllowObjCWritebackConversion=*/false); 9884 if (ICS.isFailure()) 9885 return Incompatible; 9886 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9887 ICS, AA_Assigning); 9888 } 9889 if (RHS.isInvalid()) 9890 return Incompatible; 9891 Sema::AssignConvertType result = Compatible; 9892 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9893 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9894 result = IncompatibleObjCWeakRef; 9895 return result; 9896 } 9897 9898 // FIXME: Currently, we fall through and treat C++ classes like C 9899 // structures. 9900 // FIXME: We also fall through for atomics; not sure what should 9901 // happen there, though. 9902 } else if (RHS.get()->getType() == Context.OverloadTy) { 9903 // As a set of extensions to C, we support overloading on functions. These 9904 // functions need to be resolved here. 9905 DeclAccessPair DAP; 9906 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9907 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9908 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9909 else 9910 return Incompatible; 9911 } 9912 9913 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9914 // a null pointer constant. 9915 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9916 LHSType->isBlockPointerType()) && 9917 RHS.get()->isNullPointerConstant(Context, 9918 Expr::NPC_ValueDependentIsNull)) { 9919 if (Diagnose || ConvertRHS) { 9920 CastKind Kind; 9921 CXXCastPath Path; 9922 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9923 /*IgnoreBaseAccess=*/false, Diagnose); 9924 if (ConvertRHS) 9925 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 9926 } 9927 return Compatible; 9928 } 9929 9930 // OpenCL queue_t type assignment. 9931 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9932 Context, Expr::NPC_ValueDependentIsNull)) { 9933 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9934 return Compatible; 9935 } 9936 9937 // This check seems unnatural, however it is necessary to ensure the proper 9938 // conversion of functions/arrays. If the conversion were done for all 9939 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9940 // expressions that suppress this implicit conversion (&, sizeof). 9941 // 9942 // Suppress this for references: C++ 8.5.3p5. 9943 if (!LHSType->isReferenceType()) { 9944 // FIXME: We potentially allocate here even if ConvertRHS is false. 9945 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9946 if (RHS.isInvalid()) 9947 return Incompatible; 9948 } 9949 CastKind Kind; 9950 Sema::AssignConvertType result = 9951 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9952 9953 // C99 6.5.16.1p2: The value of the right operand is converted to the 9954 // type of the assignment expression. 9955 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9956 // so that we can use references in built-in functions even in C. 9957 // The getNonReferenceType() call makes sure that the resulting expression 9958 // does not have reference type. 9959 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9960 QualType Ty = LHSType.getNonLValueExprType(Context); 9961 Expr *E = RHS.get(); 9962 9963 // Check for various Objective-C errors. If we are not reporting 9964 // diagnostics and just checking for errors, e.g., during overload 9965 // resolution, return Incompatible to indicate the failure. 9966 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9967 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9968 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9969 if (!Diagnose) 9970 return Incompatible; 9971 } 9972 if (getLangOpts().ObjC && 9973 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9974 E->getType(), E, Diagnose) || 9975 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9976 if (!Diagnose) 9977 return Incompatible; 9978 // Replace the expression with a corrected version and continue so we 9979 // can find further errors. 9980 RHS = E; 9981 return Compatible; 9982 } 9983 9984 if (ConvertRHS) 9985 RHS = ImpCastExprToType(E, Ty, Kind); 9986 } 9987 9988 return result; 9989 } 9990 9991 namespace { 9992 /// The original operand to an operator, prior to the application of the usual 9993 /// arithmetic conversions and converting the arguments of a builtin operator 9994 /// candidate. 9995 struct OriginalOperand { 9996 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9997 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9998 Op = MTE->getSubExpr(); 9999 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 10000 Op = BTE->getSubExpr(); 10001 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 10002 Orig = ICE->getSubExprAsWritten(); 10003 Conversion = ICE->getConversionFunction(); 10004 } 10005 } 10006 10007 QualType getType() const { return Orig->getType(); } 10008 10009 Expr *Orig; 10010 NamedDecl *Conversion; 10011 }; 10012 } 10013 10014 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 10015 ExprResult &RHS) { 10016 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 10017 10018 Diag(Loc, diag::err_typecheck_invalid_operands) 10019 << OrigLHS.getType() << OrigRHS.getType() 10020 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10021 10022 // If a user-defined conversion was applied to either of the operands prior 10023 // to applying the built-in operator rules, tell the user about it. 10024 if (OrigLHS.Conversion) { 10025 Diag(OrigLHS.Conversion->getLocation(), 10026 diag::note_typecheck_invalid_operands_converted) 10027 << 0 << LHS.get()->getType(); 10028 } 10029 if (OrigRHS.Conversion) { 10030 Diag(OrigRHS.Conversion->getLocation(), 10031 diag::note_typecheck_invalid_operands_converted) 10032 << 1 << RHS.get()->getType(); 10033 } 10034 10035 return QualType(); 10036 } 10037 10038 // Diagnose cases where a scalar was implicitly converted to a vector and 10039 // diagnose the underlying types. Otherwise, diagnose the error 10040 // as invalid vector logical operands for non-C++ cases. 10041 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 10042 ExprResult &RHS) { 10043 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 10044 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 10045 10046 bool LHSNatVec = LHSType->isVectorType(); 10047 bool RHSNatVec = RHSType->isVectorType(); 10048 10049 if (!(LHSNatVec && RHSNatVec)) { 10050 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 10051 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 10052 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 10053 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 10054 << Vector->getSourceRange(); 10055 return QualType(); 10056 } 10057 10058 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 10059 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 10060 << RHS.get()->getSourceRange(); 10061 10062 return QualType(); 10063 } 10064 10065 /// Try to convert a value of non-vector type to a vector type by converting 10066 /// the type to the element type of the vector and then performing a splat. 10067 /// If the language is OpenCL, we only use conversions that promote scalar 10068 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 10069 /// for float->int. 10070 /// 10071 /// OpenCL V2.0 6.2.6.p2: 10072 /// An error shall occur if any scalar operand type has greater rank 10073 /// than the type of the vector element. 10074 /// 10075 /// \param scalar - if non-null, actually perform the conversions 10076 /// \return true if the operation fails (but without diagnosing the failure) 10077 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 10078 QualType scalarTy, 10079 QualType vectorEltTy, 10080 QualType vectorTy, 10081 unsigned &DiagID) { 10082 // The conversion to apply to the scalar before splatting it, 10083 // if necessary. 10084 CastKind scalarCast = CK_NoOp; 10085 10086 if (vectorEltTy->isIntegralType(S.Context)) { 10087 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 10088 (scalarTy->isIntegerType() && 10089 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 10090 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 10091 return true; 10092 } 10093 if (!scalarTy->isIntegralType(S.Context)) 10094 return true; 10095 scalarCast = CK_IntegralCast; 10096 } else if (vectorEltTy->isRealFloatingType()) { 10097 if (scalarTy->isRealFloatingType()) { 10098 if (S.getLangOpts().OpenCL && 10099 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 10100 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 10101 return true; 10102 } 10103 scalarCast = CK_FloatingCast; 10104 } 10105 else if (scalarTy->isIntegralType(S.Context)) 10106 scalarCast = CK_IntegralToFloating; 10107 else 10108 return true; 10109 } else { 10110 return true; 10111 } 10112 10113 // Adjust scalar if desired. 10114 if (scalar) { 10115 if (scalarCast != CK_NoOp) 10116 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 10117 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 10118 } 10119 return false; 10120 } 10121 10122 /// Convert vector E to a vector with the same number of elements but different 10123 /// element type. 10124 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 10125 const auto *VecTy = E->getType()->getAs<VectorType>(); 10126 assert(VecTy && "Expression E must be a vector"); 10127 QualType NewVecTy = 10128 VecTy->isExtVectorType() 10129 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements()) 10130 : S.Context.getVectorType(ElementType, VecTy->getNumElements(), 10131 VecTy->getVectorKind()); 10132 10133 // Look through the implicit cast. Return the subexpression if its type is 10134 // NewVecTy. 10135 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10136 if (ICE->getSubExpr()->getType() == NewVecTy) 10137 return ICE->getSubExpr(); 10138 10139 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 10140 return S.ImpCastExprToType(E, NewVecTy, Cast); 10141 } 10142 10143 /// Test if a (constant) integer Int can be casted to another integer type 10144 /// IntTy without losing precision. 10145 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 10146 QualType OtherIntTy) { 10147 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 10148 10149 // Reject cases where the value of the Int is unknown as that would 10150 // possibly cause truncation, but accept cases where the scalar can be 10151 // demoted without loss of precision. 10152 Expr::EvalResult EVResult; 10153 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 10154 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 10155 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 10156 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 10157 10158 if (CstInt) { 10159 // If the scalar is constant and is of a higher order and has more active 10160 // bits that the vector element type, reject it. 10161 llvm::APSInt Result = EVResult.Val.getInt(); 10162 unsigned NumBits = IntSigned 10163 ? (Result.isNegative() ? Result.getMinSignedBits() 10164 : Result.getActiveBits()) 10165 : Result.getActiveBits(); 10166 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 10167 return true; 10168 10169 // If the signedness of the scalar type and the vector element type 10170 // differs and the number of bits is greater than that of the vector 10171 // element reject it. 10172 return (IntSigned != OtherIntSigned && 10173 NumBits > S.Context.getIntWidth(OtherIntTy)); 10174 } 10175 10176 // Reject cases where the value of the scalar is not constant and it's 10177 // order is greater than that of the vector element type. 10178 return (Order < 0); 10179 } 10180 10181 /// Test if a (constant) integer Int can be casted to floating point type 10182 /// FloatTy without losing precision. 10183 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 10184 QualType FloatTy) { 10185 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 10186 10187 // Determine if the integer constant can be expressed as a floating point 10188 // number of the appropriate type. 10189 Expr::EvalResult EVResult; 10190 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 10191 10192 uint64_t Bits = 0; 10193 if (CstInt) { 10194 // Reject constants that would be truncated if they were converted to 10195 // the floating point type. Test by simple to/from conversion. 10196 // FIXME: Ideally the conversion to an APFloat and from an APFloat 10197 // could be avoided if there was a convertFromAPInt method 10198 // which could signal back if implicit truncation occurred. 10199 llvm::APSInt Result = EVResult.Val.getInt(); 10200 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 10201 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 10202 llvm::APFloat::rmTowardZero); 10203 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 10204 !IntTy->hasSignedIntegerRepresentation()); 10205 bool Ignored = false; 10206 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 10207 &Ignored); 10208 if (Result != ConvertBack) 10209 return true; 10210 } else { 10211 // Reject types that cannot be fully encoded into the mantissa of 10212 // the float. 10213 Bits = S.Context.getTypeSize(IntTy); 10214 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 10215 S.Context.getFloatTypeSemantics(FloatTy)); 10216 if (Bits > FloatPrec) 10217 return true; 10218 } 10219 10220 return false; 10221 } 10222 10223 /// Attempt to convert and splat Scalar into a vector whose types matches 10224 /// Vector following GCC conversion rules. The rule is that implicit 10225 /// conversion can occur when Scalar can be casted to match Vector's element 10226 /// type without causing truncation of Scalar. 10227 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 10228 ExprResult *Vector) { 10229 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 10230 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 10231 const auto *VT = VectorTy->castAs<VectorType>(); 10232 10233 assert(!isa<ExtVectorType>(VT) && 10234 "ExtVectorTypes should not be handled here!"); 10235 10236 QualType VectorEltTy = VT->getElementType(); 10237 10238 // Reject cases where the vector element type or the scalar element type are 10239 // not integral or floating point types. 10240 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 10241 return true; 10242 10243 // The conversion to apply to the scalar before splatting it, 10244 // if necessary. 10245 CastKind ScalarCast = CK_NoOp; 10246 10247 // Accept cases where the vector elements are integers and the scalar is 10248 // an integer. 10249 // FIXME: Notionally if the scalar was a floating point value with a precise 10250 // integral representation, we could cast it to an appropriate integer 10251 // type and then perform the rest of the checks here. GCC will perform 10252 // this conversion in some cases as determined by the input language. 10253 // We should accept it on a language independent basis. 10254 if (VectorEltTy->isIntegralType(S.Context) && 10255 ScalarTy->isIntegralType(S.Context) && 10256 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 10257 10258 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 10259 return true; 10260 10261 ScalarCast = CK_IntegralCast; 10262 } else if (VectorEltTy->isIntegralType(S.Context) && 10263 ScalarTy->isRealFloatingType()) { 10264 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 10265 ScalarCast = CK_FloatingToIntegral; 10266 else 10267 return true; 10268 } else if (VectorEltTy->isRealFloatingType()) { 10269 if (ScalarTy->isRealFloatingType()) { 10270 10271 // Reject cases where the scalar type is not a constant and has a higher 10272 // Order than the vector element type. 10273 llvm::APFloat Result(0.0); 10274 10275 // Determine whether this is a constant scalar. In the event that the 10276 // value is dependent (and thus cannot be evaluated by the constant 10277 // evaluator), skip the evaluation. This will then diagnose once the 10278 // expression is instantiated. 10279 bool CstScalar = Scalar->get()->isValueDependent() || 10280 Scalar->get()->EvaluateAsFloat(Result, S.Context); 10281 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 10282 if (!CstScalar && Order < 0) 10283 return true; 10284 10285 // If the scalar cannot be safely casted to the vector element type, 10286 // reject it. 10287 if (CstScalar) { 10288 bool Truncated = false; 10289 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 10290 llvm::APFloat::rmNearestTiesToEven, &Truncated); 10291 if (Truncated) 10292 return true; 10293 } 10294 10295 ScalarCast = CK_FloatingCast; 10296 } else if (ScalarTy->isIntegralType(S.Context)) { 10297 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 10298 return true; 10299 10300 ScalarCast = CK_IntegralToFloating; 10301 } else 10302 return true; 10303 } else if (ScalarTy->isEnumeralType()) 10304 return true; 10305 10306 // Adjust scalar if desired. 10307 if (Scalar) { 10308 if (ScalarCast != CK_NoOp) 10309 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 10310 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 10311 } 10312 return false; 10313 } 10314 10315 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 10316 SourceLocation Loc, bool IsCompAssign, 10317 bool AllowBothBool, 10318 bool AllowBoolConversions, 10319 bool AllowBoolOperation, 10320 bool ReportInvalid) { 10321 if (!IsCompAssign) { 10322 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10323 if (LHS.isInvalid()) 10324 return QualType(); 10325 } 10326 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10327 if (RHS.isInvalid()) 10328 return QualType(); 10329 10330 // For conversion purposes, we ignore any qualifiers. 10331 // For example, "const float" and "float" are equivalent. 10332 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10333 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10334 10335 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10336 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10337 assert(LHSVecType || RHSVecType); 10338 10339 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10340 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10341 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); 10342 10343 // AltiVec-style "vector bool op vector bool" combinations are allowed 10344 // for some operators but not others. 10345 if (!AllowBothBool && 10346 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10347 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10348 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); 10349 10350 // This operation may not be performed on boolean vectors. 10351 if (!AllowBoolOperation && 10352 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType())) 10353 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); 10354 10355 // If the vector types are identical, return. 10356 if (Context.hasSameType(LHSType, RHSType)) 10357 return LHSType; 10358 10359 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10360 if (LHSVecType && RHSVecType && 10361 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10362 if (isa<ExtVectorType>(LHSVecType)) { 10363 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10364 return LHSType; 10365 } 10366 10367 if (!IsCompAssign) 10368 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10369 return RHSType; 10370 } 10371 10372 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10373 // can be mixed, with the result being the non-bool type. The non-bool 10374 // operand must have integer element type. 10375 if (AllowBoolConversions && LHSVecType && RHSVecType && 10376 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10377 (Context.getTypeSize(LHSVecType->getElementType()) == 10378 Context.getTypeSize(RHSVecType->getElementType()))) { 10379 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10380 LHSVecType->getElementType()->isIntegerType() && 10381 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10382 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10383 return LHSType; 10384 } 10385 if (!IsCompAssign && 10386 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10387 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10388 RHSVecType->getElementType()->isIntegerType()) { 10389 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10390 return RHSType; 10391 } 10392 } 10393 10394 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10395 // since the ambiguity can affect the ABI. 10396 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10397 const VectorType *VecType = SecondType->getAs<VectorType>(); 10398 return FirstType->isSizelessBuiltinType() && VecType && 10399 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10400 VecType->getVectorKind() == 10401 VectorType::SveFixedLengthPredicateVector); 10402 }; 10403 10404 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10405 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10406 return QualType(); 10407 } 10408 10409 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10410 // since the ambiguity can affect the ABI. 10411 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10412 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10413 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10414 10415 if (FirstVecType && SecondVecType) 10416 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10417 (SecondVecType->getVectorKind() == 10418 VectorType::SveFixedLengthDataVector || 10419 SecondVecType->getVectorKind() == 10420 VectorType::SveFixedLengthPredicateVector); 10421 10422 return FirstType->isSizelessBuiltinType() && SecondVecType && 10423 SecondVecType->getVectorKind() == VectorType::GenericVector; 10424 }; 10425 10426 if (IsSveGnuConversion(LHSType, RHSType) || 10427 IsSveGnuConversion(RHSType, LHSType)) { 10428 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10429 return QualType(); 10430 } 10431 10432 // If there's a vector type and a scalar, try to convert the scalar to 10433 // the vector element type and splat. 10434 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10435 if (!RHSVecType) { 10436 if (isa<ExtVectorType>(LHSVecType)) { 10437 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10438 LHSVecType->getElementType(), LHSType, 10439 DiagID)) 10440 return LHSType; 10441 } else { 10442 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10443 return LHSType; 10444 } 10445 } 10446 if (!LHSVecType) { 10447 if (isa<ExtVectorType>(RHSVecType)) { 10448 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10449 LHSType, RHSVecType->getElementType(), 10450 RHSType, DiagID)) 10451 return RHSType; 10452 } else { 10453 if (LHS.get()->isLValue() || 10454 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10455 return RHSType; 10456 } 10457 } 10458 10459 // FIXME: The code below also handles conversion between vectors and 10460 // non-scalars, we should break this down into fine grained specific checks 10461 // and emit proper diagnostics. 10462 QualType VecType = LHSVecType ? LHSType : RHSType; 10463 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10464 QualType OtherType = LHSVecType ? RHSType : LHSType; 10465 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10466 if (isLaxVectorConversion(OtherType, VecType)) { 10467 // If we're allowing lax vector conversions, only the total (data) size 10468 // needs to be the same. For non compound assignment, if one of the types is 10469 // scalar, the result is always the vector type. 10470 if (!IsCompAssign) { 10471 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10472 return VecType; 10473 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10474 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10475 // type. Note that this is already done by non-compound assignments in 10476 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10477 // <1 x T> -> T. The result is also a vector type. 10478 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10479 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10480 ExprResult *RHSExpr = &RHS; 10481 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10482 return VecType; 10483 } 10484 } 10485 10486 // Okay, the expression is invalid. 10487 10488 // If there's a non-vector, non-real operand, diagnose that. 10489 if ((!RHSVecType && !RHSType->isRealType()) || 10490 (!LHSVecType && !LHSType->isRealType())) { 10491 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10492 << LHSType << RHSType 10493 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10494 return QualType(); 10495 } 10496 10497 // OpenCL V1.1 6.2.6.p1: 10498 // If the operands are of more than one vector type, then an error shall 10499 // occur. Implicit conversions between vector types are not permitted, per 10500 // section 6.2.1. 10501 if (getLangOpts().OpenCL && 10502 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10503 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10504 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10505 << RHSType; 10506 return QualType(); 10507 } 10508 10509 10510 // If there is a vector type that is not a ExtVector and a scalar, we reach 10511 // this point if scalar could not be converted to the vector's element type 10512 // without truncation. 10513 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10514 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10515 QualType Scalar = LHSVecType ? RHSType : LHSType; 10516 QualType Vector = LHSVecType ? LHSType : RHSType; 10517 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10518 Diag(Loc, 10519 diag::err_typecheck_vector_not_convertable_implict_truncation) 10520 << ScalarOrVector << Scalar << Vector; 10521 10522 return QualType(); 10523 } 10524 10525 // Otherwise, use the generic diagnostic. 10526 Diag(Loc, DiagID) 10527 << LHSType << RHSType 10528 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10529 return QualType(); 10530 } 10531 10532 QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, 10533 SourceLocation Loc, 10534 bool IsCompAssign, 10535 ArithConvKind OperationKind) { 10536 if (!IsCompAssign) { 10537 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10538 if (LHS.isInvalid()) 10539 return QualType(); 10540 } 10541 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10542 if (RHS.isInvalid()) 10543 return QualType(); 10544 10545 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10546 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10547 10548 unsigned DiagID = diag::err_typecheck_invalid_operands; 10549 if ((OperationKind == ACK_Arithmetic) && 10550 (LHSType->castAs<BuiltinType>()->isSVEBool() || 10551 RHSType->castAs<BuiltinType>()->isSVEBool())) { 10552 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 10553 << RHS.get()->getSourceRange(); 10554 return QualType(); 10555 } 10556 10557 if (Context.hasSameType(LHSType, RHSType)) 10558 return LHSType; 10559 10560 auto tryScalableVectorConvert = [this](ExprResult *Src, QualType SrcType, 10561 QualType DestType) { 10562 const QualType DestBaseType = DestType->getSveEltType(Context); 10563 if (DestBaseType->getUnqualifiedDesugaredType() == 10564 SrcType->getUnqualifiedDesugaredType()) { 10565 unsigned DiagID = diag::err_typecheck_invalid_operands; 10566 if (!tryVectorConvertAndSplat(*this, Src, SrcType, DestBaseType, DestType, 10567 DiagID)) 10568 return DestType; 10569 } 10570 return QualType(); 10571 }; 10572 10573 if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) { 10574 auto DestType = tryScalableVectorConvert(&RHS, RHSType, LHSType); 10575 if (DestType == QualType()) 10576 return InvalidOperands(Loc, LHS, RHS); 10577 return DestType; 10578 } 10579 10580 if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) { 10581 auto DestType = tryScalableVectorConvert((IsCompAssign ? nullptr : &LHS), 10582 LHSType, RHSType); 10583 if (DestType == QualType()) 10584 return InvalidOperands(Loc, LHS, RHS); 10585 return DestType; 10586 } 10587 10588 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 10589 << RHS.get()->getSourceRange(); 10590 return QualType(); 10591 } 10592 10593 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10594 // expression. These are mainly cases where the null pointer is used as an 10595 // integer instead of a pointer. 10596 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10597 SourceLocation Loc, bool IsCompare) { 10598 // The canonical way to check for a GNU null is with isNullPointerConstant, 10599 // but we use a bit of a hack here for speed; this is a relatively 10600 // hot path, and isNullPointerConstant is slow. 10601 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10602 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10603 10604 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10605 10606 // Avoid analyzing cases where the result will either be invalid (and 10607 // diagnosed as such) or entirely valid and not something to warn about. 10608 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10609 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10610 return; 10611 10612 // Comparison operations would not make sense with a null pointer no matter 10613 // what the other expression is. 10614 if (!IsCompare) { 10615 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10616 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10617 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10618 return; 10619 } 10620 10621 // The rest of the operations only make sense with a null pointer 10622 // if the other expression is a pointer. 10623 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10624 NonNullType->canDecayToPointerType()) 10625 return; 10626 10627 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10628 << LHSNull /* LHS is NULL */ << NonNullType 10629 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10630 } 10631 10632 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10633 SourceLocation Loc) { 10634 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10635 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10636 if (!LUE || !RUE) 10637 return; 10638 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10639 RUE->getKind() != UETT_SizeOf) 10640 return; 10641 10642 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10643 QualType LHSTy = LHSArg->getType(); 10644 QualType RHSTy; 10645 10646 if (RUE->isArgumentType()) 10647 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10648 else 10649 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10650 10651 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10652 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10653 return; 10654 10655 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10656 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10657 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10658 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10659 << LHSArgDecl; 10660 } 10661 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10662 QualType ArrayElemTy = ArrayTy->getElementType(); 10663 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10664 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10665 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10666 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10667 return; 10668 S.Diag(Loc, diag::warn_division_sizeof_array) 10669 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10670 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10671 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10672 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10673 << LHSArgDecl; 10674 } 10675 10676 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10677 } 10678 } 10679 10680 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10681 ExprResult &RHS, 10682 SourceLocation Loc, bool IsDiv) { 10683 // Check for division/remainder by zero. 10684 Expr::EvalResult RHSValue; 10685 if (!RHS.get()->isValueDependent() && 10686 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10687 RHSValue.Val.getInt() == 0) 10688 S.DiagRuntimeBehavior(Loc, RHS.get(), 10689 S.PDiag(diag::warn_remainder_division_by_zero) 10690 << IsDiv << RHS.get()->getSourceRange()); 10691 } 10692 10693 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10694 SourceLocation Loc, 10695 bool IsCompAssign, bool IsDiv) { 10696 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10697 10698 QualType LHSTy = LHS.get()->getType(); 10699 QualType RHSTy = RHS.get()->getType(); 10700 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10701 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10702 /*AllowBothBool*/ getLangOpts().AltiVec, 10703 /*AllowBoolConversions*/ false, 10704 /*AllowBooleanOperation*/ false, 10705 /*ReportInvalid*/ true); 10706 if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType()) 10707 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 10708 ACK_Arithmetic); 10709 if (!IsDiv && 10710 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10711 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10712 // For division, only matrix-by-scalar is supported. Other combinations with 10713 // matrix types are invalid. 10714 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10715 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10716 10717 QualType compType = UsualArithmeticConversions( 10718 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10719 if (LHS.isInvalid() || RHS.isInvalid()) 10720 return QualType(); 10721 10722 10723 if (compType.isNull() || !compType->isArithmeticType()) 10724 return InvalidOperands(Loc, LHS, RHS); 10725 if (IsDiv) { 10726 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10727 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10728 } 10729 return compType; 10730 } 10731 10732 QualType Sema::CheckRemainderOperands( 10733 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10734 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10735 10736 if (LHS.get()->getType()->isVectorType() || 10737 RHS.get()->getType()->isVectorType()) { 10738 if (LHS.get()->getType()->hasIntegerRepresentation() && 10739 RHS.get()->getType()->hasIntegerRepresentation()) 10740 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10741 /*AllowBothBool*/ getLangOpts().AltiVec, 10742 /*AllowBoolConversions*/ false, 10743 /*AllowBooleanOperation*/ false, 10744 /*ReportInvalid*/ true); 10745 return InvalidOperands(Loc, LHS, RHS); 10746 } 10747 10748 if (LHS.get()->getType()->isVLSTBuiltinType() || 10749 RHS.get()->getType()->isVLSTBuiltinType()) { 10750 if (LHS.get()->getType()->hasIntegerRepresentation() && 10751 RHS.get()->getType()->hasIntegerRepresentation()) 10752 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 10753 ACK_Arithmetic); 10754 10755 return InvalidOperands(Loc, LHS, RHS); 10756 } 10757 10758 QualType compType = UsualArithmeticConversions( 10759 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10760 if (LHS.isInvalid() || RHS.isInvalid()) 10761 return QualType(); 10762 10763 if (compType.isNull() || !compType->isIntegerType()) 10764 return InvalidOperands(Loc, LHS, RHS); 10765 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10766 return compType; 10767 } 10768 10769 /// Diagnose invalid arithmetic on two void pointers. 10770 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10771 Expr *LHSExpr, Expr *RHSExpr) { 10772 S.Diag(Loc, S.getLangOpts().CPlusPlus 10773 ? diag::err_typecheck_pointer_arith_void_type 10774 : diag::ext_gnu_void_ptr) 10775 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10776 << RHSExpr->getSourceRange(); 10777 } 10778 10779 /// Diagnose invalid arithmetic on a void pointer. 10780 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10781 Expr *Pointer) { 10782 S.Diag(Loc, S.getLangOpts().CPlusPlus 10783 ? diag::err_typecheck_pointer_arith_void_type 10784 : diag::ext_gnu_void_ptr) 10785 << 0 /* one pointer */ << Pointer->getSourceRange(); 10786 } 10787 10788 /// Diagnose invalid arithmetic on a null pointer. 10789 /// 10790 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10791 /// idiom, which we recognize as a GNU extension. 10792 /// 10793 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10794 Expr *Pointer, bool IsGNUIdiom) { 10795 if (IsGNUIdiom) 10796 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10797 << Pointer->getSourceRange(); 10798 else 10799 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10800 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10801 } 10802 10803 /// Diagnose invalid subraction on a null pointer. 10804 /// 10805 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, 10806 Expr *Pointer, bool BothNull) { 10807 // Null - null is valid in C++ [expr.add]p7 10808 if (BothNull && S.getLangOpts().CPlusPlus) 10809 return; 10810 10811 // Is this s a macro from a system header? 10812 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) 10813 return; 10814 10815 S.Diag(Loc, diag::warn_pointer_sub_null_ptr) 10816 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10817 } 10818 10819 /// Diagnose invalid arithmetic on two function pointers. 10820 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10821 Expr *LHS, Expr *RHS) { 10822 assert(LHS->getType()->isAnyPointerType()); 10823 assert(RHS->getType()->isAnyPointerType()); 10824 S.Diag(Loc, S.getLangOpts().CPlusPlus 10825 ? diag::err_typecheck_pointer_arith_function_type 10826 : diag::ext_gnu_ptr_func_arith) 10827 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10828 // We only show the second type if it differs from the first. 10829 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10830 RHS->getType()) 10831 << RHS->getType()->getPointeeType() 10832 << LHS->getSourceRange() << RHS->getSourceRange(); 10833 } 10834 10835 /// Diagnose invalid arithmetic on a function pointer. 10836 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10837 Expr *Pointer) { 10838 assert(Pointer->getType()->isAnyPointerType()); 10839 S.Diag(Loc, S.getLangOpts().CPlusPlus 10840 ? diag::err_typecheck_pointer_arith_function_type 10841 : diag::ext_gnu_ptr_func_arith) 10842 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10843 << 0 /* one pointer, so only one type */ 10844 << Pointer->getSourceRange(); 10845 } 10846 10847 /// Emit error if Operand is incomplete pointer type 10848 /// 10849 /// \returns True if pointer has incomplete type 10850 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10851 Expr *Operand) { 10852 QualType ResType = Operand->getType(); 10853 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10854 ResType = ResAtomicType->getValueType(); 10855 10856 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10857 QualType PointeeTy = ResType->getPointeeType(); 10858 return S.RequireCompleteSizedType( 10859 Loc, PointeeTy, 10860 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10861 Operand->getSourceRange()); 10862 } 10863 10864 /// Check the validity of an arithmetic pointer operand. 10865 /// 10866 /// If the operand has pointer type, this code will check for pointer types 10867 /// which are invalid in arithmetic operations. These will be diagnosed 10868 /// appropriately, including whether or not the use is supported as an 10869 /// extension. 10870 /// 10871 /// \returns True when the operand is valid to use (even if as an extension). 10872 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10873 Expr *Operand) { 10874 QualType ResType = Operand->getType(); 10875 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10876 ResType = ResAtomicType->getValueType(); 10877 10878 if (!ResType->isAnyPointerType()) return true; 10879 10880 QualType PointeeTy = ResType->getPointeeType(); 10881 if (PointeeTy->isVoidType()) { 10882 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10883 return !S.getLangOpts().CPlusPlus; 10884 } 10885 if (PointeeTy->isFunctionType()) { 10886 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10887 return !S.getLangOpts().CPlusPlus; 10888 } 10889 10890 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10891 10892 return true; 10893 } 10894 10895 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10896 /// operands. 10897 /// 10898 /// This routine will diagnose any invalid arithmetic on pointer operands much 10899 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10900 /// for emitting a single diagnostic even for operations where both LHS and RHS 10901 /// are (potentially problematic) pointers. 10902 /// 10903 /// \returns True when the operand is valid to use (even if as an extension). 10904 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10905 Expr *LHSExpr, Expr *RHSExpr) { 10906 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10907 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10908 if (!isLHSPointer && !isRHSPointer) return true; 10909 10910 QualType LHSPointeeTy, RHSPointeeTy; 10911 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10912 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10913 10914 // if both are pointers check if operation is valid wrt address spaces 10915 if (isLHSPointer && isRHSPointer) { 10916 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10917 S.Diag(Loc, 10918 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10919 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10920 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10921 return false; 10922 } 10923 } 10924 10925 // Check for arithmetic on pointers to incomplete types. 10926 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10927 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10928 if (isLHSVoidPtr || isRHSVoidPtr) { 10929 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10930 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10931 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10932 10933 return !S.getLangOpts().CPlusPlus; 10934 } 10935 10936 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10937 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10938 if (isLHSFuncPtr || isRHSFuncPtr) { 10939 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10940 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10941 RHSExpr); 10942 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10943 10944 return !S.getLangOpts().CPlusPlus; 10945 } 10946 10947 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10948 return false; 10949 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10950 return false; 10951 10952 return true; 10953 } 10954 10955 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10956 /// literal. 10957 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10958 Expr *LHSExpr, Expr *RHSExpr) { 10959 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10960 Expr* IndexExpr = RHSExpr; 10961 if (!StrExpr) { 10962 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10963 IndexExpr = LHSExpr; 10964 } 10965 10966 bool IsStringPlusInt = StrExpr && 10967 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10968 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10969 return; 10970 10971 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10972 Self.Diag(OpLoc, diag::warn_string_plus_int) 10973 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10974 10975 // Only print a fixit for "str" + int, not for int + "str". 10976 if (IndexExpr == RHSExpr) { 10977 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10978 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10979 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10980 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10981 << FixItHint::CreateInsertion(EndLoc, "]"); 10982 } else 10983 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10984 } 10985 10986 /// Emit a warning when adding a char literal to a string. 10987 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10988 Expr *LHSExpr, Expr *RHSExpr) { 10989 const Expr *StringRefExpr = LHSExpr; 10990 const CharacterLiteral *CharExpr = 10991 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10992 10993 if (!CharExpr) { 10994 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10995 StringRefExpr = RHSExpr; 10996 } 10997 10998 if (!CharExpr || !StringRefExpr) 10999 return; 11000 11001 const QualType StringType = StringRefExpr->getType(); 11002 11003 // Return if not a PointerType. 11004 if (!StringType->isAnyPointerType()) 11005 return; 11006 11007 // Return if not a CharacterType. 11008 if (!StringType->getPointeeType()->isAnyCharacterType()) 11009 return; 11010 11011 ASTContext &Ctx = Self.getASTContext(); 11012 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 11013 11014 const QualType CharType = CharExpr->getType(); 11015 if (!CharType->isAnyCharacterType() && 11016 CharType->isIntegerType() && 11017 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 11018 Self.Diag(OpLoc, diag::warn_string_plus_char) 11019 << DiagRange << Ctx.CharTy; 11020 } else { 11021 Self.Diag(OpLoc, diag::warn_string_plus_char) 11022 << DiagRange << CharExpr->getType(); 11023 } 11024 11025 // Only print a fixit for str + char, not for char + str. 11026 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 11027 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 11028 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 11029 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 11030 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 11031 << FixItHint::CreateInsertion(EndLoc, "]"); 11032 } else { 11033 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 11034 } 11035 } 11036 11037 /// Emit error when two pointers are incompatible. 11038 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 11039 Expr *LHSExpr, Expr *RHSExpr) { 11040 assert(LHSExpr->getType()->isAnyPointerType()); 11041 assert(RHSExpr->getType()->isAnyPointerType()); 11042 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 11043 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 11044 << RHSExpr->getSourceRange(); 11045 } 11046 11047 // C99 6.5.6 11048 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 11049 SourceLocation Loc, BinaryOperatorKind Opc, 11050 QualType* CompLHSTy) { 11051 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11052 11053 if (LHS.get()->getType()->isVectorType() || 11054 RHS.get()->getType()->isVectorType()) { 11055 QualType compType = 11056 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy, 11057 /*AllowBothBool*/ getLangOpts().AltiVec, 11058 /*AllowBoolConversions*/ getLangOpts().ZVector, 11059 /*AllowBooleanOperation*/ false, 11060 /*ReportInvalid*/ true); 11061 if (CompLHSTy) *CompLHSTy = compType; 11062 return compType; 11063 } 11064 11065 if (LHS.get()->getType()->isVLSTBuiltinType() || 11066 RHS.get()->getType()->isVLSTBuiltinType()) { 11067 QualType compType = 11068 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic); 11069 if (CompLHSTy) 11070 *CompLHSTy = compType; 11071 return compType; 11072 } 11073 11074 if (LHS.get()->getType()->isConstantMatrixType() || 11075 RHS.get()->getType()->isConstantMatrixType()) { 11076 QualType compType = 11077 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 11078 if (CompLHSTy) 11079 *CompLHSTy = compType; 11080 return compType; 11081 } 11082 11083 QualType compType = UsualArithmeticConversions( 11084 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 11085 if (LHS.isInvalid() || RHS.isInvalid()) 11086 return QualType(); 11087 11088 // Diagnose "string literal" '+' int and string '+' "char literal". 11089 if (Opc == BO_Add) { 11090 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 11091 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 11092 } 11093 11094 // handle the common case first (both operands are arithmetic). 11095 if (!compType.isNull() && compType->isArithmeticType()) { 11096 if (CompLHSTy) *CompLHSTy = compType; 11097 return compType; 11098 } 11099 11100 // Type-checking. Ultimately the pointer's going to be in PExp; 11101 // note that we bias towards the LHS being the pointer. 11102 Expr *PExp = LHS.get(), *IExp = RHS.get(); 11103 11104 bool isObjCPointer; 11105 if (PExp->getType()->isPointerType()) { 11106 isObjCPointer = false; 11107 } else if (PExp->getType()->isObjCObjectPointerType()) { 11108 isObjCPointer = true; 11109 } else { 11110 std::swap(PExp, IExp); 11111 if (PExp->getType()->isPointerType()) { 11112 isObjCPointer = false; 11113 } else if (PExp->getType()->isObjCObjectPointerType()) { 11114 isObjCPointer = true; 11115 } else { 11116 return InvalidOperands(Loc, LHS, RHS); 11117 } 11118 } 11119 assert(PExp->getType()->isAnyPointerType()); 11120 11121 if (!IExp->getType()->isIntegerType()) 11122 return InvalidOperands(Loc, LHS, RHS); 11123 11124 // Adding to a null pointer results in undefined behavior. 11125 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 11126 Context, Expr::NPC_ValueDependentIsNotNull)) { 11127 // In C++ adding zero to a null pointer is defined. 11128 Expr::EvalResult KnownVal; 11129 if (!getLangOpts().CPlusPlus || 11130 (!IExp->isValueDependent() && 11131 (!IExp->EvaluateAsInt(KnownVal, Context) || 11132 KnownVal.Val.getInt() != 0))) { 11133 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 11134 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 11135 Context, BO_Add, PExp, IExp); 11136 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 11137 } 11138 } 11139 11140 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 11141 return QualType(); 11142 11143 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 11144 return QualType(); 11145 11146 // Check array bounds for pointer arithemtic 11147 CheckArrayAccess(PExp, IExp); 11148 11149 if (CompLHSTy) { 11150 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 11151 if (LHSTy.isNull()) { 11152 LHSTy = LHS.get()->getType(); 11153 if (LHSTy->isPromotableIntegerType()) 11154 LHSTy = Context.getPromotedIntegerType(LHSTy); 11155 } 11156 *CompLHSTy = LHSTy; 11157 } 11158 11159 return PExp->getType(); 11160 } 11161 11162 // C99 6.5.6 11163 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 11164 SourceLocation Loc, 11165 QualType* CompLHSTy) { 11166 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11167 11168 if (LHS.get()->getType()->isVectorType() || 11169 RHS.get()->getType()->isVectorType()) { 11170 QualType compType = 11171 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy, 11172 /*AllowBothBool*/ getLangOpts().AltiVec, 11173 /*AllowBoolConversions*/ getLangOpts().ZVector, 11174 /*AllowBooleanOperation*/ false, 11175 /*ReportInvalid*/ true); 11176 if (CompLHSTy) *CompLHSTy = compType; 11177 return compType; 11178 } 11179 11180 if (LHS.get()->getType()->isVLSTBuiltinType() || 11181 RHS.get()->getType()->isVLSTBuiltinType()) { 11182 QualType compType = 11183 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic); 11184 if (CompLHSTy) 11185 *CompLHSTy = compType; 11186 return compType; 11187 } 11188 11189 if (LHS.get()->getType()->isConstantMatrixType() || 11190 RHS.get()->getType()->isConstantMatrixType()) { 11191 QualType compType = 11192 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 11193 if (CompLHSTy) 11194 *CompLHSTy = compType; 11195 return compType; 11196 } 11197 11198 QualType compType = UsualArithmeticConversions( 11199 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 11200 if (LHS.isInvalid() || RHS.isInvalid()) 11201 return QualType(); 11202 11203 // Enforce type constraints: C99 6.5.6p3. 11204 11205 // Handle the common case first (both operands are arithmetic). 11206 if (!compType.isNull() && compType->isArithmeticType()) { 11207 if (CompLHSTy) *CompLHSTy = compType; 11208 return compType; 11209 } 11210 11211 // Either ptr - int or ptr - ptr. 11212 if (LHS.get()->getType()->isAnyPointerType()) { 11213 QualType lpointee = LHS.get()->getType()->getPointeeType(); 11214 11215 // Diagnose bad cases where we step over interface counts. 11216 if (LHS.get()->getType()->isObjCObjectPointerType() && 11217 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 11218 return QualType(); 11219 11220 // The result type of a pointer-int computation is the pointer type. 11221 if (RHS.get()->getType()->isIntegerType()) { 11222 // Subtracting from a null pointer should produce a warning. 11223 // The last argument to the diagnose call says this doesn't match the 11224 // GNU int-to-pointer idiom. 11225 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 11226 Expr::NPC_ValueDependentIsNotNull)) { 11227 // In C++ adding zero to a null pointer is defined. 11228 Expr::EvalResult KnownVal; 11229 if (!getLangOpts().CPlusPlus || 11230 (!RHS.get()->isValueDependent() && 11231 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 11232 KnownVal.Val.getInt() != 0))) { 11233 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 11234 } 11235 } 11236 11237 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 11238 return QualType(); 11239 11240 // Check array bounds for pointer arithemtic 11241 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 11242 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 11243 11244 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 11245 return LHS.get()->getType(); 11246 } 11247 11248 // Handle pointer-pointer subtractions. 11249 if (const PointerType *RHSPTy 11250 = RHS.get()->getType()->getAs<PointerType>()) { 11251 QualType rpointee = RHSPTy->getPointeeType(); 11252 11253 if (getLangOpts().CPlusPlus) { 11254 // Pointee types must be the same: C++ [expr.add] 11255 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 11256 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 11257 } 11258 } else { 11259 // Pointee types must be compatible C99 6.5.6p3 11260 if (!Context.typesAreCompatible( 11261 Context.getCanonicalType(lpointee).getUnqualifiedType(), 11262 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 11263 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 11264 return QualType(); 11265 } 11266 } 11267 11268 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 11269 LHS.get(), RHS.get())) 11270 return QualType(); 11271 11272 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( 11273 Context, Expr::NPC_ValueDependentIsNotNull); 11274 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( 11275 Context, Expr::NPC_ValueDependentIsNotNull); 11276 11277 // Subtracting nullptr or from nullptr is suspect 11278 if (LHSIsNullPtr) 11279 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); 11280 if (RHSIsNullPtr) 11281 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); 11282 11283 // The pointee type may have zero size. As an extension, a structure or 11284 // union may have zero size or an array may have zero length. In this 11285 // case subtraction does not make sense. 11286 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 11287 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 11288 if (ElementSize.isZero()) { 11289 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 11290 << rpointee.getUnqualifiedType() 11291 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11292 } 11293 } 11294 11295 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 11296 return Context.getPointerDiffType(); 11297 } 11298 } 11299 11300 return InvalidOperands(Loc, LHS, RHS); 11301 } 11302 11303 static bool isScopedEnumerationType(QualType T) { 11304 if (const EnumType *ET = T->getAs<EnumType>()) 11305 return ET->getDecl()->isScoped(); 11306 return false; 11307 } 11308 11309 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 11310 SourceLocation Loc, BinaryOperatorKind Opc, 11311 QualType LHSType) { 11312 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 11313 // so skip remaining warnings as we don't want to modify values within Sema. 11314 if (S.getLangOpts().OpenCL) 11315 return; 11316 11317 // Check right/shifter operand 11318 Expr::EvalResult RHSResult; 11319 if (RHS.get()->isValueDependent() || 11320 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 11321 return; 11322 llvm::APSInt Right = RHSResult.Val.getInt(); 11323 11324 if (Right.isNegative()) { 11325 S.DiagRuntimeBehavior(Loc, RHS.get(), 11326 S.PDiag(diag::warn_shift_negative) 11327 << RHS.get()->getSourceRange()); 11328 return; 11329 } 11330 11331 QualType LHSExprType = LHS.get()->getType(); 11332 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 11333 if (LHSExprType->isBitIntType()) 11334 LeftSize = S.Context.getIntWidth(LHSExprType); 11335 else if (LHSExprType->isFixedPointType()) { 11336 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 11337 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 11338 } 11339 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 11340 if (Right.uge(LeftBits)) { 11341 S.DiagRuntimeBehavior(Loc, RHS.get(), 11342 S.PDiag(diag::warn_shift_gt_typewidth) 11343 << RHS.get()->getSourceRange()); 11344 return; 11345 } 11346 11347 // FIXME: We probably need to handle fixed point types specially here. 11348 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 11349 return; 11350 11351 // When left shifting an ICE which is signed, we can check for overflow which 11352 // according to C++ standards prior to C++2a has undefined behavior 11353 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 11354 // more than the maximum value representable in the result type, so never 11355 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 11356 // expression is still probably a bug.) 11357 Expr::EvalResult LHSResult; 11358 if (LHS.get()->isValueDependent() || 11359 LHSType->hasUnsignedIntegerRepresentation() || 11360 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 11361 return; 11362 llvm::APSInt Left = LHSResult.Val.getInt(); 11363 11364 // If LHS does not have a signed type and non-negative value 11365 // then, the behavior is undefined before C++2a. Warn about it. 11366 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 11367 !S.getLangOpts().CPlusPlus20) { 11368 S.DiagRuntimeBehavior(Loc, LHS.get(), 11369 S.PDiag(diag::warn_shift_lhs_negative) 11370 << LHS.get()->getSourceRange()); 11371 return; 11372 } 11373 11374 llvm::APInt ResultBits = 11375 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 11376 if (LeftBits.uge(ResultBits)) 11377 return; 11378 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 11379 Result = Result.shl(Right); 11380 11381 // Print the bit representation of the signed integer as an unsigned 11382 // hexadecimal number. 11383 SmallString<40> HexResult; 11384 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 11385 11386 // If we are only missing a sign bit, this is less likely to result in actual 11387 // bugs -- if the result is cast back to an unsigned type, it will have the 11388 // expected value. Thus we place this behind a different warning that can be 11389 // turned off separately if needed. 11390 if (LeftBits == ResultBits - 1) { 11391 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 11392 << HexResult << LHSType 11393 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11394 return; 11395 } 11396 11397 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 11398 << HexResult.str() << Result.getMinSignedBits() << LHSType 11399 << Left.getBitWidth() << LHS.get()->getSourceRange() 11400 << RHS.get()->getSourceRange(); 11401 } 11402 11403 /// Return the resulting type when a vector is shifted 11404 /// by a scalar or vector shift amount. 11405 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 11406 SourceLocation Loc, bool IsCompAssign) { 11407 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 11408 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 11409 !LHS.get()->getType()->isVectorType()) { 11410 S.Diag(Loc, diag::err_shift_rhs_only_vector) 11411 << RHS.get()->getType() << LHS.get()->getType() 11412 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11413 return QualType(); 11414 } 11415 11416 if (!IsCompAssign) { 11417 LHS = S.UsualUnaryConversions(LHS.get()); 11418 if (LHS.isInvalid()) return QualType(); 11419 } 11420 11421 RHS = S.UsualUnaryConversions(RHS.get()); 11422 if (RHS.isInvalid()) return QualType(); 11423 11424 QualType LHSType = LHS.get()->getType(); 11425 // Note that LHS might be a scalar because the routine calls not only in 11426 // OpenCL case. 11427 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 11428 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 11429 11430 // Note that RHS might not be a vector. 11431 QualType RHSType = RHS.get()->getType(); 11432 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 11433 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 11434 11435 // Do not allow shifts for boolean vectors. 11436 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) || 11437 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) { 11438 S.Diag(Loc, diag::err_typecheck_invalid_operands) 11439 << LHS.get()->getType() << RHS.get()->getType() 11440 << LHS.get()->getSourceRange(); 11441 return QualType(); 11442 } 11443 11444 // The operands need to be integers. 11445 if (!LHSEleType->isIntegerType()) { 11446 S.Diag(Loc, diag::err_typecheck_expect_int) 11447 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11448 return QualType(); 11449 } 11450 11451 if (!RHSEleType->isIntegerType()) { 11452 S.Diag(Loc, diag::err_typecheck_expect_int) 11453 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11454 return QualType(); 11455 } 11456 11457 if (!LHSVecTy) { 11458 assert(RHSVecTy); 11459 if (IsCompAssign) 11460 return RHSType; 11461 if (LHSEleType != RHSEleType) { 11462 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 11463 LHSEleType = RHSEleType; 11464 } 11465 QualType VecTy = 11466 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11467 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11468 LHSType = VecTy; 11469 } else if (RHSVecTy) { 11470 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11471 // are applied component-wise. So if RHS is a vector, then ensure 11472 // that the number of elements is the same as LHS... 11473 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11474 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11475 << LHS.get()->getType() << RHS.get()->getType() 11476 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11477 return QualType(); 11478 } 11479 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11480 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11481 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11482 if (LHSBT != RHSBT && 11483 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11484 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11485 << LHS.get()->getType() << RHS.get()->getType() 11486 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11487 } 11488 } 11489 } else { 11490 // ...else expand RHS to match the number of elements in LHS. 11491 QualType VecTy = 11492 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11493 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11494 } 11495 11496 return LHSType; 11497 } 11498 11499 static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, 11500 ExprResult &RHS, SourceLocation Loc, 11501 bool IsCompAssign) { 11502 if (!IsCompAssign) { 11503 LHS = S.UsualUnaryConversions(LHS.get()); 11504 if (LHS.isInvalid()) 11505 return QualType(); 11506 } 11507 11508 RHS = S.UsualUnaryConversions(RHS.get()); 11509 if (RHS.isInvalid()) 11510 return QualType(); 11511 11512 QualType LHSType = LHS.get()->getType(); 11513 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); 11514 QualType LHSEleType = LHSType->isVLSTBuiltinType() 11515 ? LHSBuiltinTy->getSveEltType(S.getASTContext()) 11516 : LHSType; 11517 11518 // Note that RHS might not be a vector 11519 QualType RHSType = RHS.get()->getType(); 11520 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>(); 11521 QualType RHSEleType = RHSType->isVLSTBuiltinType() 11522 ? RHSBuiltinTy->getSveEltType(S.getASTContext()) 11523 : RHSType; 11524 11525 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) || 11526 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) { 11527 S.Diag(Loc, diag::err_typecheck_invalid_operands) 11528 << LHSType << RHSType << LHS.get()->getSourceRange(); 11529 return QualType(); 11530 } 11531 11532 if (!LHSEleType->isIntegerType()) { 11533 S.Diag(Loc, diag::err_typecheck_expect_int) 11534 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11535 return QualType(); 11536 } 11537 11538 if (!RHSEleType->isIntegerType()) { 11539 S.Diag(Loc, diag::err_typecheck_expect_int) 11540 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11541 return QualType(); 11542 } 11543 11544 if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() && 11545 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC != 11546 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) { 11547 S.Diag(Loc, diag::err_typecheck_invalid_operands) 11548 << LHSType << RHSType << LHS.get()->getSourceRange() 11549 << RHS.get()->getSourceRange(); 11550 return QualType(); 11551 } 11552 11553 if (!LHSType->isVLSTBuiltinType()) { 11554 assert(RHSType->isVLSTBuiltinType()); 11555 if (IsCompAssign) 11556 return RHSType; 11557 if (LHSEleType != RHSEleType) { 11558 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast); 11559 LHSEleType = RHSEleType; 11560 } 11561 const llvm::ElementCount VecSize = 11562 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC; 11563 QualType VecTy = 11564 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue()); 11565 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat); 11566 LHSType = VecTy; 11567 } else if (RHSBuiltinTy && RHSBuiltinTy->isVLSTBuiltinType()) { 11568 if (S.Context.getTypeSize(RHSBuiltinTy) != 11569 S.Context.getTypeSize(LHSBuiltinTy)) { 11570 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11571 << LHSType << RHSType << LHS.get()->getSourceRange() 11572 << RHS.get()->getSourceRange(); 11573 return QualType(); 11574 } 11575 } else { 11576 const llvm::ElementCount VecSize = 11577 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC; 11578 if (LHSEleType != RHSEleType) { 11579 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast); 11580 RHSEleType = LHSEleType; 11581 } 11582 QualType VecTy = 11583 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue()); 11584 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11585 } 11586 11587 return LHSType; 11588 } 11589 11590 // C99 6.5.7 11591 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11592 SourceLocation Loc, BinaryOperatorKind Opc, 11593 bool IsCompAssign) { 11594 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11595 11596 // Vector shifts promote their scalar inputs to vector type. 11597 if (LHS.get()->getType()->isVectorType() || 11598 RHS.get()->getType()->isVectorType()) { 11599 if (LangOpts.ZVector) { 11600 // The shift operators for the z vector extensions work basically 11601 // like general shifts, except that neither the LHS nor the RHS is 11602 // allowed to be a "vector bool". 11603 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11604 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11605 return InvalidOperands(Loc, LHS, RHS); 11606 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11607 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11608 return InvalidOperands(Loc, LHS, RHS); 11609 } 11610 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11611 } 11612 11613 if (LHS.get()->getType()->isVLSTBuiltinType() || 11614 RHS.get()->getType()->isVLSTBuiltinType()) 11615 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11616 11617 // Shifts don't perform usual arithmetic conversions, they just do integer 11618 // promotions on each operand. C99 6.5.7p3 11619 11620 // For the LHS, do usual unary conversions, but then reset them away 11621 // if this is a compound assignment. 11622 ExprResult OldLHS = LHS; 11623 LHS = UsualUnaryConversions(LHS.get()); 11624 if (LHS.isInvalid()) 11625 return QualType(); 11626 QualType LHSType = LHS.get()->getType(); 11627 if (IsCompAssign) LHS = OldLHS; 11628 11629 // The RHS is simpler. 11630 RHS = UsualUnaryConversions(RHS.get()); 11631 if (RHS.isInvalid()) 11632 return QualType(); 11633 QualType RHSType = RHS.get()->getType(); 11634 11635 // C99 6.5.7p2: Each of the operands shall have integer type. 11636 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11637 if ((!LHSType->isFixedPointOrIntegerType() && 11638 !LHSType->hasIntegerRepresentation()) || 11639 !RHSType->hasIntegerRepresentation()) 11640 return InvalidOperands(Loc, LHS, RHS); 11641 11642 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11643 // hasIntegerRepresentation() above instead of this. 11644 if (isScopedEnumerationType(LHSType) || 11645 isScopedEnumerationType(RHSType)) { 11646 return InvalidOperands(Loc, LHS, RHS); 11647 } 11648 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11649 11650 // "The type of the result is that of the promoted left operand." 11651 return LHSType; 11652 } 11653 11654 /// Diagnose bad pointer comparisons. 11655 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11656 ExprResult &LHS, ExprResult &RHS, 11657 bool IsError) { 11658 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11659 : diag::ext_typecheck_comparison_of_distinct_pointers) 11660 << LHS.get()->getType() << RHS.get()->getType() 11661 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11662 } 11663 11664 /// Returns false if the pointers are converted to a composite type, 11665 /// true otherwise. 11666 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11667 ExprResult &LHS, ExprResult &RHS) { 11668 // C++ [expr.rel]p2: 11669 // [...] Pointer conversions (4.10) and qualification 11670 // conversions (4.4) are performed on pointer operands (or on 11671 // a pointer operand and a null pointer constant) to bring 11672 // them to their composite pointer type. [...] 11673 // 11674 // C++ [expr.eq]p1 uses the same notion for (in)equality 11675 // comparisons of pointers. 11676 11677 QualType LHSType = LHS.get()->getType(); 11678 QualType RHSType = RHS.get()->getType(); 11679 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11680 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11681 11682 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11683 if (T.isNull()) { 11684 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11685 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11686 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11687 else 11688 S.InvalidOperands(Loc, LHS, RHS); 11689 return true; 11690 } 11691 11692 return false; 11693 } 11694 11695 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11696 ExprResult &LHS, 11697 ExprResult &RHS, 11698 bool IsError) { 11699 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11700 : diag::ext_typecheck_comparison_of_fptr_to_void) 11701 << LHS.get()->getType() << RHS.get()->getType() 11702 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11703 } 11704 11705 static bool isObjCObjectLiteral(ExprResult &E) { 11706 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11707 case Stmt::ObjCArrayLiteralClass: 11708 case Stmt::ObjCDictionaryLiteralClass: 11709 case Stmt::ObjCStringLiteralClass: 11710 case Stmt::ObjCBoxedExprClass: 11711 return true; 11712 default: 11713 // Note that ObjCBoolLiteral is NOT an object literal! 11714 return false; 11715 } 11716 } 11717 11718 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11719 const ObjCObjectPointerType *Type = 11720 LHS->getType()->getAs<ObjCObjectPointerType>(); 11721 11722 // If this is not actually an Objective-C object, bail out. 11723 if (!Type) 11724 return false; 11725 11726 // Get the LHS object's interface type. 11727 QualType InterfaceType = Type->getPointeeType(); 11728 11729 // If the RHS isn't an Objective-C object, bail out. 11730 if (!RHS->getType()->isObjCObjectPointerType()) 11731 return false; 11732 11733 // Try to find the -isEqual: method. 11734 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11735 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11736 InterfaceType, 11737 /*IsInstance=*/true); 11738 if (!Method) { 11739 if (Type->isObjCIdType()) { 11740 // For 'id', just check the global pool. 11741 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11742 /*receiverId=*/true); 11743 } else { 11744 // Check protocols. 11745 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11746 /*IsInstance=*/true); 11747 } 11748 } 11749 11750 if (!Method) 11751 return false; 11752 11753 QualType T = Method->parameters()[0]->getType(); 11754 if (!T->isObjCObjectPointerType()) 11755 return false; 11756 11757 QualType R = Method->getReturnType(); 11758 if (!R->isScalarType()) 11759 return false; 11760 11761 return true; 11762 } 11763 11764 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11765 FromE = FromE->IgnoreParenImpCasts(); 11766 switch (FromE->getStmtClass()) { 11767 default: 11768 break; 11769 case Stmt::ObjCStringLiteralClass: 11770 // "string literal" 11771 return LK_String; 11772 case Stmt::ObjCArrayLiteralClass: 11773 // "array literal" 11774 return LK_Array; 11775 case Stmt::ObjCDictionaryLiteralClass: 11776 // "dictionary literal" 11777 return LK_Dictionary; 11778 case Stmt::BlockExprClass: 11779 return LK_Block; 11780 case Stmt::ObjCBoxedExprClass: { 11781 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11782 switch (Inner->getStmtClass()) { 11783 case Stmt::IntegerLiteralClass: 11784 case Stmt::FloatingLiteralClass: 11785 case Stmt::CharacterLiteralClass: 11786 case Stmt::ObjCBoolLiteralExprClass: 11787 case Stmt::CXXBoolLiteralExprClass: 11788 // "numeric literal" 11789 return LK_Numeric; 11790 case Stmt::ImplicitCastExprClass: { 11791 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11792 // Boolean literals can be represented by implicit casts. 11793 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11794 return LK_Numeric; 11795 break; 11796 } 11797 default: 11798 break; 11799 } 11800 return LK_Boxed; 11801 } 11802 } 11803 return LK_None; 11804 } 11805 11806 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11807 ExprResult &LHS, ExprResult &RHS, 11808 BinaryOperator::Opcode Opc){ 11809 Expr *Literal; 11810 Expr *Other; 11811 if (isObjCObjectLiteral(LHS)) { 11812 Literal = LHS.get(); 11813 Other = RHS.get(); 11814 } else { 11815 Literal = RHS.get(); 11816 Other = LHS.get(); 11817 } 11818 11819 // Don't warn on comparisons against nil. 11820 Other = Other->IgnoreParenCasts(); 11821 if (Other->isNullPointerConstant(S.getASTContext(), 11822 Expr::NPC_ValueDependentIsNotNull)) 11823 return; 11824 11825 // This should be kept in sync with warn_objc_literal_comparison. 11826 // LK_String should always be after the other literals, since it has its own 11827 // warning flag. 11828 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11829 assert(LiteralKind != Sema::LK_Block); 11830 if (LiteralKind == Sema::LK_None) { 11831 llvm_unreachable("Unknown Objective-C object literal kind"); 11832 } 11833 11834 if (LiteralKind == Sema::LK_String) 11835 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11836 << Literal->getSourceRange(); 11837 else 11838 S.Diag(Loc, diag::warn_objc_literal_comparison) 11839 << LiteralKind << Literal->getSourceRange(); 11840 11841 if (BinaryOperator::isEqualityOp(Opc) && 11842 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11843 SourceLocation Start = LHS.get()->getBeginLoc(); 11844 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11845 CharSourceRange OpRange = 11846 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11847 11848 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11849 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11850 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11851 << FixItHint::CreateInsertion(End, "]"); 11852 } 11853 } 11854 11855 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11856 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11857 ExprResult &RHS, SourceLocation Loc, 11858 BinaryOperatorKind Opc) { 11859 // Check that left hand side is !something. 11860 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11861 if (!UO || UO->getOpcode() != UO_LNot) return; 11862 11863 // Only check if the right hand side is non-bool arithmetic type. 11864 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11865 11866 // Make sure that the something in !something is not bool. 11867 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11868 if (SubExpr->isKnownToHaveBooleanValue()) return; 11869 11870 // Emit warning. 11871 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11872 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11873 << Loc << IsBitwiseOp; 11874 11875 // First note suggest !(x < y) 11876 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11877 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11878 FirstClose = S.getLocForEndOfToken(FirstClose); 11879 if (FirstClose.isInvalid()) 11880 FirstOpen = SourceLocation(); 11881 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11882 << IsBitwiseOp 11883 << FixItHint::CreateInsertion(FirstOpen, "(") 11884 << FixItHint::CreateInsertion(FirstClose, ")"); 11885 11886 // Second note suggests (!x) < y 11887 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11888 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11889 SecondClose = S.getLocForEndOfToken(SecondClose); 11890 if (SecondClose.isInvalid()) 11891 SecondOpen = SourceLocation(); 11892 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11893 << FixItHint::CreateInsertion(SecondOpen, "(") 11894 << FixItHint::CreateInsertion(SecondClose, ")"); 11895 } 11896 11897 // Returns true if E refers to a non-weak array. 11898 static bool checkForArray(const Expr *E) { 11899 const ValueDecl *D = nullptr; 11900 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11901 D = DR->getDecl(); 11902 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11903 if (Mem->isImplicitAccess()) 11904 D = Mem->getMemberDecl(); 11905 } 11906 if (!D) 11907 return false; 11908 return D->getType()->isArrayType() && !D->isWeak(); 11909 } 11910 11911 /// Diagnose some forms of syntactically-obvious tautological comparison. 11912 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11913 Expr *LHS, Expr *RHS, 11914 BinaryOperatorKind Opc) { 11915 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11916 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11917 11918 QualType LHSType = LHS->getType(); 11919 QualType RHSType = RHS->getType(); 11920 if (LHSType->hasFloatingRepresentation() || 11921 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11922 S.inTemplateInstantiation()) 11923 return; 11924 11925 // Comparisons between two array types are ill-formed for operator<=>, so 11926 // we shouldn't emit any additional warnings about it. 11927 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11928 return; 11929 11930 // For non-floating point types, check for self-comparisons of the form 11931 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11932 // often indicate logic errors in the program. 11933 // 11934 // NOTE: Don't warn about comparison expressions resulting from macro 11935 // expansion. Also don't warn about comparisons which are only self 11936 // comparisons within a template instantiation. The warnings should catch 11937 // obvious cases in the definition of the template anyways. The idea is to 11938 // warn when the typed comparison operator will always evaluate to the same 11939 // result. 11940 11941 // Used for indexing into %select in warn_comparison_always 11942 enum { 11943 AlwaysConstant, 11944 AlwaysTrue, 11945 AlwaysFalse, 11946 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11947 }; 11948 11949 // C++2a [depr.array.comp]: 11950 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11951 // operands of array type are deprecated. 11952 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11953 RHSStripped->getType()->isArrayType()) { 11954 S.Diag(Loc, diag::warn_depr_array_comparison) 11955 << LHS->getSourceRange() << RHS->getSourceRange() 11956 << LHSStripped->getType() << RHSStripped->getType(); 11957 // Carry on to produce the tautological comparison warning, if this 11958 // expression is potentially-evaluated, we can resolve the array to a 11959 // non-weak declaration, and so on. 11960 } 11961 11962 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11963 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11964 unsigned Result; 11965 switch (Opc) { 11966 case BO_EQ: 11967 case BO_LE: 11968 case BO_GE: 11969 Result = AlwaysTrue; 11970 break; 11971 case BO_NE: 11972 case BO_LT: 11973 case BO_GT: 11974 Result = AlwaysFalse; 11975 break; 11976 case BO_Cmp: 11977 Result = AlwaysEqual; 11978 break; 11979 default: 11980 Result = AlwaysConstant; 11981 break; 11982 } 11983 S.DiagRuntimeBehavior(Loc, nullptr, 11984 S.PDiag(diag::warn_comparison_always) 11985 << 0 /*self-comparison*/ 11986 << Result); 11987 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11988 // What is it always going to evaluate to? 11989 unsigned Result; 11990 switch (Opc) { 11991 case BO_EQ: // e.g. array1 == array2 11992 Result = AlwaysFalse; 11993 break; 11994 case BO_NE: // e.g. array1 != array2 11995 Result = AlwaysTrue; 11996 break; 11997 default: // e.g. array1 <= array2 11998 // The best we can say is 'a constant' 11999 Result = AlwaysConstant; 12000 break; 12001 } 12002 S.DiagRuntimeBehavior(Loc, nullptr, 12003 S.PDiag(diag::warn_comparison_always) 12004 << 1 /*array comparison*/ 12005 << Result); 12006 } 12007 } 12008 12009 if (isa<CastExpr>(LHSStripped)) 12010 LHSStripped = LHSStripped->IgnoreParenCasts(); 12011 if (isa<CastExpr>(RHSStripped)) 12012 RHSStripped = RHSStripped->IgnoreParenCasts(); 12013 12014 // Warn about comparisons against a string constant (unless the other 12015 // operand is null); the user probably wants string comparison function. 12016 Expr *LiteralString = nullptr; 12017 Expr *LiteralStringStripped = nullptr; 12018 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 12019 !RHSStripped->isNullPointerConstant(S.Context, 12020 Expr::NPC_ValueDependentIsNull)) { 12021 LiteralString = LHS; 12022 LiteralStringStripped = LHSStripped; 12023 } else if ((isa<StringLiteral>(RHSStripped) || 12024 isa<ObjCEncodeExpr>(RHSStripped)) && 12025 !LHSStripped->isNullPointerConstant(S.Context, 12026 Expr::NPC_ValueDependentIsNull)) { 12027 LiteralString = RHS; 12028 LiteralStringStripped = RHSStripped; 12029 } 12030 12031 if (LiteralString) { 12032 S.DiagRuntimeBehavior(Loc, nullptr, 12033 S.PDiag(diag::warn_stringcompare) 12034 << isa<ObjCEncodeExpr>(LiteralStringStripped) 12035 << LiteralString->getSourceRange()); 12036 } 12037 } 12038 12039 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 12040 switch (CK) { 12041 default: { 12042 #ifndef NDEBUG 12043 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 12044 << "\n"; 12045 #endif 12046 llvm_unreachable("unhandled cast kind"); 12047 } 12048 case CK_UserDefinedConversion: 12049 return ICK_Identity; 12050 case CK_LValueToRValue: 12051 return ICK_Lvalue_To_Rvalue; 12052 case CK_ArrayToPointerDecay: 12053 return ICK_Array_To_Pointer; 12054 case CK_FunctionToPointerDecay: 12055 return ICK_Function_To_Pointer; 12056 case CK_IntegralCast: 12057 return ICK_Integral_Conversion; 12058 case CK_FloatingCast: 12059 return ICK_Floating_Conversion; 12060 case CK_IntegralToFloating: 12061 case CK_FloatingToIntegral: 12062 return ICK_Floating_Integral; 12063 case CK_IntegralComplexCast: 12064 case CK_FloatingComplexCast: 12065 case CK_FloatingComplexToIntegralComplex: 12066 case CK_IntegralComplexToFloatingComplex: 12067 return ICK_Complex_Conversion; 12068 case CK_FloatingComplexToReal: 12069 case CK_FloatingRealToComplex: 12070 case CK_IntegralComplexToReal: 12071 case CK_IntegralRealToComplex: 12072 return ICK_Complex_Real; 12073 } 12074 } 12075 12076 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 12077 QualType FromType, 12078 SourceLocation Loc) { 12079 // Check for a narrowing implicit conversion. 12080 StandardConversionSequence SCS; 12081 SCS.setAsIdentityConversion(); 12082 SCS.setToType(0, FromType); 12083 SCS.setToType(1, ToType); 12084 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 12085 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 12086 12087 APValue PreNarrowingValue; 12088 QualType PreNarrowingType; 12089 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 12090 PreNarrowingType, 12091 /*IgnoreFloatToIntegralConversion*/ true)) { 12092 case NK_Dependent_Narrowing: 12093 // Implicit conversion to a narrower type, but the expression is 12094 // value-dependent so we can't tell whether it's actually narrowing. 12095 case NK_Not_Narrowing: 12096 return false; 12097 12098 case NK_Constant_Narrowing: 12099 // Implicit conversion to a narrower type, and the value is not a constant 12100 // expression. 12101 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 12102 << /*Constant*/ 1 12103 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 12104 return true; 12105 12106 case NK_Variable_Narrowing: 12107 // Implicit conversion to a narrower type, and the value is not a constant 12108 // expression. 12109 case NK_Type_Narrowing: 12110 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 12111 << /*Constant*/ 0 << FromType << ToType; 12112 // TODO: It's not a constant expression, but what if the user intended it 12113 // to be? Can we produce notes to help them figure out why it isn't? 12114 return true; 12115 } 12116 llvm_unreachable("unhandled case in switch"); 12117 } 12118 12119 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 12120 ExprResult &LHS, 12121 ExprResult &RHS, 12122 SourceLocation Loc) { 12123 QualType LHSType = LHS.get()->getType(); 12124 QualType RHSType = RHS.get()->getType(); 12125 // Dig out the original argument type and expression before implicit casts 12126 // were applied. These are the types/expressions we need to check the 12127 // [expr.spaceship] requirements against. 12128 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 12129 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 12130 QualType LHSStrippedType = LHSStripped.get()->getType(); 12131 QualType RHSStrippedType = RHSStripped.get()->getType(); 12132 12133 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 12134 // other is not, the program is ill-formed. 12135 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 12136 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 12137 return QualType(); 12138 } 12139 12140 // FIXME: Consider combining this with checkEnumArithmeticConversions. 12141 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 12142 RHSStrippedType->isEnumeralType(); 12143 if (NumEnumArgs == 1) { 12144 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 12145 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 12146 if (OtherTy->hasFloatingRepresentation()) { 12147 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 12148 return QualType(); 12149 } 12150 } 12151 if (NumEnumArgs == 2) { 12152 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 12153 // type E, the operator yields the result of converting the operands 12154 // to the underlying type of E and applying <=> to the converted operands. 12155 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 12156 S.InvalidOperands(Loc, LHS, RHS); 12157 return QualType(); 12158 } 12159 QualType IntType = 12160 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 12161 assert(IntType->isArithmeticType()); 12162 12163 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 12164 // promote the boolean type, and all other promotable integer types, to 12165 // avoid this. 12166 if (IntType->isPromotableIntegerType()) 12167 IntType = S.Context.getPromotedIntegerType(IntType); 12168 12169 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 12170 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 12171 LHSType = RHSType = IntType; 12172 } 12173 12174 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 12175 // usual arithmetic conversions are applied to the operands. 12176 QualType Type = 12177 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 12178 if (LHS.isInvalid() || RHS.isInvalid()) 12179 return QualType(); 12180 if (Type.isNull()) 12181 return S.InvalidOperands(Loc, LHS, RHS); 12182 12183 Optional<ComparisonCategoryType> CCT = 12184 getComparisonCategoryForBuiltinCmp(Type); 12185 if (!CCT) 12186 return S.InvalidOperands(Loc, LHS, RHS); 12187 12188 bool HasNarrowing = checkThreeWayNarrowingConversion( 12189 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 12190 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 12191 RHS.get()->getBeginLoc()); 12192 if (HasNarrowing) 12193 return QualType(); 12194 12195 assert(!Type.isNull() && "composite type for <=> has not been set"); 12196 12197 return S.CheckComparisonCategoryType( 12198 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 12199 } 12200 12201 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 12202 ExprResult &RHS, 12203 SourceLocation Loc, 12204 BinaryOperatorKind Opc) { 12205 if (Opc == BO_Cmp) 12206 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 12207 12208 // C99 6.5.8p3 / C99 6.5.9p4 12209 QualType Type = 12210 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 12211 if (LHS.isInvalid() || RHS.isInvalid()) 12212 return QualType(); 12213 if (Type.isNull()) 12214 return S.InvalidOperands(Loc, LHS, RHS); 12215 assert(Type->isArithmeticType() || Type->isEnumeralType()); 12216 12217 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 12218 return S.InvalidOperands(Loc, LHS, RHS); 12219 12220 // Check for comparisons of floating point operands using != and ==. 12221 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 12222 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); 12223 12224 // The result of comparisons is 'bool' in C++, 'int' in C. 12225 return S.Context.getLogicalOperationType(); 12226 } 12227 12228 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 12229 if (!NullE.get()->getType()->isAnyPointerType()) 12230 return; 12231 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 12232 if (!E.get()->getType()->isAnyPointerType() && 12233 E.get()->isNullPointerConstant(Context, 12234 Expr::NPC_ValueDependentIsNotNull) == 12235 Expr::NPCK_ZeroExpression) { 12236 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 12237 if (CL->getValue() == 0) 12238 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 12239 << NullValue 12240 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 12241 NullValue ? "NULL" : "(void *)0"); 12242 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 12243 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 12244 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 12245 if (T == Context.CharTy) 12246 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 12247 << NullValue 12248 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 12249 NullValue ? "NULL" : "(void *)0"); 12250 } 12251 } 12252 } 12253 12254 // C99 6.5.8, C++ [expr.rel] 12255 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 12256 SourceLocation Loc, 12257 BinaryOperatorKind Opc) { 12258 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 12259 bool IsThreeWay = Opc == BO_Cmp; 12260 bool IsOrdered = IsRelational || IsThreeWay; 12261 auto IsAnyPointerType = [](ExprResult E) { 12262 QualType Ty = E.get()->getType(); 12263 return Ty->isPointerType() || Ty->isMemberPointerType(); 12264 }; 12265 12266 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 12267 // type, array-to-pointer, ..., conversions are performed on both operands to 12268 // bring them to their composite type. 12269 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 12270 // any type-related checks. 12271 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 12272 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12273 if (LHS.isInvalid()) 12274 return QualType(); 12275 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12276 if (RHS.isInvalid()) 12277 return QualType(); 12278 } else { 12279 LHS = DefaultLvalueConversion(LHS.get()); 12280 if (LHS.isInvalid()) 12281 return QualType(); 12282 RHS = DefaultLvalueConversion(RHS.get()); 12283 if (RHS.isInvalid()) 12284 return QualType(); 12285 } 12286 12287 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 12288 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 12289 CheckPtrComparisonWithNullChar(LHS, RHS); 12290 CheckPtrComparisonWithNullChar(RHS, LHS); 12291 } 12292 12293 // Handle vector comparisons separately. 12294 if (LHS.get()->getType()->isVectorType() || 12295 RHS.get()->getType()->isVectorType()) 12296 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 12297 12298 if (LHS.get()->getType()->isVLSTBuiltinType() || 12299 RHS.get()->getType()->isVLSTBuiltinType()) 12300 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc); 12301 12302 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12303 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12304 12305 QualType LHSType = LHS.get()->getType(); 12306 QualType RHSType = RHS.get()->getType(); 12307 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 12308 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 12309 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 12310 12311 const Expr::NullPointerConstantKind LHSNullKind = 12312 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 12313 const Expr::NullPointerConstantKind RHSNullKind = 12314 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 12315 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 12316 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 12317 12318 auto computeResultTy = [&]() { 12319 if (Opc != BO_Cmp) 12320 return Context.getLogicalOperationType(); 12321 assert(getLangOpts().CPlusPlus); 12322 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 12323 12324 QualType CompositeTy = LHS.get()->getType(); 12325 assert(!CompositeTy->isReferenceType()); 12326 12327 Optional<ComparisonCategoryType> CCT = 12328 getComparisonCategoryForBuiltinCmp(CompositeTy); 12329 if (!CCT) 12330 return InvalidOperands(Loc, LHS, RHS); 12331 12332 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 12333 // P0946R0: Comparisons between a null pointer constant and an object 12334 // pointer result in std::strong_equality, which is ill-formed under 12335 // P1959R0. 12336 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 12337 << (LHSIsNull ? LHS.get()->getSourceRange() 12338 : RHS.get()->getSourceRange()); 12339 return QualType(); 12340 } 12341 12342 return CheckComparisonCategoryType( 12343 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 12344 }; 12345 12346 if (!IsOrdered && LHSIsNull != RHSIsNull) { 12347 bool IsEquality = Opc == BO_EQ; 12348 if (RHSIsNull) 12349 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 12350 RHS.get()->getSourceRange()); 12351 else 12352 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 12353 LHS.get()->getSourceRange()); 12354 } 12355 12356 if (IsOrdered && LHSType->isFunctionPointerType() && 12357 RHSType->isFunctionPointerType()) { 12358 // Valid unless a relational comparison of function pointers 12359 bool IsError = Opc == BO_Cmp; 12360 auto DiagID = 12361 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 12362 : getLangOpts().CPlusPlus 12363 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 12364 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 12365 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 12366 << RHS.get()->getSourceRange(); 12367 if (IsError) 12368 return QualType(); 12369 } 12370 12371 if ((LHSType->isIntegerType() && !LHSIsNull) || 12372 (RHSType->isIntegerType() && !RHSIsNull)) { 12373 // Skip normal pointer conversion checks in this case; we have better 12374 // diagnostics for this below. 12375 } else if (getLangOpts().CPlusPlus) { 12376 // Equality comparison of a function pointer to a void pointer is invalid, 12377 // but we allow it as an extension. 12378 // FIXME: If we really want to allow this, should it be part of composite 12379 // pointer type computation so it works in conditionals too? 12380 if (!IsOrdered && 12381 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 12382 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 12383 // This is a gcc extension compatibility comparison. 12384 // In a SFINAE context, we treat this as a hard error to maintain 12385 // conformance with the C++ standard. 12386 diagnoseFunctionPointerToVoidComparison( 12387 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 12388 12389 if (isSFINAEContext()) 12390 return QualType(); 12391 12392 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12393 return computeResultTy(); 12394 } 12395 12396 // C++ [expr.eq]p2: 12397 // If at least one operand is a pointer [...] bring them to their 12398 // composite pointer type. 12399 // C++ [expr.spaceship]p6 12400 // If at least one of the operands is of pointer type, [...] bring them 12401 // to their composite pointer type. 12402 // C++ [expr.rel]p2: 12403 // If both operands are pointers, [...] bring them to their composite 12404 // pointer type. 12405 // For <=>, the only valid non-pointer types are arrays and functions, and 12406 // we already decayed those, so this is really the same as the relational 12407 // comparison rule. 12408 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 12409 (IsOrdered ? 2 : 1) && 12410 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 12411 RHSType->isObjCObjectPointerType()))) { 12412 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12413 return QualType(); 12414 return computeResultTy(); 12415 } 12416 } else if (LHSType->isPointerType() && 12417 RHSType->isPointerType()) { // C99 6.5.8p2 12418 // All of the following pointer-related warnings are GCC extensions, except 12419 // when handling null pointer constants. 12420 QualType LCanPointeeTy = 12421 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 12422 QualType RCanPointeeTy = 12423 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 12424 12425 // C99 6.5.9p2 and C99 6.5.8p2 12426 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 12427 RCanPointeeTy.getUnqualifiedType())) { 12428 if (IsRelational) { 12429 // Pointers both need to point to complete or incomplete types 12430 if ((LCanPointeeTy->isIncompleteType() != 12431 RCanPointeeTy->isIncompleteType()) && 12432 !getLangOpts().C11) { 12433 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 12434 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 12435 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 12436 << RCanPointeeTy->isIncompleteType(); 12437 } 12438 } 12439 } else if (!IsRelational && 12440 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 12441 // Valid unless comparison between non-null pointer and function pointer 12442 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 12443 && !LHSIsNull && !RHSIsNull) 12444 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 12445 /*isError*/false); 12446 } else { 12447 // Invalid 12448 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 12449 } 12450 if (LCanPointeeTy != RCanPointeeTy) { 12451 // Treat NULL constant as a special case in OpenCL. 12452 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 12453 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 12454 Diag(Loc, 12455 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 12456 << LHSType << RHSType << 0 /* comparison */ 12457 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 12458 } 12459 } 12460 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 12461 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 12462 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 12463 : CK_BitCast; 12464 if (LHSIsNull && !RHSIsNull) 12465 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 12466 else 12467 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 12468 } 12469 return computeResultTy(); 12470 } 12471 12472 if (getLangOpts().CPlusPlus) { 12473 // C++ [expr.eq]p4: 12474 // Two operands of type std::nullptr_t or one operand of type 12475 // std::nullptr_t and the other a null pointer constant compare equal. 12476 if (!IsOrdered && LHSIsNull && RHSIsNull) { 12477 if (LHSType->isNullPtrType()) { 12478 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12479 return computeResultTy(); 12480 } 12481 if (RHSType->isNullPtrType()) { 12482 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12483 return computeResultTy(); 12484 } 12485 } 12486 12487 // Comparison of Objective-C pointers and block pointers against nullptr_t. 12488 // These aren't covered by the composite pointer type rules. 12489 if (!IsOrdered && RHSType->isNullPtrType() && 12490 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 12491 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12492 return computeResultTy(); 12493 } 12494 if (!IsOrdered && LHSType->isNullPtrType() && 12495 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 12496 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12497 return computeResultTy(); 12498 } 12499 12500 if (IsRelational && 12501 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 12502 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 12503 // HACK: Relational comparison of nullptr_t against a pointer type is 12504 // invalid per DR583, but we allow it within std::less<> and friends, 12505 // since otherwise common uses of it break. 12506 // FIXME: Consider removing this hack once LWG fixes std::less<> and 12507 // friends to have std::nullptr_t overload candidates. 12508 DeclContext *DC = CurContext; 12509 if (isa<FunctionDecl>(DC)) 12510 DC = DC->getParent(); 12511 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 12512 if (CTSD->isInStdNamespace() && 12513 llvm::StringSwitch<bool>(CTSD->getName()) 12514 .Cases("less", "less_equal", "greater", "greater_equal", true) 12515 .Default(false)) { 12516 if (RHSType->isNullPtrType()) 12517 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12518 else 12519 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12520 return computeResultTy(); 12521 } 12522 } 12523 } 12524 12525 // C++ [expr.eq]p2: 12526 // If at least one operand is a pointer to member, [...] bring them to 12527 // their composite pointer type. 12528 if (!IsOrdered && 12529 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 12530 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12531 return QualType(); 12532 else 12533 return computeResultTy(); 12534 } 12535 } 12536 12537 // Handle block pointer types. 12538 if (!IsOrdered && LHSType->isBlockPointerType() && 12539 RHSType->isBlockPointerType()) { 12540 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 12541 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 12542 12543 if (!LHSIsNull && !RHSIsNull && 12544 !Context.typesAreCompatible(lpointee, rpointee)) { 12545 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12546 << LHSType << RHSType << LHS.get()->getSourceRange() 12547 << RHS.get()->getSourceRange(); 12548 } 12549 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12550 return computeResultTy(); 12551 } 12552 12553 // Allow block pointers to be compared with null pointer constants. 12554 if (!IsOrdered 12555 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 12556 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 12557 if (!LHSIsNull && !RHSIsNull) { 12558 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 12559 ->getPointeeType()->isVoidType()) 12560 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12561 ->getPointeeType()->isVoidType()))) 12562 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12563 << LHSType << RHSType << LHS.get()->getSourceRange() 12564 << RHS.get()->getSourceRange(); 12565 } 12566 if (LHSIsNull && !RHSIsNull) 12567 LHS = ImpCastExprToType(LHS.get(), RHSType, 12568 RHSType->isPointerType() ? CK_BitCast 12569 : CK_AnyPointerToBlockPointerCast); 12570 else 12571 RHS = ImpCastExprToType(RHS.get(), LHSType, 12572 LHSType->isPointerType() ? CK_BitCast 12573 : CK_AnyPointerToBlockPointerCast); 12574 return computeResultTy(); 12575 } 12576 12577 if (LHSType->isObjCObjectPointerType() || 12578 RHSType->isObjCObjectPointerType()) { 12579 const PointerType *LPT = LHSType->getAs<PointerType>(); 12580 const PointerType *RPT = RHSType->getAs<PointerType>(); 12581 if (LPT || RPT) { 12582 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12583 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12584 12585 if (!LPtrToVoid && !RPtrToVoid && 12586 !Context.typesAreCompatible(LHSType, RHSType)) { 12587 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12588 /*isError*/false); 12589 } 12590 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12591 // the RHS, but we have test coverage for this behavior. 12592 // FIXME: Consider using convertPointersToCompositeType in C++. 12593 if (LHSIsNull && !RHSIsNull) { 12594 Expr *E = LHS.get(); 12595 if (getLangOpts().ObjCAutoRefCount) 12596 CheckObjCConversion(SourceRange(), RHSType, E, 12597 CCK_ImplicitConversion); 12598 LHS = ImpCastExprToType(E, RHSType, 12599 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12600 } 12601 else { 12602 Expr *E = RHS.get(); 12603 if (getLangOpts().ObjCAutoRefCount) 12604 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12605 /*Diagnose=*/true, 12606 /*DiagnoseCFAudited=*/false, Opc); 12607 RHS = ImpCastExprToType(E, LHSType, 12608 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12609 } 12610 return computeResultTy(); 12611 } 12612 if (LHSType->isObjCObjectPointerType() && 12613 RHSType->isObjCObjectPointerType()) { 12614 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12615 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12616 /*isError*/false); 12617 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12618 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12619 12620 if (LHSIsNull && !RHSIsNull) 12621 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12622 else 12623 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12624 return computeResultTy(); 12625 } 12626 12627 if (!IsOrdered && LHSType->isBlockPointerType() && 12628 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12629 LHS = ImpCastExprToType(LHS.get(), RHSType, 12630 CK_BlockPointerToObjCPointerCast); 12631 return computeResultTy(); 12632 } else if (!IsOrdered && 12633 LHSType->isBlockCompatibleObjCPointerType(Context) && 12634 RHSType->isBlockPointerType()) { 12635 RHS = ImpCastExprToType(RHS.get(), LHSType, 12636 CK_BlockPointerToObjCPointerCast); 12637 return computeResultTy(); 12638 } 12639 } 12640 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12641 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12642 unsigned DiagID = 0; 12643 bool isError = false; 12644 if (LangOpts.DebuggerSupport) { 12645 // Under a debugger, allow the comparison of pointers to integers, 12646 // since users tend to want to compare addresses. 12647 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12648 (RHSIsNull && RHSType->isIntegerType())) { 12649 if (IsOrdered) { 12650 isError = getLangOpts().CPlusPlus; 12651 DiagID = 12652 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12653 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12654 } 12655 } else if (getLangOpts().CPlusPlus) { 12656 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12657 isError = true; 12658 } else if (IsOrdered) 12659 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12660 else 12661 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12662 12663 if (DiagID) { 12664 Diag(Loc, DiagID) 12665 << LHSType << RHSType << LHS.get()->getSourceRange() 12666 << RHS.get()->getSourceRange(); 12667 if (isError) 12668 return QualType(); 12669 } 12670 12671 if (LHSType->isIntegerType()) 12672 LHS = ImpCastExprToType(LHS.get(), RHSType, 12673 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12674 else 12675 RHS = ImpCastExprToType(RHS.get(), LHSType, 12676 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12677 return computeResultTy(); 12678 } 12679 12680 // Handle block pointers. 12681 if (!IsOrdered && RHSIsNull 12682 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12683 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12684 return computeResultTy(); 12685 } 12686 if (!IsOrdered && LHSIsNull 12687 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12688 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12689 return computeResultTy(); 12690 } 12691 12692 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 12693 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12694 return computeResultTy(); 12695 } 12696 12697 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12698 return computeResultTy(); 12699 } 12700 12701 if (LHSIsNull && RHSType->isQueueT()) { 12702 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12703 return computeResultTy(); 12704 } 12705 12706 if (LHSType->isQueueT() && RHSIsNull) { 12707 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12708 return computeResultTy(); 12709 } 12710 } 12711 12712 return InvalidOperands(Loc, LHS, RHS); 12713 } 12714 12715 // Return a signed ext_vector_type that is of identical size and number of 12716 // elements. For floating point vectors, return an integer type of identical 12717 // size and number of elements. In the non ext_vector_type case, search from 12718 // the largest type to the smallest type to avoid cases where long long == long, 12719 // where long gets picked over long long. 12720 QualType Sema::GetSignedVectorType(QualType V) { 12721 const VectorType *VTy = V->castAs<VectorType>(); 12722 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12723 12724 if (isa<ExtVectorType>(VTy)) { 12725 if (VTy->isExtVectorBoolType()) 12726 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements()); 12727 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12728 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12729 if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12730 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12731 if (TypeSize == Context.getTypeSize(Context.IntTy)) 12732 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12733 if (TypeSize == Context.getTypeSize(Context.Int128Ty)) 12734 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements()); 12735 if (TypeSize == Context.getTypeSize(Context.LongTy)) 12736 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12737 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12738 "Unhandled vector element size in vector compare"); 12739 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12740 } 12741 12742 if (TypeSize == Context.getTypeSize(Context.Int128Ty)) 12743 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(), 12744 VectorType::GenericVector); 12745 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12746 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12747 VectorType::GenericVector); 12748 if (TypeSize == Context.getTypeSize(Context.LongTy)) 12749 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12750 VectorType::GenericVector); 12751 if (TypeSize == Context.getTypeSize(Context.IntTy)) 12752 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12753 VectorType::GenericVector); 12754 if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12755 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12756 VectorType::GenericVector); 12757 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12758 "Unhandled vector element size in vector compare"); 12759 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12760 VectorType::GenericVector); 12761 } 12762 12763 QualType Sema::GetSignedSizelessVectorType(QualType V) { 12764 const BuiltinType *VTy = V->castAs<BuiltinType>(); 12765 assert(VTy->isSizelessBuiltinType() && "expected sizeless type"); 12766 12767 const QualType ETy = V->getSveEltType(Context); 12768 const auto TypeSize = Context.getTypeSize(ETy); 12769 12770 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true); 12771 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC; 12772 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue()); 12773 } 12774 12775 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12776 /// operates on extended vector types. Instead of producing an IntTy result, 12777 /// like a scalar comparison, a vector comparison produces a vector of integer 12778 /// types. 12779 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12780 SourceLocation Loc, 12781 BinaryOperatorKind Opc) { 12782 if (Opc == BO_Cmp) { 12783 Diag(Loc, diag::err_three_way_vector_comparison); 12784 return QualType(); 12785 } 12786 12787 // Check to make sure we're operating on vectors of the same type and width, 12788 // Allowing one side to be a scalar of element type. 12789 QualType vType = 12790 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false, 12791 /*AllowBothBool*/ true, 12792 /*AllowBoolConversions*/ getLangOpts().ZVector, 12793 /*AllowBooleanOperation*/ true, 12794 /*ReportInvalid*/ true); 12795 if (vType.isNull()) 12796 return vType; 12797 12798 QualType LHSType = LHS.get()->getType(); 12799 12800 // Determine the return type of a vector compare. By default clang will return 12801 // a scalar for all vector compares except vector bool and vector pixel. 12802 // With the gcc compiler we will always return a vector type and with the xl 12803 // compiler we will always return a scalar type. This switch allows choosing 12804 // which behavior is prefered. 12805 if (getLangOpts().AltiVec) { 12806 switch (getLangOpts().getAltivecSrcCompat()) { 12807 case LangOptions::AltivecSrcCompatKind::Mixed: 12808 // If AltiVec, the comparison results in a numeric type, i.e. 12809 // bool for C++, int for C 12810 if (vType->castAs<VectorType>()->getVectorKind() == 12811 VectorType::AltiVecVector) 12812 return Context.getLogicalOperationType(); 12813 else 12814 Diag(Loc, diag::warn_deprecated_altivec_src_compat); 12815 break; 12816 case LangOptions::AltivecSrcCompatKind::GCC: 12817 // For GCC we always return the vector type. 12818 break; 12819 case LangOptions::AltivecSrcCompatKind::XL: 12820 return Context.getLogicalOperationType(); 12821 break; 12822 } 12823 } 12824 12825 // For non-floating point types, check for self-comparisons of the form 12826 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12827 // often indicate logic errors in the program. 12828 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12829 12830 // Check for comparisons of floating point operands using != and ==. 12831 if (BinaryOperator::isEqualityOp(Opc) && 12832 LHSType->hasFloatingRepresentation()) { 12833 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12834 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); 12835 } 12836 12837 // Return a signed type for the vector. 12838 return GetSignedVectorType(vType); 12839 } 12840 12841 QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS, 12842 ExprResult &RHS, 12843 SourceLocation Loc, 12844 BinaryOperatorKind Opc) { 12845 if (Opc == BO_Cmp) { 12846 Diag(Loc, diag::err_three_way_vector_comparison); 12847 return QualType(); 12848 } 12849 12850 // Check to make sure we're operating on vectors of the same type and width, 12851 // Allowing one side to be a scalar of element type. 12852 QualType vType = CheckSizelessVectorOperands( 12853 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison); 12854 12855 if (vType.isNull()) 12856 return vType; 12857 12858 QualType LHSType = LHS.get()->getType(); 12859 12860 // For non-floating point types, check for self-comparisons of the form 12861 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12862 // often indicate logic errors in the program. 12863 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12864 12865 // Check for comparisons of floating point operands using != and ==. 12866 if (BinaryOperator::isEqualityOp(Opc) && 12867 LHSType->hasFloatingRepresentation()) { 12868 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12869 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); 12870 } 12871 12872 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); 12873 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>(); 12874 12875 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() && 12876 RHSBuiltinTy->isSVEBool()) 12877 return LHSType; 12878 12879 // Return a signed type for the vector. 12880 return GetSignedSizelessVectorType(vType); 12881 } 12882 12883 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12884 const ExprResult &XorRHS, 12885 const SourceLocation Loc) { 12886 // Do not diagnose macros. 12887 if (Loc.isMacroID()) 12888 return; 12889 12890 // Do not diagnose if both LHS and RHS are macros. 12891 if (XorLHS.get()->getExprLoc().isMacroID() && 12892 XorRHS.get()->getExprLoc().isMacroID()) 12893 return; 12894 12895 bool Negative = false; 12896 bool ExplicitPlus = false; 12897 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12898 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12899 12900 if (!LHSInt) 12901 return; 12902 if (!RHSInt) { 12903 // Check negative literals. 12904 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12905 UnaryOperatorKind Opc = UO->getOpcode(); 12906 if (Opc != UO_Minus && Opc != UO_Plus) 12907 return; 12908 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12909 if (!RHSInt) 12910 return; 12911 Negative = (Opc == UO_Minus); 12912 ExplicitPlus = !Negative; 12913 } else { 12914 return; 12915 } 12916 } 12917 12918 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12919 llvm::APInt RightSideValue = RHSInt->getValue(); 12920 if (LeftSideValue != 2 && LeftSideValue != 10) 12921 return; 12922 12923 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12924 return; 12925 12926 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12927 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12928 llvm::StringRef ExprStr = 12929 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12930 12931 CharSourceRange XorRange = 12932 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12933 llvm::StringRef XorStr = 12934 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12935 // Do not diagnose if xor keyword/macro is used. 12936 if (XorStr == "xor") 12937 return; 12938 12939 std::string LHSStr = std::string(Lexer::getSourceText( 12940 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12941 S.getSourceManager(), S.getLangOpts())); 12942 std::string RHSStr = std::string(Lexer::getSourceText( 12943 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12944 S.getSourceManager(), S.getLangOpts())); 12945 12946 if (Negative) { 12947 RightSideValue = -RightSideValue; 12948 RHSStr = "-" + RHSStr; 12949 } else if (ExplicitPlus) { 12950 RHSStr = "+" + RHSStr; 12951 } 12952 12953 StringRef LHSStrRef = LHSStr; 12954 StringRef RHSStrRef = RHSStr; 12955 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12956 // literals. 12957 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12958 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12959 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12960 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12961 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12962 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12963 LHSStrRef.contains('\'') || RHSStrRef.contains('\'')) 12964 return; 12965 12966 bool SuggestXor = 12967 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12968 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12969 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12970 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12971 std::string SuggestedExpr = "1 << " + RHSStr; 12972 bool Overflow = false; 12973 llvm::APInt One = (LeftSideValue - 1); 12974 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12975 if (Overflow) { 12976 if (RightSideIntValue < 64) 12977 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12978 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 12979 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12980 else if (RightSideIntValue == 64) 12981 S.Diag(Loc, diag::warn_xor_used_as_pow) 12982 << ExprStr << toString(XorValue, 10, true); 12983 else 12984 return; 12985 } else { 12986 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12987 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 12988 << toString(PowValue, 10, true) 12989 << FixItHint::CreateReplacement( 12990 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12991 } 12992 12993 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12994 << ("0x2 ^ " + RHSStr) << SuggestXor; 12995 } else if (LeftSideValue == 10) { 12996 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12997 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12998 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 12999 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 13000 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 13001 << ("0xA ^ " + RHSStr) << SuggestXor; 13002 } 13003 } 13004 13005 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 13006 SourceLocation Loc) { 13007 // Ensure that either both operands are of the same vector type, or 13008 // one operand is of a vector type and the other is of its element type. 13009 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 13010 /*AllowBothBool*/ true, 13011 /*AllowBoolConversions*/ false, 13012 /*AllowBooleanOperation*/ false, 13013 /*ReportInvalid*/ false); 13014 if (vType.isNull()) 13015 return InvalidOperands(Loc, LHS, RHS); 13016 if (getLangOpts().OpenCL && 13017 getLangOpts().getOpenCLCompatibleVersion() < 120 && 13018 vType->hasFloatingRepresentation()) 13019 return InvalidOperands(Loc, LHS, RHS); 13020 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 13021 // usage of the logical operators && and || with vectors in C. This 13022 // check could be notionally dropped. 13023 if (!getLangOpts().CPlusPlus && 13024 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 13025 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 13026 13027 return GetSignedVectorType(LHS.get()->getType()); 13028 } 13029 13030 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 13031 SourceLocation Loc, 13032 bool IsCompAssign) { 13033 if (!IsCompAssign) { 13034 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 13035 if (LHS.isInvalid()) 13036 return QualType(); 13037 } 13038 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 13039 if (RHS.isInvalid()) 13040 return QualType(); 13041 13042 // For conversion purposes, we ignore any qualifiers. 13043 // For example, "const float" and "float" are equivalent. 13044 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 13045 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 13046 13047 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 13048 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 13049 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 13050 13051 if (Context.hasSameType(LHSType, RHSType)) 13052 return LHSType; 13053 13054 // Type conversion may change LHS/RHS. Keep copies to the original results, in 13055 // case we have to return InvalidOperands. 13056 ExprResult OriginalLHS = LHS; 13057 ExprResult OriginalRHS = RHS; 13058 if (LHSMatType && !RHSMatType) { 13059 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 13060 if (!RHS.isInvalid()) 13061 return LHSType; 13062 13063 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 13064 } 13065 13066 if (!LHSMatType && RHSMatType) { 13067 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 13068 if (!LHS.isInvalid()) 13069 return RHSType; 13070 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 13071 } 13072 13073 return InvalidOperands(Loc, LHS, RHS); 13074 } 13075 13076 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 13077 SourceLocation Loc, 13078 bool IsCompAssign) { 13079 if (!IsCompAssign) { 13080 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 13081 if (LHS.isInvalid()) 13082 return QualType(); 13083 } 13084 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 13085 if (RHS.isInvalid()) 13086 return QualType(); 13087 13088 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 13089 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 13090 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 13091 13092 if (LHSMatType && RHSMatType) { 13093 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 13094 return InvalidOperands(Loc, LHS, RHS); 13095 13096 if (!Context.hasSameType(LHSMatType->getElementType(), 13097 RHSMatType->getElementType())) 13098 return InvalidOperands(Loc, LHS, RHS); 13099 13100 return Context.getConstantMatrixType(LHSMatType->getElementType(), 13101 LHSMatType->getNumRows(), 13102 RHSMatType->getNumColumns()); 13103 } 13104 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 13105 } 13106 13107 static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) { 13108 switch (Opc) { 13109 default: 13110 return false; 13111 case BO_And: 13112 case BO_AndAssign: 13113 case BO_Or: 13114 case BO_OrAssign: 13115 case BO_Xor: 13116 case BO_XorAssign: 13117 return true; 13118 } 13119 } 13120 13121 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 13122 SourceLocation Loc, 13123 BinaryOperatorKind Opc) { 13124 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 13125 13126 bool IsCompAssign = 13127 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 13128 13129 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc); 13130 13131 if (LHS.get()->getType()->isVectorType() || 13132 RHS.get()->getType()->isVectorType()) { 13133 if (LHS.get()->getType()->hasIntegerRepresentation() && 13134 RHS.get()->getType()->hasIntegerRepresentation()) 13135 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 13136 /*AllowBothBool*/ true, 13137 /*AllowBoolConversions*/ getLangOpts().ZVector, 13138 /*AllowBooleanOperation*/ LegalBoolVecOperator, 13139 /*ReportInvalid*/ true); 13140 return InvalidOperands(Loc, LHS, RHS); 13141 } 13142 13143 if (LHS.get()->getType()->isVLSTBuiltinType() || 13144 RHS.get()->getType()->isVLSTBuiltinType()) { 13145 if (LHS.get()->getType()->hasIntegerRepresentation() && 13146 RHS.get()->getType()->hasIntegerRepresentation()) 13147 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 13148 ACK_BitwiseOp); 13149 return InvalidOperands(Loc, LHS, RHS); 13150 } 13151 13152 if (LHS.get()->getType()->isVLSTBuiltinType() || 13153 RHS.get()->getType()->isVLSTBuiltinType()) { 13154 if (LHS.get()->getType()->hasIntegerRepresentation() && 13155 RHS.get()->getType()->hasIntegerRepresentation()) 13156 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 13157 ACK_BitwiseOp); 13158 return InvalidOperands(Loc, LHS, RHS); 13159 } 13160 13161 if (Opc == BO_And) 13162 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 13163 13164 if (LHS.get()->getType()->hasFloatingRepresentation() || 13165 RHS.get()->getType()->hasFloatingRepresentation()) 13166 return InvalidOperands(Loc, LHS, RHS); 13167 13168 ExprResult LHSResult = LHS, RHSResult = RHS; 13169 QualType compType = UsualArithmeticConversions( 13170 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 13171 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 13172 return QualType(); 13173 LHS = LHSResult.get(); 13174 RHS = RHSResult.get(); 13175 13176 if (Opc == BO_Xor) 13177 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 13178 13179 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 13180 return compType; 13181 return InvalidOperands(Loc, LHS, RHS); 13182 } 13183 13184 // C99 6.5.[13,14] 13185 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 13186 SourceLocation Loc, 13187 BinaryOperatorKind Opc) { 13188 // Check vector operands differently. 13189 if (LHS.get()->getType()->isVectorType() || 13190 RHS.get()->getType()->isVectorType()) 13191 return CheckVectorLogicalOperands(LHS, RHS, Loc); 13192 13193 bool EnumConstantInBoolContext = false; 13194 for (const ExprResult &HS : {LHS, RHS}) { 13195 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 13196 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 13197 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 13198 EnumConstantInBoolContext = true; 13199 } 13200 } 13201 13202 if (EnumConstantInBoolContext) 13203 Diag(Loc, diag::warn_enum_constant_in_bool_context); 13204 13205 // Diagnose cases where the user write a logical and/or but probably meant a 13206 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 13207 // is a constant. 13208 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 13209 !LHS.get()->getType()->isBooleanType() && 13210 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 13211 // Don't warn in macros or template instantiations. 13212 !Loc.isMacroID() && !inTemplateInstantiation()) { 13213 // If the RHS can be constant folded, and if it constant folds to something 13214 // that isn't 0 or 1 (which indicate a potential logical operation that 13215 // happened to fold to true/false) then warn. 13216 // Parens on the RHS are ignored. 13217 Expr::EvalResult EVResult; 13218 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 13219 llvm::APSInt Result = EVResult.Val.getInt(); 13220 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 13221 !RHS.get()->getExprLoc().isMacroID()) || 13222 (Result != 0 && Result != 1)) { 13223 Diag(Loc, diag::warn_logical_instead_of_bitwise) 13224 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||"); 13225 // Suggest replacing the logical operator with the bitwise version 13226 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 13227 << (Opc == BO_LAnd ? "&" : "|") 13228 << FixItHint::CreateReplacement( 13229 SourceRange(Loc, getLocForEndOfToken(Loc)), 13230 Opc == BO_LAnd ? "&" : "|"); 13231 if (Opc == BO_LAnd) 13232 // Suggest replacing "Foo() && kNonZero" with "Foo()" 13233 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 13234 << FixItHint::CreateRemoval( 13235 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 13236 RHS.get()->getEndLoc())); 13237 } 13238 } 13239 } 13240 13241 if (!Context.getLangOpts().CPlusPlus) { 13242 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 13243 // not operate on the built-in scalar and vector float types. 13244 if (Context.getLangOpts().OpenCL && 13245 Context.getLangOpts().OpenCLVersion < 120) { 13246 if (LHS.get()->getType()->isFloatingType() || 13247 RHS.get()->getType()->isFloatingType()) 13248 return InvalidOperands(Loc, LHS, RHS); 13249 } 13250 13251 LHS = UsualUnaryConversions(LHS.get()); 13252 if (LHS.isInvalid()) 13253 return QualType(); 13254 13255 RHS = UsualUnaryConversions(RHS.get()); 13256 if (RHS.isInvalid()) 13257 return QualType(); 13258 13259 if (!LHS.get()->getType()->isScalarType() || 13260 !RHS.get()->getType()->isScalarType()) 13261 return InvalidOperands(Loc, LHS, RHS); 13262 13263 return Context.IntTy; 13264 } 13265 13266 // The following is safe because we only use this method for 13267 // non-overloadable operands. 13268 13269 // C++ [expr.log.and]p1 13270 // C++ [expr.log.or]p1 13271 // The operands are both contextually converted to type bool. 13272 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 13273 if (LHSRes.isInvalid()) 13274 return InvalidOperands(Loc, LHS, RHS); 13275 LHS = LHSRes; 13276 13277 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 13278 if (RHSRes.isInvalid()) 13279 return InvalidOperands(Loc, LHS, RHS); 13280 RHS = RHSRes; 13281 13282 // C++ [expr.log.and]p2 13283 // C++ [expr.log.or]p2 13284 // The result is a bool. 13285 return Context.BoolTy; 13286 } 13287 13288 static bool IsReadonlyMessage(Expr *E, Sema &S) { 13289 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 13290 if (!ME) return false; 13291 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 13292 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 13293 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 13294 if (!Base) return false; 13295 return Base->getMethodDecl() != nullptr; 13296 } 13297 13298 /// Is the given expression (which must be 'const') a reference to a 13299 /// variable which was originally non-const, but which has become 13300 /// 'const' due to being captured within a block? 13301 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 13302 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 13303 assert(E->isLValue() && E->getType().isConstQualified()); 13304 E = E->IgnoreParens(); 13305 13306 // Must be a reference to a declaration from an enclosing scope. 13307 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 13308 if (!DRE) return NCCK_None; 13309 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 13310 13311 // The declaration must be a variable which is not declared 'const'. 13312 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 13313 if (!var) return NCCK_None; 13314 if (var->getType().isConstQualified()) return NCCK_None; 13315 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 13316 13317 // Decide whether the first capture was for a block or a lambda. 13318 DeclContext *DC = S.CurContext, *Prev = nullptr; 13319 // Decide whether the first capture was for a block or a lambda. 13320 while (DC) { 13321 // For init-capture, it is possible that the variable belongs to the 13322 // template pattern of the current context. 13323 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 13324 if (var->isInitCapture() && 13325 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 13326 break; 13327 if (DC == var->getDeclContext()) 13328 break; 13329 Prev = DC; 13330 DC = DC->getParent(); 13331 } 13332 // Unless we have an init-capture, we've gone one step too far. 13333 if (!var->isInitCapture()) 13334 DC = Prev; 13335 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 13336 } 13337 13338 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 13339 Ty = Ty.getNonReferenceType(); 13340 if (IsDereference && Ty->isPointerType()) 13341 Ty = Ty->getPointeeType(); 13342 return !Ty.isConstQualified(); 13343 } 13344 13345 // Update err_typecheck_assign_const and note_typecheck_assign_const 13346 // when this enum is changed. 13347 enum { 13348 ConstFunction, 13349 ConstVariable, 13350 ConstMember, 13351 ConstMethod, 13352 NestedConstMember, 13353 ConstUnknown, // Keep as last element 13354 }; 13355 13356 /// Emit the "read-only variable not assignable" error and print notes to give 13357 /// more information about why the variable is not assignable, such as pointing 13358 /// to the declaration of a const variable, showing that a method is const, or 13359 /// that the function is returning a const reference. 13360 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 13361 SourceLocation Loc) { 13362 SourceRange ExprRange = E->getSourceRange(); 13363 13364 // Only emit one error on the first const found. All other consts will emit 13365 // a note to the error. 13366 bool DiagnosticEmitted = false; 13367 13368 // Track if the current expression is the result of a dereference, and if the 13369 // next checked expression is the result of a dereference. 13370 bool IsDereference = false; 13371 bool NextIsDereference = false; 13372 13373 // Loop to process MemberExpr chains. 13374 while (true) { 13375 IsDereference = NextIsDereference; 13376 13377 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 13378 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13379 NextIsDereference = ME->isArrow(); 13380 const ValueDecl *VD = ME->getMemberDecl(); 13381 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 13382 // Mutable fields can be modified even if the class is const. 13383 if (Field->isMutable()) { 13384 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 13385 break; 13386 } 13387 13388 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 13389 if (!DiagnosticEmitted) { 13390 S.Diag(Loc, diag::err_typecheck_assign_const) 13391 << ExprRange << ConstMember << false /*static*/ << Field 13392 << Field->getType(); 13393 DiagnosticEmitted = true; 13394 } 13395 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 13396 << ConstMember << false /*static*/ << Field << Field->getType() 13397 << Field->getSourceRange(); 13398 } 13399 E = ME->getBase(); 13400 continue; 13401 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 13402 if (VDecl->getType().isConstQualified()) { 13403 if (!DiagnosticEmitted) { 13404 S.Diag(Loc, diag::err_typecheck_assign_const) 13405 << ExprRange << ConstMember << true /*static*/ << VDecl 13406 << VDecl->getType(); 13407 DiagnosticEmitted = true; 13408 } 13409 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 13410 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 13411 << VDecl->getSourceRange(); 13412 } 13413 // Static fields do not inherit constness from parents. 13414 break; 13415 } 13416 break; // End MemberExpr 13417 } else if (const ArraySubscriptExpr *ASE = 13418 dyn_cast<ArraySubscriptExpr>(E)) { 13419 E = ASE->getBase()->IgnoreParenImpCasts(); 13420 continue; 13421 } else if (const ExtVectorElementExpr *EVE = 13422 dyn_cast<ExtVectorElementExpr>(E)) { 13423 E = EVE->getBase()->IgnoreParenImpCasts(); 13424 continue; 13425 } 13426 break; 13427 } 13428 13429 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 13430 // Function calls 13431 const FunctionDecl *FD = CE->getDirectCallee(); 13432 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 13433 if (!DiagnosticEmitted) { 13434 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 13435 << ConstFunction << FD; 13436 DiagnosticEmitted = true; 13437 } 13438 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 13439 diag::note_typecheck_assign_const) 13440 << ConstFunction << FD << FD->getReturnType() 13441 << FD->getReturnTypeSourceRange(); 13442 } 13443 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13444 // Point to variable declaration. 13445 if (const ValueDecl *VD = DRE->getDecl()) { 13446 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 13447 if (!DiagnosticEmitted) { 13448 S.Diag(Loc, diag::err_typecheck_assign_const) 13449 << ExprRange << ConstVariable << VD << VD->getType(); 13450 DiagnosticEmitted = true; 13451 } 13452 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 13453 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 13454 } 13455 } 13456 } else if (isa<CXXThisExpr>(E)) { 13457 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 13458 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 13459 if (MD->isConst()) { 13460 if (!DiagnosticEmitted) { 13461 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 13462 << ConstMethod << MD; 13463 DiagnosticEmitted = true; 13464 } 13465 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 13466 << ConstMethod << MD << MD->getSourceRange(); 13467 } 13468 } 13469 } 13470 } 13471 13472 if (DiagnosticEmitted) 13473 return; 13474 13475 // Can't determine a more specific message, so display the generic error. 13476 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 13477 } 13478 13479 enum OriginalExprKind { 13480 OEK_Variable, 13481 OEK_Member, 13482 OEK_LValue 13483 }; 13484 13485 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 13486 const RecordType *Ty, 13487 SourceLocation Loc, SourceRange Range, 13488 OriginalExprKind OEK, 13489 bool &DiagnosticEmitted) { 13490 std::vector<const RecordType *> RecordTypeList; 13491 RecordTypeList.push_back(Ty); 13492 unsigned NextToCheckIndex = 0; 13493 // We walk the record hierarchy breadth-first to ensure that we print 13494 // diagnostics in field nesting order. 13495 while (RecordTypeList.size() > NextToCheckIndex) { 13496 bool IsNested = NextToCheckIndex > 0; 13497 for (const FieldDecl *Field : 13498 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 13499 // First, check every field for constness. 13500 QualType FieldTy = Field->getType(); 13501 if (FieldTy.isConstQualified()) { 13502 if (!DiagnosticEmitted) { 13503 S.Diag(Loc, diag::err_typecheck_assign_const) 13504 << Range << NestedConstMember << OEK << VD 13505 << IsNested << Field; 13506 DiagnosticEmitted = true; 13507 } 13508 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 13509 << NestedConstMember << IsNested << Field 13510 << FieldTy << Field->getSourceRange(); 13511 } 13512 13513 // Then we append it to the list to check next in order. 13514 FieldTy = FieldTy.getCanonicalType(); 13515 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 13516 if (!llvm::is_contained(RecordTypeList, FieldRecTy)) 13517 RecordTypeList.push_back(FieldRecTy); 13518 } 13519 } 13520 ++NextToCheckIndex; 13521 } 13522 } 13523 13524 /// Emit an error for the case where a record we are trying to assign to has a 13525 /// const-qualified field somewhere in its hierarchy. 13526 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 13527 SourceLocation Loc) { 13528 QualType Ty = E->getType(); 13529 assert(Ty->isRecordType() && "lvalue was not record?"); 13530 SourceRange Range = E->getSourceRange(); 13531 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 13532 bool DiagEmitted = false; 13533 13534 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 13535 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 13536 Range, OEK_Member, DiagEmitted); 13537 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13538 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 13539 Range, OEK_Variable, DiagEmitted); 13540 else 13541 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 13542 Range, OEK_LValue, DiagEmitted); 13543 if (!DiagEmitted) 13544 DiagnoseConstAssignment(S, E, Loc); 13545 } 13546 13547 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 13548 /// emit an error and return true. If so, return false. 13549 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 13550 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 13551 13552 S.CheckShadowingDeclModification(E, Loc); 13553 13554 SourceLocation OrigLoc = Loc; 13555 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 13556 &Loc); 13557 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 13558 IsLV = Expr::MLV_InvalidMessageExpression; 13559 if (IsLV == Expr::MLV_Valid) 13560 return false; 13561 13562 unsigned DiagID = 0; 13563 bool NeedType = false; 13564 switch (IsLV) { // C99 6.5.16p2 13565 case Expr::MLV_ConstQualified: 13566 // Use a specialized diagnostic when we're assigning to an object 13567 // from an enclosing function or block. 13568 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 13569 if (NCCK == NCCK_Block) 13570 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 13571 else 13572 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 13573 break; 13574 } 13575 13576 // In ARC, use some specialized diagnostics for occasions where we 13577 // infer 'const'. These are always pseudo-strong variables. 13578 if (S.getLangOpts().ObjCAutoRefCount) { 13579 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 13580 if (declRef && isa<VarDecl>(declRef->getDecl())) { 13581 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 13582 13583 // Use the normal diagnostic if it's pseudo-__strong but the 13584 // user actually wrote 'const'. 13585 if (var->isARCPseudoStrong() && 13586 (!var->getTypeSourceInfo() || 13587 !var->getTypeSourceInfo()->getType().isConstQualified())) { 13588 // There are three pseudo-strong cases: 13589 // - self 13590 ObjCMethodDecl *method = S.getCurMethodDecl(); 13591 if (method && var == method->getSelfDecl()) { 13592 DiagID = method->isClassMethod() 13593 ? diag::err_typecheck_arc_assign_self_class_method 13594 : diag::err_typecheck_arc_assign_self; 13595 13596 // - Objective-C externally_retained attribute. 13597 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 13598 isa<ParmVarDecl>(var)) { 13599 DiagID = diag::err_typecheck_arc_assign_externally_retained; 13600 13601 // - fast enumeration variables 13602 } else { 13603 DiagID = diag::err_typecheck_arr_assign_enumeration; 13604 } 13605 13606 SourceRange Assign; 13607 if (Loc != OrigLoc) 13608 Assign = SourceRange(OrigLoc, OrigLoc); 13609 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13610 // We need to preserve the AST regardless, so migration tool 13611 // can do its job. 13612 return false; 13613 } 13614 } 13615 } 13616 13617 // If none of the special cases above are triggered, then this is a 13618 // simple const assignment. 13619 if (DiagID == 0) { 13620 DiagnoseConstAssignment(S, E, Loc); 13621 return true; 13622 } 13623 13624 break; 13625 case Expr::MLV_ConstAddrSpace: 13626 DiagnoseConstAssignment(S, E, Loc); 13627 return true; 13628 case Expr::MLV_ConstQualifiedField: 13629 DiagnoseRecursiveConstFields(S, E, Loc); 13630 return true; 13631 case Expr::MLV_ArrayType: 13632 case Expr::MLV_ArrayTemporary: 13633 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 13634 NeedType = true; 13635 break; 13636 case Expr::MLV_NotObjectType: 13637 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 13638 NeedType = true; 13639 break; 13640 case Expr::MLV_LValueCast: 13641 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 13642 break; 13643 case Expr::MLV_Valid: 13644 llvm_unreachable("did not take early return for MLV_Valid"); 13645 case Expr::MLV_InvalidExpression: 13646 case Expr::MLV_MemberFunction: 13647 case Expr::MLV_ClassTemporary: 13648 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 13649 break; 13650 case Expr::MLV_IncompleteType: 13651 case Expr::MLV_IncompleteVoidType: 13652 return S.RequireCompleteType(Loc, E->getType(), 13653 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 13654 case Expr::MLV_DuplicateVectorComponents: 13655 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 13656 break; 13657 case Expr::MLV_NoSetterProperty: 13658 llvm_unreachable("readonly properties should be processed differently"); 13659 case Expr::MLV_InvalidMessageExpression: 13660 DiagID = diag::err_readonly_message_assignment; 13661 break; 13662 case Expr::MLV_SubObjCPropertySetting: 13663 DiagID = diag::err_no_subobject_property_setting; 13664 break; 13665 } 13666 13667 SourceRange Assign; 13668 if (Loc != OrigLoc) 13669 Assign = SourceRange(OrigLoc, OrigLoc); 13670 if (NeedType) 13671 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 13672 else 13673 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13674 return true; 13675 } 13676 13677 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 13678 SourceLocation Loc, 13679 Sema &Sema) { 13680 if (Sema.inTemplateInstantiation()) 13681 return; 13682 if (Sema.isUnevaluatedContext()) 13683 return; 13684 if (Loc.isInvalid() || Loc.isMacroID()) 13685 return; 13686 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 13687 return; 13688 13689 // C / C++ fields 13690 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 13691 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 13692 if (ML && MR) { 13693 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 13694 return; 13695 const ValueDecl *LHSDecl = 13696 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 13697 const ValueDecl *RHSDecl = 13698 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13699 if (LHSDecl != RHSDecl) 13700 return; 13701 if (LHSDecl->getType().isVolatileQualified()) 13702 return; 13703 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13704 if (RefTy->getPointeeType().isVolatileQualified()) 13705 return; 13706 13707 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13708 } 13709 13710 // Objective-C instance variables 13711 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13712 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13713 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13714 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13715 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13716 if (RL && RR && RL->getDecl() == RR->getDecl()) 13717 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13718 } 13719 } 13720 13721 // C99 6.5.16.1 13722 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13723 SourceLocation Loc, 13724 QualType CompoundType) { 13725 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13726 13727 // Verify that LHS is a modifiable lvalue, and emit error if not. 13728 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13729 return QualType(); 13730 13731 QualType LHSType = LHSExpr->getType(); 13732 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13733 CompoundType; 13734 // OpenCL v1.2 s6.1.1.1 p2: 13735 // The half data type can only be used to declare a pointer to a buffer that 13736 // contains half values 13737 if (getLangOpts().OpenCL && 13738 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13739 LHSType->isHalfType()) { 13740 Diag(Loc, diag::err_opencl_half_load_store) << 1 13741 << LHSType.getUnqualifiedType(); 13742 return QualType(); 13743 } 13744 13745 AssignConvertType ConvTy; 13746 if (CompoundType.isNull()) { 13747 Expr *RHSCheck = RHS.get(); 13748 13749 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13750 13751 QualType LHSTy(LHSType); 13752 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13753 if (RHS.isInvalid()) 13754 return QualType(); 13755 // Special case of NSObject attributes on c-style pointer types. 13756 if (ConvTy == IncompatiblePointer && 13757 ((Context.isObjCNSObjectType(LHSType) && 13758 RHSType->isObjCObjectPointerType()) || 13759 (Context.isObjCNSObjectType(RHSType) && 13760 LHSType->isObjCObjectPointerType()))) 13761 ConvTy = Compatible; 13762 13763 if (ConvTy == Compatible && 13764 LHSType->isObjCObjectType()) 13765 Diag(Loc, diag::err_objc_object_assignment) 13766 << LHSType; 13767 13768 // If the RHS is a unary plus or minus, check to see if they = and + are 13769 // right next to each other. If so, the user may have typo'd "x =+ 4" 13770 // instead of "x += 4". 13771 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13772 RHSCheck = ICE->getSubExpr(); 13773 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13774 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13775 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13776 // Only if the two operators are exactly adjacent. 13777 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13778 // And there is a space or other character before the subexpr of the 13779 // unary +/-. We don't want to warn on "x=-1". 13780 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13781 UO->getSubExpr()->getBeginLoc().isFileID()) { 13782 Diag(Loc, diag::warn_not_compound_assign) 13783 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13784 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13785 } 13786 } 13787 13788 if (ConvTy == Compatible) { 13789 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13790 // Warn about retain cycles where a block captures the LHS, but 13791 // not if the LHS is a simple variable into which the block is 13792 // being stored...unless that variable can be captured by reference! 13793 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13794 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13795 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13796 checkRetainCycles(LHSExpr, RHS.get()); 13797 } 13798 13799 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13800 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13801 // It is safe to assign a weak reference into a strong variable. 13802 // Although this code can still have problems: 13803 // id x = self.weakProp; 13804 // id y = self.weakProp; 13805 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13806 // paths through the function. This should be revisited if 13807 // -Wrepeated-use-of-weak is made flow-sensitive. 13808 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13809 // variable, which will be valid for the current autorelease scope. 13810 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13811 RHS.get()->getBeginLoc())) 13812 getCurFunction()->markSafeWeakUse(RHS.get()); 13813 13814 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13815 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13816 } 13817 } 13818 } else { 13819 // Compound assignment "x += y" 13820 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13821 } 13822 13823 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13824 RHS.get(), AA_Assigning)) 13825 return QualType(); 13826 13827 CheckForNullPointerDereference(*this, LHSExpr); 13828 13829 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13830 if (CompoundType.isNull()) { 13831 // C++2a [expr.ass]p5: 13832 // A simple-assignment whose left operand is of a volatile-qualified 13833 // type is deprecated unless the assignment is either a discarded-value 13834 // expression or an unevaluated operand 13835 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13836 } else { 13837 // C++2a [expr.ass]p6: 13838 // [Compound-assignment] expressions are deprecated if E1 has 13839 // volatile-qualified type 13840 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13841 } 13842 } 13843 13844 // C11 6.5.16p3: The type of an assignment expression is the type of the 13845 // left operand would have after lvalue conversion. 13846 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has 13847 // qualified type, the value has the unqualified version of the type of the 13848 // lvalue; additionally, if the lvalue has atomic type, the value has the 13849 // non-atomic version of the type of the lvalue. 13850 // C++ 5.17p1: the type of the assignment expression is that of its left 13851 // operand. 13852 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType(); 13853 } 13854 13855 // Only ignore explicit casts to void. 13856 static bool IgnoreCommaOperand(const Expr *E) { 13857 E = E->IgnoreParens(); 13858 13859 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13860 if (CE->getCastKind() == CK_ToVoid) { 13861 return true; 13862 } 13863 13864 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13865 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13866 CE->getSubExpr()->getType()->isDependentType()) { 13867 return true; 13868 } 13869 } 13870 13871 return false; 13872 } 13873 13874 // Look for instances where it is likely the comma operator is confused with 13875 // another operator. There is an explicit list of acceptable expressions for 13876 // the left hand side of the comma operator, otherwise emit a warning. 13877 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13878 // No warnings in macros 13879 if (Loc.isMacroID()) 13880 return; 13881 13882 // Don't warn in template instantiations. 13883 if (inTemplateInstantiation()) 13884 return; 13885 13886 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13887 // instead, skip more than needed, then call back into here with the 13888 // CommaVisitor in SemaStmt.cpp. 13889 // The listed locations are the initialization and increment portions 13890 // of a for loop. The additional checks are on the condition of 13891 // if statements, do/while loops, and for loops. 13892 // Differences in scope flags for C89 mode requires the extra logic. 13893 const unsigned ForIncrementFlags = 13894 getLangOpts().C99 || getLangOpts().CPlusPlus 13895 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13896 : Scope::ContinueScope | Scope::BreakScope; 13897 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13898 const unsigned ScopeFlags = getCurScope()->getFlags(); 13899 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13900 (ScopeFlags & ForInitFlags) == ForInitFlags) 13901 return; 13902 13903 // If there are multiple comma operators used together, get the RHS of the 13904 // of the comma operator as the LHS. 13905 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13906 if (BO->getOpcode() != BO_Comma) 13907 break; 13908 LHS = BO->getRHS(); 13909 } 13910 13911 // Only allow some expressions on LHS to not warn. 13912 if (IgnoreCommaOperand(LHS)) 13913 return; 13914 13915 Diag(Loc, diag::warn_comma_operator); 13916 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13917 << LHS->getSourceRange() 13918 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13919 LangOpts.CPlusPlus ? "static_cast<void>(" 13920 : "(void)(") 13921 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13922 ")"); 13923 } 13924 13925 // C99 6.5.17 13926 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13927 SourceLocation Loc) { 13928 LHS = S.CheckPlaceholderExpr(LHS.get()); 13929 RHS = S.CheckPlaceholderExpr(RHS.get()); 13930 if (LHS.isInvalid() || RHS.isInvalid()) 13931 return QualType(); 13932 13933 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13934 // operands, but not unary promotions. 13935 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13936 13937 // So we treat the LHS as a ignored value, and in C++ we allow the 13938 // containing site to determine what should be done with the RHS. 13939 LHS = S.IgnoredValueConversions(LHS.get()); 13940 if (LHS.isInvalid()) 13941 return QualType(); 13942 13943 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand); 13944 13945 if (!S.getLangOpts().CPlusPlus) { 13946 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13947 if (RHS.isInvalid()) 13948 return QualType(); 13949 if (!RHS.get()->getType()->isVoidType()) 13950 S.RequireCompleteType(Loc, RHS.get()->getType(), 13951 diag::err_incomplete_type); 13952 } 13953 13954 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13955 S.DiagnoseCommaOperator(LHS.get(), Loc); 13956 13957 return RHS.get()->getType(); 13958 } 13959 13960 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13961 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13962 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13963 ExprValueKind &VK, 13964 ExprObjectKind &OK, 13965 SourceLocation OpLoc, 13966 bool IsInc, bool IsPrefix) { 13967 if (Op->isTypeDependent()) 13968 return S.Context.DependentTy; 13969 13970 QualType ResType = Op->getType(); 13971 // Atomic types can be used for increment / decrement where the non-atomic 13972 // versions can, so ignore the _Atomic() specifier for the purpose of 13973 // checking. 13974 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13975 ResType = ResAtomicType->getValueType(); 13976 13977 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13978 13979 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13980 // Decrement of bool is not allowed. 13981 if (!IsInc) { 13982 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13983 return QualType(); 13984 } 13985 // Increment of bool sets it to true, but is deprecated. 13986 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13987 : diag::warn_increment_bool) 13988 << Op->getSourceRange(); 13989 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13990 // Error on enum increments and decrements in C++ mode 13991 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13992 return QualType(); 13993 } else if (ResType->isRealType()) { 13994 // OK! 13995 } else if (ResType->isPointerType()) { 13996 // C99 6.5.2.4p2, 6.5.6p2 13997 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13998 return QualType(); 13999 } else if (ResType->isObjCObjectPointerType()) { 14000 // On modern runtimes, ObjC pointer arithmetic is forbidden. 14001 // Otherwise, we just need a complete type. 14002 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 14003 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 14004 return QualType(); 14005 } else if (ResType->isAnyComplexType()) { 14006 // C99 does not support ++/-- on complex types, we allow as an extension. 14007 S.Diag(OpLoc, diag::ext_integer_increment_complex) 14008 << ResType << Op->getSourceRange(); 14009 } else if (ResType->isPlaceholderType()) { 14010 ExprResult PR = S.CheckPlaceholderExpr(Op); 14011 if (PR.isInvalid()) return QualType(); 14012 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 14013 IsInc, IsPrefix); 14014 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 14015 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 14016 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 14017 (ResType->castAs<VectorType>()->getVectorKind() != 14018 VectorType::AltiVecBool)) { 14019 // The z vector extensions allow ++ and -- for non-bool vectors. 14020 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 14021 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 14022 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 14023 } else { 14024 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 14025 << ResType << int(IsInc) << Op->getSourceRange(); 14026 return QualType(); 14027 } 14028 // At this point, we know we have a real, complex or pointer type. 14029 // Now make sure the operand is a modifiable lvalue. 14030 if (CheckForModifiableLvalue(Op, OpLoc, S)) 14031 return QualType(); 14032 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 14033 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 14034 // An operand with volatile-qualified type is deprecated 14035 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 14036 << IsInc << ResType; 14037 } 14038 // In C++, a prefix increment is the same type as the operand. Otherwise 14039 // (in C or with postfix), the increment is the unqualified type of the 14040 // operand. 14041 if (IsPrefix && S.getLangOpts().CPlusPlus) { 14042 VK = VK_LValue; 14043 OK = Op->getObjectKind(); 14044 return ResType; 14045 } else { 14046 VK = VK_PRValue; 14047 return ResType.getUnqualifiedType(); 14048 } 14049 } 14050 14051 14052 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 14053 /// This routine allows us to typecheck complex/recursive expressions 14054 /// where the declaration is needed for type checking. We only need to 14055 /// handle cases when the expression references a function designator 14056 /// or is an lvalue. Here are some examples: 14057 /// - &(x) => x 14058 /// - &*****f => f for f a function designator. 14059 /// - &s.xx => s 14060 /// - &s.zz[1].yy -> s, if zz is an array 14061 /// - *(x + 1) -> x, if x is an array 14062 /// - &"123"[2] -> 0 14063 /// - & __real__ x -> x 14064 /// 14065 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 14066 /// members. 14067 static ValueDecl *getPrimaryDecl(Expr *E) { 14068 switch (E->getStmtClass()) { 14069 case Stmt::DeclRefExprClass: 14070 return cast<DeclRefExpr>(E)->getDecl(); 14071 case Stmt::MemberExprClass: 14072 // If this is an arrow operator, the address is an offset from 14073 // the base's value, so the object the base refers to is 14074 // irrelevant. 14075 if (cast<MemberExpr>(E)->isArrow()) 14076 return nullptr; 14077 // Otherwise, the expression refers to a part of the base 14078 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 14079 case Stmt::ArraySubscriptExprClass: { 14080 // FIXME: This code shouldn't be necessary! We should catch the implicit 14081 // promotion of register arrays earlier. 14082 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 14083 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 14084 if (ICE->getSubExpr()->getType()->isArrayType()) 14085 return getPrimaryDecl(ICE->getSubExpr()); 14086 } 14087 return nullptr; 14088 } 14089 case Stmt::UnaryOperatorClass: { 14090 UnaryOperator *UO = cast<UnaryOperator>(E); 14091 14092 switch(UO->getOpcode()) { 14093 case UO_Real: 14094 case UO_Imag: 14095 case UO_Extension: 14096 return getPrimaryDecl(UO->getSubExpr()); 14097 default: 14098 return nullptr; 14099 } 14100 } 14101 case Stmt::ParenExprClass: 14102 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 14103 case Stmt::ImplicitCastExprClass: 14104 // If the result of an implicit cast is an l-value, we care about 14105 // the sub-expression; otherwise, the result here doesn't matter. 14106 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 14107 case Stmt::CXXUuidofExprClass: 14108 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 14109 default: 14110 return nullptr; 14111 } 14112 } 14113 14114 namespace { 14115 enum { 14116 AO_Bit_Field = 0, 14117 AO_Vector_Element = 1, 14118 AO_Property_Expansion = 2, 14119 AO_Register_Variable = 3, 14120 AO_Matrix_Element = 4, 14121 AO_No_Error = 5 14122 }; 14123 } 14124 /// Diagnose invalid operand for address of operations. 14125 /// 14126 /// \param Type The type of operand which cannot have its address taken. 14127 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 14128 Expr *E, unsigned Type) { 14129 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 14130 } 14131 14132 /// CheckAddressOfOperand - The operand of & must be either a function 14133 /// designator or an lvalue designating an object. If it is an lvalue, the 14134 /// object cannot be declared with storage class register or be a bit field. 14135 /// Note: The usual conversions are *not* applied to the operand of the & 14136 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 14137 /// In C++, the operand might be an overloaded function name, in which case 14138 /// we allow the '&' but retain the overloaded-function type. 14139 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 14140 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 14141 if (PTy->getKind() == BuiltinType::Overload) { 14142 Expr *E = OrigOp.get()->IgnoreParens(); 14143 if (!isa<OverloadExpr>(E)) { 14144 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 14145 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 14146 << OrigOp.get()->getSourceRange(); 14147 return QualType(); 14148 } 14149 14150 OverloadExpr *Ovl = cast<OverloadExpr>(E); 14151 if (isa<UnresolvedMemberExpr>(Ovl)) 14152 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 14153 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 14154 << OrigOp.get()->getSourceRange(); 14155 return QualType(); 14156 } 14157 14158 return Context.OverloadTy; 14159 } 14160 14161 if (PTy->getKind() == BuiltinType::UnknownAny) 14162 return Context.UnknownAnyTy; 14163 14164 if (PTy->getKind() == BuiltinType::BoundMember) { 14165 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 14166 << OrigOp.get()->getSourceRange(); 14167 return QualType(); 14168 } 14169 14170 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 14171 if (OrigOp.isInvalid()) return QualType(); 14172 } 14173 14174 if (OrigOp.get()->isTypeDependent()) 14175 return Context.DependentTy; 14176 14177 assert(!OrigOp.get()->hasPlaceholderType()); 14178 14179 // Make sure to ignore parentheses in subsequent checks 14180 Expr *op = OrigOp.get()->IgnoreParens(); 14181 14182 // In OpenCL captures for blocks called as lambda functions 14183 // are located in the private address space. Blocks used in 14184 // enqueue_kernel can be located in a different address space 14185 // depending on a vendor implementation. Thus preventing 14186 // taking an address of the capture to avoid invalid AS casts. 14187 if (LangOpts.OpenCL) { 14188 auto* VarRef = dyn_cast<DeclRefExpr>(op); 14189 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 14190 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 14191 return QualType(); 14192 } 14193 } 14194 14195 if (getLangOpts().C99) { 14196 // Implement C99-only parts of addressof rules. 14197 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 14198 if (uOp->getOpcode() == UO_Deref) 14199 // Per C99 6.5.3.2, the address of a deref always returns a valid result 14200 // (assuming the deref expression is valid). 14201 return uOp->getSubExpr()->getType(); 14202 } 14203 // Technically, there should be a check for array subscript 14204 // expressions here, but the result of one is always an lvalue anyway. 14205 } 14206 ValueDecl *dcl = getPrimaryDecl(op); 14207 14208 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 14209 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 14210 op->getBeginLoc())) 14211 return QualType(); 14212 14213 Expr::LValueClassification lval = op->ClassifyLValue(Context); 14214 unsigned AddressOfError = AO_No_Error; 14215 14216 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 14217 bool sfinae = (bool)isSFINAEContext(); 14218 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 14219 : diag::ext_typecheck_addrof_temporary) 14220 << op->getType() << op->getSourceRange(); 14221 if (sfinae) 14222 return QualType(); 14223 // Materialize the temporary as an lvalue so that we can take its address. 14224 OrigOp = op = 14225 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 14226 } else if (isa<ObjCSelectorExpr>(op)) { 14227 return Context.getPointerType(op->getType()); 14228 } else if (lval == Expr::LV_MemberFunction) { 14229 // If it's an instance method, make a member pointer. 14230 // The expression must have exactly the form &A::foo. 14231 14232 // If the underlying expression isn't a decl ref, give up. 14233 if (!isa<DeclRefExpr>(op)) { 14234 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 14235 << OrigOp.get()->getSourceRange(); 14236 return QualType(); 14237 } 14238 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 14239 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 14240 14241 // The id-expression was parenthesized. 14242 if (OrigOp.get() != DRE) { 14243 Diag(OpLoc, diag::err_parens_pointer_member_function) 14244 << OrigOp.get()->getSourceRange(); 14245 14246 // The method was named without a qualifier. 14247 } else if (!DRE->getQualifier()) { 14248 if (MD->getParent()->getName().empty()) 14249 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 14250 << op->getSourceRange(); 14251 else { 14252 SmallString<32> Str; 14253 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 14254 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 14255 << op->getSourceRange() 14256 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 14257 } 14258 } 14259 14260 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 14261 if (isa<CXXDestructorDecl>(MD)) 14262 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 14263 14264 QualType MPTy = Context.getMemberPointerType( 14265 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 14266 // Under the MS ABI, lock down the inheritance model now. 14267 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14268 (void)isCompleteType(OpLoc, MPTy); 14269 return MPTy; 14270 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 14271 // C99 6.5.3.2p1 14272 // The operand must be either an l-value or a function designator 14273 if (!op->getType()->isFunctionType()) { 14274 // Use a special diagnostic for loads from property references. 14275 if (isa<PseudoObjectExpr>(op)) { 14276 AddressOfError = AO_Property_Expansion; 14277 } else { 14278 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 14279 << op->getType() << op->getSourceRange(); 14280 return QualType(); 14281 } 14282 } 14283 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 14284 // The operand cannot be a bit-field 14285 AddressOfError = AO_Bit_Field; 14286 } else if (op->getObjectKind() == OK_VectorComponent) { 14287 // The operand cannot be an element of a vector 14288 AddressOfError = AO_Vector_Element; 14289 } else if (op->getObjectKind() == OK_MatrixComponent) { 14290 // The operand cannot be an element of a matrix. 14291 AddressOfError = AO_Matrix_Element; 14292 } else if (dcl) { // C99 6.5.3.2p1 14293 // We have an lvalue with a decl. Make sure the decl is not declared 14294 // with the register storage-class specifier. 14295 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 14296 // in C++ it is not error to take address of a register 14297 // variable (c++03 7.1.1P3) 14298 if (vd->getStorageClass() == SC_Register && 14299 !getLangOpts().CPlusPlus) { 14300 AddressOfError = AO_Register_Variable; 14301 } 14302 } else if (isa<MSPropertyDecl>(dcl)) { 14303 AddressOfError = AO_Property_Expansion; 14304 } else if (isa<FunctionTemplateDecl>(dcl)) { 14305 return Context.OverloadTy; 14306 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 14307 // Okay: we can take the address of a field. 14308 // Could be a pointer to member, though, if there is an explicit 14309 // scope qualifier for the class. 14310 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 14311 DeclContext *Ctx = dcl->getDeclContext(); 14312 if (Ctx && Ctx->isRecord()) { 14313 if (dcl->getType()->isReferenceType()) { 14314 Diag(OpLoc, 14315 diag::err_cannot_form_pointer_to_member_of_reference_type) 14316 << dcl->getDeclName() << dcl->getType(); 14317 return QualType(); 14318 } 14319 14320 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 14321 Ctx = Ctx->getParent(); 14322 14323 QualType MPTy = Context.getMemberPointerType( 14324 op->getType(), 14325 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 14326 // Under the MS ABI, lock down the inheritance model now. 14327 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14328 (void)isCompleteType(OpLoc, MPTy); 14329 return MPTy; 14330 } 14331 } 14332 } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl, 14333 MSGuidDecl, UnnamedGlobalConstantDecl>(dcl)) 14334 llvm_unreachable("Unknown/unexpected decl type"); 14335 } 14336 14337 if (AddressOfError != AO_No_Error) { 14338 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 14339 return QualType(); 14340 } 14341 14342 if (lval == Expr::LV_IncompleteVoidType) { 14343 // Taking the address of a void variable is technically illegal, but we 14344 // allow it in cases which are otherwise valid. 14345 // Example: "extern void x; void* y = &x;". 14346 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 14347 } 14348 14349 // If the operand has type "type", the result has type "pointer to type". 14350 if (op->getType()->isObjCObjectType()) 14351 return Context.getObjCObjectPointerType(op->getType()); 14352 14353 CheckAddressOfPackedMember(op); 14354 14355 return Context.getPointerType(op->getType()); 14356 } 14357 14358 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 14359 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 14360 if (!DRE) 14361 return; 14362 const Decl *D = DRE->getDecl(); 14363 if (!D) 14364 return; 14365 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 14366 if (!Param) 14367 return; 14368 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 14369 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 14370 return; 14371 if (FunctionScopeInfo *FD = S.getCurFunction()) 14372 if (!FD->ModifiedNonNullParams.count(Param)) 14373 FD->ModifiedNonNullParams.insert(Param); 14374 } 14375 14376 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 14377 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 14378 SourceLocation OpLoc) { 14379 if (Op->isTypeDependent()) 14380 return S.Context.DependentTy; 14381 14382 ExprResult ConvResult = S.UsualUnaryConversions(Op); 14383 if (ConvResult.isInvalid()) 14384 return QualType(); 14385 Op = ConvResult.get(); 14386 QualType OpTy = Op->getType(); 14387 QualType Result; 14388 14389 if (isa<CXXReinterpretCastExpr>(Op)) { 14390 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 14391 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 14392 Op->getSourceRange()); 14393 } 14394 14395 if (const PointerType *PT = OpTy->getAs<PointerType>()) 14396 { 14397 Result = PT->getPointeeType(); 14398 } 14399 else if (const ObjCObjectPointerType *OPT = 14400 OpTy->getAs<ObjCObjectPointerType>()) 14401 Result = OPT->getPointeeType(); 14402 else { 14403 ExprResult PR = S.CheckPlaceholderExpr(Op); 14404 if (PR.isInvalid()) return QualType(); 14405 if (PR.get() != Op) 14406 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 14407 } 14408 14409 if (Result.isNull()) { 14410 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 14411 << OpTy << Op->getSourceRange(); 14412 return QualType(); 14413 } 14414 14415 // Note that per both C89 and C99, indirection is always legal, even if Result 14416 // is an incomplete type or void. It would be possible to warn about 14417 // dereferencing a void pointer, but it's completely well-defined, and such a 14418 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 14419 // for pointers to 'void' but is fine for any other pointer type: 14420 // 14421 // C++ [expr.unary.op]p1: 14422 // [...] the expression to which [the unary * operator] is applied shall 14423 // be a pointer to an object type, or a pointer to a function type 14424 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 14425 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 14426 << OpTy << Op->getSourceRange(); 14427 14428 // Dereferences are usually l-values... 14429 VK = VK_LValue; 14430 14431 // ...except that certain expressions are never l-values in C. 14432 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 14433 VK = VK_PRValue; 14434 14435 return Result; 14436 } 14437 14438 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 14439 BinaryOperatorKind Opc; 14440 switch (Kind) { 14441 default: llvm_unreachable("Unknown binop!"); 14442 case tok::periodstar: Opc = BO_PtrMemD; break; 14443 case tok::arrowstar: Opc = BO_PtrMemI; break; 14444 case tok::star: Opc = BO_Mul; break; 14445 case tok::slash: Opc = BO_Div; break; 14446 case tok::percent: Opc = BO_Rem; break; 14447 case tok::plus: Opc = BO_Add; break; 14448 case tok::minus: Opc = BO_Sub; break; 14449 case tok::lessless: Opc = BO_Shl; break; 14450 case tok::greatergreater: Opc = BO_Shr; break; 14451 case tok::lessequal: Opc = BO_LE; break; 14452 case tok::less: Opc = BO_LT; break; 14453 case tok::greaterequal: Opc = BO_GE; break; 14454 case tok::greater: Opc = BO_GT; break; 14455 case tok::exclaimequal: Opc = BO_NE; break; 14456 case tok::equalequal: Opc = BO_EQ; break; 14457 case tok::spaceship: Opc = BO_Cmp; break; 14458 case tok::amp: Opc = BO_And; break; 14459 case tok::caret: Opc = BO_Xor; break; 14460 case tok::pipe: Opc = BO_Or; break; 14461 case tok::ampamp: Opc = BO_LAnd; break; 14462 case tok::pipepipe: Opc = BO_LOr; break; 14463 case tok::equal: Opc = BO_Assign; break; 14464 case tok::starequal: Opc = BO_MulAssign; break; 14465 case tok::slashequal: Opc = BO_DivAssign; break; 14466 case tok::percentequal: Opc = BO_RemAssign; break; 14467 case tok::plusequal: Opc = BO_AddAssign; break; 14468 case tok::minusequal: Opc = BO_SubAssign; break; 14469 case tok::lesslessequal: Opc = BO_ShlAssign; break; 14470 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 14471 case tok::ampequal: Opc = BO_AndAssign; break; 14472 case tok::caretequal: Opc = BO_XorAssign; break; 14473 case tok::pipeequal: Opc = BO_OrAssign; break; 14474 case tok::comma: Opc = BO_Comma; break; 14475 } 14476 return Opc; 14477 } 14478 14479 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 14480 tok::TokenKind Kind) { 14481 UnaryOperatorKind Opc; 14482 switch (Kind) { 14483 default: llvm_unreachable("Unknown unary op!"); 14484 case tok::plusplus: Opc = UO_PreInc; break; 14485 case tok::minusminus: Opc = UO_PreDec; break; 14486 case tok::amp: Opc = UO_AddrOf; break; 14487 case tok::star: Opc = UO_Deref; break; 14488 case tok::plus: Opc = UO_Plus; break; 14489 case tok::minus: Opc = UO_Minus; break; 14490 case tok::tilde: Opc = UO_Not; break; 14491 case tok::exclaim: Opc = UO_LNot; break; 14492 case tok::kw___real: Opc = UO_Real; break; 14493 case tok::kw___imag: Opc = UO_Imag; break; 14494 case tok::kw___extension__: Opc = UO_Extension; break; 14495 } 14496 return Opc; 14497 } 14498 14499 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 14500 /// This warning suppressed in the event of macro expansions. 14501 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 14502 SourceLocation OpLoc, bool IsBuiltin) { 14503 if (S.inTemplateInstantiation()) 14504 return; 14505 if (S.isUnevaluatedContext()) 14506 return; 14507 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 14508 return; 14509 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14510 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14511 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14512 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14513 if (!LHSDeclRef || !RHSDeclRef || 14514 LHSDeclRef->getLocation().isMacroID() || 14515 RHSDeclRef->getLocation().isMacroID()) 14516 return; 14517 const ValueDecl *LHSDecl = 14518 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 14519 const ValueDecl *RHSDecl = 14520 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 14521 if (LHSDecl != RHSDecl) 14522 return; 14523 if (LHSDecl->getType().isVolatileQualified()) 14524 return; 14525 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 14526 if (RefTy->getPointeeType().isVolatileQualified()) 14527 return; 14528 14529 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 14530 : diag::warn_self_assignment_overloaded) 14531 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 14532 << RHSExpr->getSourceRange(); 14533 } 14534 14535 /// Check if a bitwise-& is performed on an Objective-C pointer. This 14536 /// is usually indicative of introspection within the Objective-C pointer. 14537 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 14538 SourceLocation OpLoc) { 14539 if (!S.getLangOpts().ObjC) 14540 return; 14541 14542 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 14543 const Expr *LHS = L.get(); 14544 const Expr *RHS = R.get(); 14545 14546 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 14547 ObjCPointerExpr = LHS; 14548 OtherExpr = RHS; 14549 } 14550 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 14551 ObjCPointerExpr = RHS; 14552 OtherExpr = LHS; 14553 } 14554 14555 // This warning is deliberately made very specific to reduce false 14556 // positives with logic that uses '&' for hashing. This logic mainly 14557 // looks for code trying to introspect into tagged pointers, which 14558 // code should generally never do. 14559 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 14560 unsigned Diag = diag::warn_objc_pointer_masking; 14561 // Determine if we are introspecting the result of performSelectorXXX. 14562 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 14563 // Special case messages to -performSelector and friends, which 14564 // can return non-pointer values boxed in a pointer value. 14565 // Some clients may wish to silence warnings in this subcase. 14566 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 14567 Selector S = ME->getSelector(); 14568 StringRef SelArg0 = S.getNameForSlot(0); 14569 if (SelArg0.startswith("performSelector")) 14570 Diag = diag::warn_objc_pointer_masking_performSelector; 14571 } 14572 14573 S.Diag(OpLoc, Diag) 14574 << ObjCPointerExpr->getSourceRange(); 14575 } 14576 } 14577 14578 static NamedDecl *getDeclFromExpr(Expr *E) { 14579 if (!E) 14580 return nullptr; 14581 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 14582 return DRE->getDecl(); 14583 if (auto *ME = dyn_cast<MemberExpr>(E)) 14584 return ME->getMemberDecl(); 14585 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 14586 return IRE->getDecl(); 14587 return nullptr; 14588 } 14589 14590 // This helper function promotes a binary operator's operands (which are of a 14591 // half vector type) to a vector of floats and then truncates the result to 14592 // a vector of either half or short. 14593 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 14594 BinaryOperatorKind Opc, QualType ResultTy, 14595 ExprValueKind VK, ExprObjectKind OK, 14596 bool IsCompAssign, SourceLocation OpLoc, 14597 FPOptionsOverride FPFeatures) { 14598 auto &Context = S.getASTContext(); 14599 assert((isVector(ResultTy, Context.HalfTy) || 14600 isVector(ResultTy, Context.ShortTy)) && 14601 "Result must be a vector of half or short"); 14602 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 14603 isVector(RHS.get()->getType(), Context.HalfTy) && 14604 "both operands expected to be a half vector"); 14605 14606 RHS = convertVector(RHS.get(), Context.FloatTy, S); 14607 QualType BinOpResTy = RHS.get()->getType(); 14608 14609 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 14610 // change BinOpResTy to a vector of ints. 14611 if (isVector(ResultTy, Context.ShortTy)) 14612 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 14613 14614 if (IsCompAssign) 14615 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14616 ResultTy, VK, OK, OpLoc, FPFeatures, 14617 BinOpResTy, BinOpResTy); 14618 14619 LHS = convertVector(LHS.get(), Context.FloatTy, S); 14620 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14621 BinOpResTy, VK, OK, OpLoc, FPFeatures); 14622 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 14623 } 14624 14625 static std::pair<ExprResult, ExprResult> 14626 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 14627 Expr *RHSExpr) { 14628 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14629 if (!S.Context.isDependenceAllowed()) { 14630 // C cannot handle TypoExpr nodes on either side of a binop because it 14631 // doesn't handle dependent types properly, so make sure any TypoExprs have 14632 // been dealt with before checking the operands. 14633 LHS = S.CorrectDelayedTyposInExpr(LHS); 14634 RHS = S.CorrectDelayedTyposInExpr( 14635 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 14636 [Opc, LHS](Expr *E) { 14637 if (Opc != BO_Assign) 14638 return ExprResult(E); 14639 // Avoid correcting the RHS to the same Expr as the LHS. 14640 Decl *D = getDeclFromExpr(E); 14641 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 14642 }); 14643 } 14644 return std::make_pair(LHS, RHS); 14645 } 14646 14647 /// Returns true if conversion between vectors of halfs and vectors of floats 14648 /// is needed. 14649 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 14650 Expr *E0, Expr *E1 = nullptr) { 14651 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 14652 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 14653 return false; 14654 14655 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 14656 QualType Ty = E->IgnoreImplicit()->getType(); 14657 14658 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 14659 // to vectors of floats. Although the element type of the vectors is __fp16, 14660 // the vectors shouldn't be treated as storage-only types. See the 14661 // discussion here: https://reviews.llvm.org/rG825235c140e7 14662 if (const VectorType *VT = Ty->getAs<VectorType>()) { 14663 if (VT->getVectorKind() == VectorType::NeonVector) 14664 return false; 14665 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 14666 } 14667 return false; 14668 }; 14669 14670 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 14671 } 14672 14673 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 14674 /// operator @p Opc at location @c TokLoc. This routine only supports 14675 /// built-in operations; ActOnBinOp handles overloaded operators. 14676 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 14677 BinaryOperatorKind Opc, 14678 Expr *LHSExpr, Expr *RHSExpr) { 14679 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 14680 // The syntax only allows initializer lists on the RHS of assignment, 14681 // so we don't need to worry about accepting invalid code for 14682 // non-assignment operators. 14683 // C++11 5.17p9: 14684 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 14685 // of x = {} is x = T(). 14686 InitializationKind Kind = InitializationKind::CreateDirectList( 14687 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14688 InitializedEntity Entity = 14689 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 14690 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 14691 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 14692 if (Init.isInvalid()) 14693 return Init; 14694 RHSExpr = Init.get(); 14695 } 14696 14697 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14698 QualType ResultTy; // Result type of the binary operator. 14699 // The following two variables are used for compound assignment operators 14700 QualType CompLHSTy; // Type of LHS after promotions for computation 14701 QualType CompResultTy; // Type of computation result 14702 ExprValueKind VK = VK_PRValue; 14703 ExprObjectKind OK = OK_Ordinary; 14704 bool ConvertHalfVec = false; 14705 14706 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14707 if (!LHS.isUsable() || !RHS.isUsable()) 14708 return ExprError(); 14709 14710 if (getLangOpts().OpenCL) { 14711 QualType LHSTy = LHSExpr->getType(); 14712 QualType RHSTy = RHSExpr->getType(); 14713 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14714 // the ATOMIC_VAR_INIT macro. 14715 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14716 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14717 if (BO_Assign == Opc) 14718 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14719 else 14720 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14721 return ExprError(); 14722 } 14723 14724 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14725 // only with a builtin functions and therefore should be disallowed here. 14726 if (LHSTy->isImageType() || RHSTy->isImageType() || 14727 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14728 LHSTy->isPipeType() || RHSTy->isPipeType() || 14729 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14730 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14731 return ExprError(); 14732 } 14733 } 14734 14735 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14736 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14737 14738 switch (Opc) { 14739 case BO_Assign: 14740 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14741 if (getLangOpts().CPlusPlus && 14742 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14743 VK = LHS.get()->getValueKind(); 14744 OK = LHS.get()->getObjectKind(); 14745 } 14746 if (!ResultTy.isNull()) { 14747 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14748 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14749 14750 // Avoid copying a block to the heap if the block is assigned to a local 14751 // auto variable that is declared in the same scope as the block. This 14752 // optimization is unsafe if the local variable is declared in an outer 14753 // scope. For example: 14754 // 14755 // BlockTy b; 14756 // { 14757 // b = ^{...}; 14758 // } 14759 // // It is unsafe to invoke the block here if it wasn't copied to the 14760 // // heap. 14761 // b(); 14762 14763 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14764 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14765 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14766 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14767 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14768 14769 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14770 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14771 NTCUC_Assignment, NTCUK_Copy); 14772 } 14773 RecordModifiableNonNullParam(*this, LHS.get()); 14774 break; 14775 case BO_PtrMemD: 14776 case BO_PtrMemI: 14777 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14778 Opc == BO_PtrMemI); 14779 break; 14780 case BO_Mul: 14781 case BO_Div: 14782 ConvertHalfVec = true; 14783 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14784 Opc == BO_Div); 14785 break; 14786 case BO_Rem: 14787 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14788 break; 14789 case BO_Add: 14790 ConvertHalfVec = true; 14791 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14792 break; 14793 case BO_Sub: 14794 ConvertHalfVec = true; 14795 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14796 break; 14797 case BO_Shl: 14798 case BO_Shr: 14799 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14800 break; 14801 case BO_LE: 14802 case BO_LT: 14803 case BO_GE: 14804 case BO_GT: 14805 ConvertHalfVec = true; 14806 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14807 break; 14808 case BO_EQ: 14809 case BO_NE: 14810 ConvertHalfVec = true; 14811 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14812 break; 14813 case BO_Cmp: 14814 ConvertHalfVec = true; 14815 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14816 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14817 break; 14818 case BO_And: 14819 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14820 LLVM_FALLTHROUGH; 14821 case BO_Xor: 14822 case BO_Or: 14823 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14824 break; 14825 case BO_LAnd: 14826 case BO_LOr: 14827 ConvertHalfVec = true; 14828 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14829 break; 14830 case BO_MulAssign: 14831 case BO_DivAssign: 14832 ConvertHalfVec = true; 14833 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14834 Opc == BO_DivAssign); 14835 CompLHSTy = CompResultTy; 14836 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14837 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14838 break; 14839 case BO_RemAssign: 14840 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14841 CompLHSTy = CompResultTy; 14842 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14843 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14844 break; 14845 case BO_AddAssign: 14846 ConvertHalfVec = true; 14847 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14848 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14849 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14850 break; 14851 case BO_SubAssign: 14852 ConvertHalfVec = true; 14853 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14854 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14855 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14856 break; 14857 case BO_ShlAssign: 14858 case BO_ShrAssign: 14859 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14860 CompLHSTy = CompResultTy; 14861 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14862 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14863 break; 14864 case BO_AndAssign: 14865 case BO_OrAssign: // fallthrough 14866 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14867 LLVM_FALLTHROUGH; 14868 case BO_XorAssign: 14869 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14870 CompLHSTy = CompResultTy; 14871 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14872 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14873 break; 14874 case BO_Comma: 14875 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14876 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14877 VK = RHS.get()->getValueKind(); 14878 OK = RHS.get()->getObjectKind(); 14879 } 14880 break; 14881 } 14882 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14883 return ExprError(); 14884 14885 // Some of the binary operations require promoting operands of half vector to 14886 // float vectors and truncating the result back to half vector. For now, we do 14887 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14888 // arm64). 14889 assert( 14890 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14891 isVector(LHS.get()->getType(), Context.HalfTy)) && 14892 "both sides are half vectors or neither sides are"); 14893 ConvertHalfVec = 14894 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14895 14896 // Check for array bounds violations for both sides of the BinaryOperator 14897 CheckArrayAccess(LHS.get()); 14898 CheckArrayAccess(RHS.get()); 14899 14900 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14901 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14902 &Context.Idents.get("object_setClass"), 14903 SourceLocation(), LookupOrdinaryName); 14904 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14905 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14906 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14907 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14908 "object_setClass(") 14909 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14910 ",") 14911 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14912 } 14913 else 14914 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14915 } 14916 else if (const ObjCIvarRefExpr *OIRE = 14917 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14918 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14919 14920 // Opc is not a compound assignment if CompResultTy is null. 14921 if (CompResultTy.isNull()) { 14922 if (ConvertHalfVec) 14923 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14924 OpLoc, CurFPFeatureOverrides()); 14925 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14926 VK, OK, OpLoc, CurFPFeatureOverrides()); 14927 } 14928 14929 // Handle compound assignments. 14930 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14931 OK_ObjCProperty) { 14932 VK = VK_LValue; 14933 OK = LHS.get()->getObjectKind(); 14934 } 14935 14936 // The LHS is not converted to the result type for fixed-point compound 14937 // assignment as the common type is computed on demand. Reset the CompLHSTy 14938 // to the LHS type we would have gotten after unary conversions. 14939 if (CompResultTy->isFixedPointType()) 14940 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14941 14942 if (ConvertHalfVec) 14943 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14944 OpLoc, CurFPFeatureOverrides()); 14945 14946 return CompoundAssignOperator::Create( 14947 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14948 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14949 } 14950 14951 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14952 /// operators are mixed in a way that suggests that the programmer forgot that 14953 /// comparison operators have higher precedence. The most typical example of 14954 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14955 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14956 SourceLocation OpLoc, Expr *LHSExpr, 14957 Expr *RHSExpr) { 14958 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14959 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14960 14961 // Check that one of the sides is a comparison operator and the other isn't. 14962 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14963 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14964 if (isLeftComp == isRightComp) 14965 return; 14966 14967 // Bitwise operations are sometimes used as eager logical ops. 14968 // Don't diagnose this. 14969 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14970 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14971 if (isLeftBitwise || isRightBitwise) 14972 return; 14973 14974 SourceRange DiagRange = isLeftComp 14975 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14976 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14977 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14978 SourceRange ParensRange = 14979 isLeftComp 14980 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14981 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14982 14983 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14984 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14985 SuggestParentheses(Self, OpLoc, 14986 Self.PDiag(diag::note_precedence_silence) << OpStr, 14987 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14988 SuggestParentheses(Self, OpLoc, 14989 Self.PDiag(diag::note_precedence_bitwise_first) 14990 << BinaryOperator::getOpcodeStr(Opc), 14991 ParensRange); 14992 } 14993 14994 /// It accepts a '&&' expr that is inside a '||' one. 14995 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14996 /// in parentheses. 14997 static void 14998 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14999 BinaryOperator *Bop) { 15000 assert(Bop->getOpcode() == BO_LAnd); 15001 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 15002 << Bop->getSourceRange() << OpLoc; 15003 SuggestParentheses(Self, Bop->getOperatorLoc(), 15004 Self.PDiag(diag::note_precedence_silence) 15005 << Bop->getOpcodeStr(), 15006 Bop->getSourceRange()); 15007 } 15008 15009 /// Returns true if the given expression can be evaluated as a constant 15010 /// 'true'. 15011 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 15012 bool Res; 15013 return !E->isValueDependent() && 15014 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 15015 } 15016 15017 /// Returns true if the given expression can be evaluated as a constant 15018 /// 'false'. 15019 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 15020 bool Res; 15021 return !E->isValueDependent() && 15022 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 15023 } 15024 15025 /// Look for '&&' in the left hand of a '||' expr. 15026 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 15027 Expr *LHSExpr, Expr *RHSExpr) { 15028 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 15029 if (Bop->getOpcode() == BO_LAnd) { 15030 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 15031 if (EvaluatesAsFalse(S, RHSExpr)) 15032 return; 15033 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 15034 if (!EvaluatesAsTrue(S, Bop->getLHS())) 15035 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 15036 } else if (Bop->getOpcode() == BO_LOr) { 15037 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 15038 // If it's "a || b && 1 || c" we didn't warn earlier for 15039 // "a || b && 1", but warn now. 15040 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 15041 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 15042 } 15043 } 15044 } 15045 } 15046 15047 /// Look for '&&' in the right hand of a '||' expr. 15048 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 15049 Expr *LHSExpr, Expr *RHSExpr) { 15050 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 15051 if (Bop->getOpcode() == BO_LAnd) { 15052 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 15053 if (EvaluatesAsFalse(S, LHSExpr)) 15054 return; 15055 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 15056 if (!EvaluatesAsTrue(S, Bop->getRHS())) 15057 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 15058 } 15059 } 15060 } 15061 15062 /// Look for bitwise op in the left or right hand of a bitwise op with 15063 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 15064 /// the '&' expression in parentheses. 15065 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 15066 SourceLocation OpLoc, Expr *SubExpr) { 15067 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 15068 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 15069 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 15070 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 15071 << Bop->getSourceRange() << OpLoc; 15072 SuggestParentheses(S, Bop->getOperatorLoc(), 15073 S.PDiag(diag::note_precedence_silence) 15074 << Bop->getOpcodeStr(), 15075 Bop->getSourceRange()); 15076 } 15077 } 15078 } 15079 15080 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 15081 Expr *SubExpr, StringRef Shift) { 15082 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 15083 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 15084 StringRef Op = Bop->getOpcodeStr(); 15085 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 15086 << Bop->getSourceRange() << OpLoc << Shift << Op; 15087 SuggestParentheses(S, Bop->getOperatorLoc(), 15088 S.PDiag(diag::note_precedence_silence) << Op, 15089 Bop->getSourceRange()); 15090 } 15091 } 15092 } 15093 15094 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 15095 Expr *LHSExpr, Expr *RHSExpr) { 15096 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 15097 if (!OCE) 15098 return; 15099 15100 FunctionDecl *FD = OCE->getDirectCallee(); 15101 if (!FD || !FD->isOverloadedOperator()) 15102 return; 15103 15104 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 15105 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 15106 return; 15107 15108 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 15109 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 15110 << (Kind == OO_LessLess); 15111 SuggestParentheses(S, OCE->getOperatorLoc(), 15112 S.PDiag(diag::note_precedence_silence) 15113 << (Kind == OO_LessLess ? "<<" : ">>"), 15114 OCE->getSourceRange()); 15115 SuggestParentheses( 15116 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 15117 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 15118 } 15119 15120 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 15121 /// precedence. 15122 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 15123 SourceLocation OpLoc, Expr *LHSExpr, 15124 Expr *RHSExpr){ 15125 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 15126 if (BinaryOperator::isBitwiseOp(Opc)) 15127 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 15128 15129 // Diagnose "arg1 & arg2 | arg3" 15130 if ((Opc == BO_Or || Opc == BO_Xor) && 15131 !OpLoc.isMacroID()/* Don't warn in macros. */) { 15132 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 15133 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 15134 } 15135 15136 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 15137 // We don't warn for 'assert(a || b && "bad")' since this is safe. 15138 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 15139 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 15140 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 15141 } 15142 15143 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 15144 || Opc == BO_Shr) { 15145 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 15146 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 15147 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 15148 } 15149 15150 // Warn on overloaded shift operators and comparisons, such as: 15151 // cout << 5 == 4; 15152 if (BinaryOperator::isComparisonOp(Opc)) 15153 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 15154 } 15155 15156 // Binary Operators. 'Tok' is the token for the operator. 15157 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 15158 tok::TokenKind Kind, 15159 Expr *LHSExpr, Expr *RHSExpr) { 15160 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 15161 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 15162 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 15163 15164 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 15165 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 15166 15167 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 15168 } 15169 15170 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 15171 UnresolvedSetImpl &Functions) { 15172 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 15173 if (OverOp != OO_None && OverOp != OO_Equal) 15174 LookupOverloadedOperatorName(OverOp, S, Functions); 15175 15176 // In C++20 onwards, we may have a second operator to look up. 15177 if (getLangOpts().CPlusPlus20) { 15178 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 15179 LookupOverloadedOperatorName(ExtraOp, S, Functions); 15180 } 15181 } 15182 15183 /// Build an overloaded binary operator expression in the given scope. 15184 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 15185 BinaryOperatorKind Opc, 15186 Expr *LHS, Expr *RHS) { 15187 switch (Opc) { 15188 case BO_Assign: 15189 case BO_DivAssign: 15190 case BO_RemAssign: 15191 case BO_SubAssign: 15192 case BO_AndAssign: 15193 case BO_OrAssign: 15194 case BO_XorAssign: 15195 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 15196 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 15197 break; 15198 default: 15199 break; 15200 } 15201 15202 // Find all of the overloaded operators visible from this point. 15203 UnresolvedSet<16> Functions; 15204 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 15205 15206 // Build the (potentially-overloaded, potentially-dependent) 15207 // binary operation. 15208 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 15209 } 15210 15211 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 15212 BinaryOperatorKind Opc, 15213 Expr *LHSExpr, Expr *RHSExpr) { 15214 ExprResult LHS, RHS; 15215 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 15216 if (!LHS.isUsable() || !RHS.isUsable()) 15217 return ExprError(); 15218 LHSExpr = LHS.get(); 15219 RHSExpr = RHS.get(); 15220 15221 // We want to end up calling one of checkPseudoObjectAssignment 15222 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 15223 // both expressions are overloadable or either is type-dependent), 15224 // or CreateBuiltinBinOp (in any other case). We also want to get 15225 // any placeholder types out of the way. 15226 15227 // Handle pseudo-objects in the LHS. 15228 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 15229 // Assignments with a pseudo-object l-value need special analysis. 15230 if (pty->getKind() == BuiltinType::PseudoObject && 15231 BinaryOperator::isAssignmentOp(Opc)) 15232 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 15233 15234 // Don't resolve overloads if the other type is overloadable. 15235 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 15236 // We can't actually test that if we still have a placeholder, 15237 // though. Fortunately, none of the exceptions we see in that 15238 // code below are valid when the LHS is an overload set. Note 15239 // that an overload set can be dependently-typed, but it never 15240 // instantiates to having an overloadable type. 15241 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 15242 if (resolvedRHS.isInvalid()) return ExprError(); 15243 RHSExpr = resolvedRHS.get(); 15244 15245 if (RHSExpr->isTypeDependent() || 15246 RHSExpr->getType()->isOverloadableType()) 15247 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15248 } 15249 15250 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 15251 // template, diagnose the missing 'template' keyword instead of diagnosing 15252 // an invalid use of a bound member function. 15253 // 15254 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 15255 // to C++1z [over.over]/1.4, but we already checked for that case above. 15256 if (Opc == BO_LT && inTemplateInstantiation() && 15257 (pty->getKind() == BuiltinType::BoundMember || 15258 pty->getKind() == BuiltinType::Overload)) { 15259 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 15260 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 15261 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 15262 return isa<FunctionTemplateDecl>(ND); 15263 })) { 15264 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 15265 : OE->getNameLoc(), 15266 diag::err_template_kw_missing) 15267 << OE->getName().getAsString() << ""; 15268 return ExprError(); 15269 } 15270 } 15271 15272 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 15273 if (LHS.isInvalid()) return ExprError(); 15274 LHSExpr = LHS.get(); 15275 } 15276 15277 // Handle pseudo-objects in the RHS. 15278 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 15279 // An overload in the RHS can potentially be resolved by the type 15280 // being assigned to. 15281 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 15282 if (getLangOpts().CPlusPlus && 15283 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 15284 LHSExpr->getType()->isOverloadableType())) 15285 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15286 15287 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 15288 } 15289 15290 // Don't resolve overloads if the other type is overloadable. 15291 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 15292 LHSExpr->getType()->isOverloadableType()) 15293 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15294 15295 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 15296 if (!resolvedRHS.isUsable()) return ExprError(); 15297 RHSExpr = resolvedRHS.get(); 15298 } 15299 15300 if (getLangOpts().CPlusPlus) { 15301 // If either expression is type-dependent, always build an 15302 // overloaded op. 15303 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 15304 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15305 15306 // Otherwise, build an overloaded op if either expression has an 15307 // overloadable type. 15308 if (LHSExpr->getType()->isOverloadableType() || 15309 RHSExpr->getType()->isOverloadableType()) 15310 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15311 } 15312 15313 if (getLangOpts().RecoveryAST && 15314 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 15315 assert(!getLangOpts().CPlusPlus); 15316 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 15317 "Should only occur in error-recovery path."); 15318 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 15319 // C [6.15.16] p3: 15320 // An assignment expression has the value of the left operand after the 15321 // assignment, but is not an lvalue. 15322 return CompoundAssignOperator::Create( 15323 Context, LHSExpr, RHSExpr, Opc, 15324 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 15325 OpLoc, CurFPFeatureOverrides()); 15326 QualType ResultType; 15327 switch (Opc) { 15328 case BO_Assign: 15329 ResultType = LHSExpr->getType().getUnqualifiedType(); 15330 break; 15331 case BO_LT: 15332 case BO_GT: 15333 case BO_LE: 15334 case BO_GE: 15335 case BO_EQ: 15336 case BO_NE: 15337 case BO_LAnd: 15338 case BO_LOr: 15339 // These operators have a fixed result type regardless of operands. 15340 ResultType = Context.IntTy; 15341 break; 15342 case BO_Comma: 15343 ResultType = RHSExpr->getType(); 15344 break; 15345 default: 15346 ResultType = Context.DependentTy; 15347 break; 15348 } 15349 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 15350 VK_PRValue, OK_Ordinary, OpLoc, 15351 CurFPFeatureOverrides()); 15352 } 15353 15354 // Build a built-in binary operation. 15355 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 15356 } 15357 15358 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 15359 if (T.isNull() || T->isDependentType()) 15360 return false; 15361 15362 if (!T->isPromotableIntegerType()) 15363 return true; 15364 15365 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 15366 } 15367 15368 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 15369 UnaryOperatorKind Opc, 15370 Expr *InputExpr) { 15371 ExprResult Input = InputExpr; 15372 ExprValueKind VK = VK_PRValue; 15373 ExprObjectKind OK = OK_Ordinary; 15374 QualType resultType; 15375 bool CanOverflow = false; 15376 15377 bool ConvertHalfVec = false; 15378 if (getLangOpts().OpenCL) { 15379 QualType Ty = InputExpr->getType(); 15380 // The only legal unary operation for atomics is '&'. 15381 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 15382 // OpenCL special types - image, sampler, pipe, and blocks are to be used 15383 // only with a builtin functions and therefore should be disallowed here. 15384 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 15385 || Ty->isBlockPointerType())) { 15386 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15387 << InputExpr->getType() 15388 << Input.get()->getSourceRange()); 15389 } 15390 } 15391 15392 if (getLangOpts().HLSL) { 15393 if (Opc == UO_AddrOf) 15394 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0); 15395 if (Opc == UO_Deref) 15396 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1); 15397 } 15398 15399 switch (Opc) { 15400 case UO_PreInc: 15401 case UO_PreDec: 15402 case UO_PostInc: 15403 case UO_PostDec: 15404 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 15405 OpLoc, 15406 Opc == UO_PreInc || 15407 Opc == UO_PostInc, 15408 Opc == UO_PreInc || 15409 Opc == UO_PreDec); 15410 CanOverflow = isOverflowingIntegerType(Context, resultType); 15411 break; 15412 case UO_AddrOf: 15413 resultType = CheckAddressOfOperand(Input, OpLoc); 15414 CheckAddressOfNoDeref(InputExpr); 15415 RecordModifiableNonNullParam(*this, InputExpr); 15416 break; 15417 case UO_Deref: { 15418 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 15419 if (Input.isInvalid()) return ExprError(); 15420 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 15421 break; 15422 } 15423 case UO_Plus: 15424 case UO_Minus: 15425 CanOverflow = Opc == UO_Minus && 15426 isOverflowingIntegerType(Context, Input.get()->getType()); 15427 Input = UsualUnaryConversions(Input.get()); 15428 if (Input.isInvalid()) return ExprError(); 15429 // Unary plus and minus require promoting an operand of half vector to a 15430 // float vector and truncating the result back to a half vector. For now, we 15431 // do this only when HalfArgsAndReturns is set (that is, when the target is 15432 // arm or arm64). 15433 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 15434 15435 // If the operand is a half vector, promote it to a float vector. 15436 if (ConvertHalfVec) 15437 Input = convertVector(Input.get(), Context.FloatTy, *this); 15438 resultType = Input.get()->getType(); 15439 if (resultType->isDependentType()) 15440 break; 15441 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 15442 break; 15443 else if (resultType->isVectorType() && 15444 // The z vector extensions don't allow + or - with bool vectors. 15445 (!Context.getLangOpts().ZVector || 15446 resultType->castAs<VectorType>()->getVectorKind() != 15447 VectorType::AltiVecBool)) 15448 break; 15449 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 15450 Opc == UO_Plus && 15451 resultType->isPointerType()) 15452 break; 15453 15454 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15455 << resultType << Input.get()->getSourceRange()); 15456 15457 case UO_Not: // bitwise complement 15458 Input = UsualUnaryConversions(Input.get()); 15459 if (Input.isInvalid()) 15460 return ExprError(); 15461 resultType = Input.get()->getType(); 15462 if (resultType->isDependentType()) 15463 break; 15464 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 15465 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 15466 // C99 does not support '~' for complex conjugation. 15467 Diag(OpLoc, diag::ext_integer_complement_complex) 15468 << resultType << Input.get()->getSourceRange(); 15469 else if (resultType->hasIntegerRepresentation()) 15470 break; 15471 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 15472 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 15473 // on vector float types. 15474 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 15475 if (!T->isIntegerType()) 15476 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15477 << resultType << Input.get()->getSourceRange()); 15478 } else { 15479 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15480 << resultType << Input.get()->getSourceRange()); 15481 } 15482 break; 15483 15484 case UO_LNot: // logical negation 15485 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 15486 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 15487 if (Input.isInvalid()) return ExprError(); 15488 resultType = Input.get()->getType(); 15489 15490 // Though we still have to promote half FP to float... 15491 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 15492 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 15493 resultType = Context.FloatTy; 15494 } 15495 15496 if (resultType->isDependentType()) 15497 break; 15498 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 15499 // C99 6.5.3.3p1: ok, fallthrough; 15500 if (Context.getLangOpts().CPlusPlus) { 15501 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 15502 // operand contextually converted to bool. 15503 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 15504 ScalarTypeToBooleanCastKind(resultType)); 15505 } else if (Context.getLangOpts().OpenCL && 15506 Context.getLangOpts().OpenCLVersion < 120) { 15507 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 15508 // operate on scalar float types. 15509 if (!resultType->isIntegerType() && !resultType->isPointerType()) 15510 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15511 << resultType << Input.get()->getSourceRange()); 15512 } 15513 } else if (resultType->isExtVectorType()) { 15514 if (Context.getLangOpts().OpenCL && 15515 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { 15516 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 15517 // operate on vector float types. 15518 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 15519 if (!T->isIntegerType()) 15520 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15521 << resultType << Input.get()->getSourceRange()); 15522 } 15523 // Vector logical not returns the signed variant of the operand type. 15524 resultType = GetSignedVectorType(resultType); 15525 break; 15526 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 15527 const VectorType *VTy = resultType->castAs<VectorType>(); 15528 if (VTy->getVectorKind() != VectorType::GenericVector) 15529 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15530 << resultType << Input.get()->getSourceRange()); 15531 15532 // Vector logical not returns the signed variant of the operand type. 15533 resultType = GetSignedVectorType(resultType); 15534 break; 15535 } else { 15536 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15537 << resultType << Input.get()->getSourceRange()); 15538 } 15539 15540 // LNot always has type int. C99 6.5.3.3p5. 15541 // In C++, it's bool. C++ 5.3.1p8 15542 resultType = Context.getLogicalOperationType(); 15543 break; 15544 case UO_Real: 15545 case UO_Imag: 15546 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 15547 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 15548 // complex l-values to ordinary l-values and all other values to r-values. 15549 if (Input.isInvalid()) return ExprError(); 15550 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 15551 if (Input.get()->isGLValue() && 15552 Input.get()->getObjectKind() == OK_Ordinary) 15553 VK = Input.get()->getValueKind(); 15554 } else if (!getLangOpts().CPlusPlus) { 15555 // In C, a volatile scalar is read by __imag. In C++, it is not. 15556 Input = DefaultLvalueConversion(Input.get()); 15557 } 15558 break; 15559 case UO_Extension: 15560 resultType = Input.get()->getType(); 15561 VK = Input.get()->getValueKind(); 15562 OK = Input.get()->getObjectKind(); 15563 break; 15564 case UO_Coawait: 15565 // It's unnecessary to represent the pass-through operator co_await in the 15566 // AST; just return the input expression instead. 15567 assert(!Input.get()->getType()->isDependentType() && 15568 "the co_await expression must be non-dependant before " 15569 "building operator co_await"); 15570 return Input; 15571 } 15572 if (resultType.isNull() || Input.isInvalid()) 15573 return ExprError(); 15574 15575 // Check for array bounds violations in the operand of the UnaryOperator, 15576 // except for the '*' and '&' operators that have to be handled specially 15577 // by CheckArrayAccess (as there are special cases like &array[arraysize] 15578 // that are explicitly defined as valid by the standard). 15579 if (Opc != UO_AddrOf && Opc != UO_Deref) 15580 CheckArrayAccess(Input.get()); 15581 15582 auto *UO = 15583 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 15584 OpLoc, CanOverflow, CurFPFeatureOverrides()); 15585 15586 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 15587 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 15588 !isUnevaluatedContext()) 15589 ExprEvalContexts.back().PossibleDerefs.insert(UO); 15590 15591 // Convert the result back to a half vector. 15592 if (ConvertHalfVec) 15593 return convertVector(UO, Context.HalfTy, *this); 15594 return UO; 15595 } 15596 15597 /// Determine whether the given expression is a qualified member 15598 /// access expression, of a form that could be turned into a pointer to member 15599 /// with the address-of operator. 15600 bool Sema::isQualifiedMemberAccess(Expr *E) { 15601 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15602 if (!DRE->getQualifier()) 15603 return false; 15604 15605 ValueDecl *VD = DRE->getDecl(); 15606 if (!VD->isCXXClassMember()) 15607 return false; 15608 15609 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 15610 return true; 15611 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 15612 return Method->isInstance(); 15613 15614 return false; 15615 } 15616 15617 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15618 if (!ULE->getQualifier()) 15619 return false; 15620 15621 for (NamedDecl *D : ULE->decls()) { 15622 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 15623 if (Method->isInstance()) 15624 return true; 15625 } else { 15626 // Overload set does not contain methods. 15627 break; 15628 } 15629 } 15630 15631 return false; 15632 } 15633 15634 return false; 15635 } 15636 15637 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 15638 UnaryOperatorKind Opc, Expr *Input) { 15639 // First things first: handle placeholders so that the 15640 // overloaded-operator check considers the right type. 15641 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 15642 // Increment and decrement of pseudo-object references. 15643 if (pty->getKind() == BuiltinType::PseudoObject && 15644 UnaryOperator::isIncrementDecrementOp(Opc)) 15645 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 15646 15647 // extension is always a builtin operator. 15648 if (Opc == UO_Extension) 15649 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15650 15651 // & gets special logic for several kinds of placeholder. 15652 // The builtin code knows what to do. 15653 if (Opc == UO_AddrOf && 15654 (pty->getKind() == BuiltinType::Overload || 15655 pty->getKind() == BuiltinType::UnknownAny || 15656 pty->getKind() == BuiltinType::BoundMember)) 15657 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15658 15659 // Anything else needs to be handled now. 15660 ExprResult Result = CheckPlaceholderExpr(Input); 15661 if (Result.isInvalid()) return ExprError(); 15662 Input = Result.get(); 15663 } 15664 15665 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 15666 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 15667 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 15668 // Find all of the overloaded operators visible from this point. 15669 UnresolvedSet<16> Functions; 15670 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 15671 if (S && OverOp != OO_None) 15672 LookupOverloadedOperatorName(OverOp, S, Functions); 15673 15674 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 15675 } 15676 15677 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15678 } 15679 15680 // Unary Operators. 'Tok' is the token for the operator. 15681 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 15682 tok::TokenKind Op, Expr *Input) { 15683 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 15684 } 15685 15686 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 15687 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 15688 LabelDecl *TheDecl) { 15689 TheDecl->markUsed(Context); 15690 // Create the AST node. The address of a label always has type 'void*'. 15691 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 15692 Context.getPointerType(Context.VoidTy)); 15693 } 15694 15695 void Sema::ActOnStartStmtExpr() { 15696 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15697 } 15698 15699 void Sema::ActOnStmtExprError() { 15700 // Note that function is also called by TreeTransform when leaving a 15701 // StmtExpr scope without rebuilding anything. 15702 15703 DiscardCleanupsInEvaluationContext(); 15704 PopExpressionEvaluationContext(); 15705 } 15706 15707 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15708 SourceLocation RPLoc) { 15709 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15710 } 15711 15712 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15713 SourceLocation RPLoc, unsigned TemplateDepth) { 15714 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15715 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15716 15717 if (hasAnyUnrecoverableErrorsInThisFunction()) 15718 DiscardCleanupsInEvaluationContext(); 15719 assert(!Cleanup.exprNeedsCleanups() && 15720 "cleanups within StmtExpr not correctly bound!"); 15721 PopExpressionEvaluationContext(); 15722 15723 // FIXME: there are a variety of strange constraints to enforce here, for 15724 // example, it is not possible to goto into a stmt expression apparently. 15725 // More semantic analysis is needed. 15726 15727 // If there are sub-stmts in the compound stmt, take the type of the last one 15728 // as the type of the stmtexpr. 15729 QualType Ty = Context.VoidTy; 15730 bool StmtExprMayBindToTemp = false; 15731 if (!Compound->body_empty()) { 15732 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15733 if (const auto *LastStmt = 15734 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15735 if (const Expr *Value = LastStmt->getExprStmt()) { 15736 StmtExprMayBindToTemp = true; 15737 Ty = Value->getType(); 15738 } 15739 } 15740 } 15741 15742 // FIXME: Check that expression type is complete/non-abstract; statement 15743 // expressions are not lvalues. 15744 Expr *ResStmtExpr = 15745 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15746 if (StmtExprMayBindToTemp) 15747 return MaybeBindToTemporary(ResStmtExpr); 15748 return ResStmtExpr; 15749 } 15750 15751 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15752 if (ER.isInvalid()) 15753 return ExprError(); 15754 15755 // Do function/array conversion on the last expression, but not 15756 // lvalue-to-rvalue. However, initialize an unqualified type. 15757 ER = DefaultFunctionArrayConversion(ER.get()); 15758 if (ER.isInvalid()) 15759 return ExprError(); 15760 Expr *E = ER.get(); 15761 15762 if (E->isTypeDependent()) 15763 return E; 15764 15765 // In ARC, if the final expression ends in a consume, splice 15766 // the consume out and bind it later. In the alternate case 15767 // (when dealing with a retainable type), the result 15768 // initialization will create a produce. In both cases the 15769 // result will be +1, and we'll need to balance that out with 15770 // a bind. 15771 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15772 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15773 return Cast->getSubExpr(); 15774 15775 // FIXME: Provide a better location for the initialization. 15776 return PerformCopyInitialization( 15777 InitializedEntity::InitializeStmtExprResult( 15778 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15779 SourceLocation(), E); 15780 } 15781 15782 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15783 TypeSourceInfo *TInfo, 15784 ArrayRef<OffsetOfComponent> Components, 15785 SourceLocation RParenLoc) { 15786 QualType ArgTy = TInfo->getType(); 15787 bool Dependent = ArgTy->isDependentType(); 15788 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15789 15790 // We must have at least one component that refers to the type, and the first 15791 // one is known to be a field designator. Verify that the ArgTy represents 15792 // a struct/union/class. 15793 if (!Dependent && !ArgTy->isRecordType()) 15794 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15795 << ArgTy << TypeRange); 15796 15797 // Type must be complete per C99 7.17p3 because a declaring a variable 15798 // with an incomplete type would be ill-formed. 15799 if (!Dependent 15800 && RequireCompleteType(BuiltinLoc, ArgTy, 15801 diag::err_offsetof_incomplete_type, TypeRange)) 15802 return ExprError(); 15803 15804 bool DidWarnAboutNonPOD = false; 15805 QualType CurrentType = ArgTy; 15806 SmallVector<OffsetOfNode, 4> Comps; 15807 SmallVector<Expr*, 4> Exprs; 15808 for (const OffsetOfComponent &OC : Components) { 15809 if (OC.isBrackets) { 15810 // Offset of an array sub-field. TODO: Should we allow vector elements? 15811 if (!CurrentType->isDependentType()) { 15812 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15813 if(!AT) 15814 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15815 << CurrentType); 15816 CurrentType = AT->getElementType(); 15817 } else 15818 CurrentType = Context.DependentTy; 15819 15820 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15821 if (IdxRval.isInvalid()) 15822 return ExprError(); 15823 Expr *Idx = IdxRval.get(); 15824 15825 // The expression must be an integral expression. 15826 // FIXME: An integral constant expression? 15827 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15828 !Idx->getType()->isIntegerType()) 15829 return ExprError( 15830 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15831 << Idx->getSourceRange()); 15832 15833 // Record this array index. 15834 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15835 Exprs.push_back(Idx); 15836 continue; 15837 } 15838 15839 // Offset of a field. 15840 if (CurrentType->isDependentType()) { 15841 // We have the offset of a field, but we can't look into the dependent 15842 // type. Just record the identifier of the field. 15843 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15844 CurrentType = Context.DependentTy; 15845 continue; 15846 } 15847 15848 // We need to have a complete type to look into. 15849 if (RequireCompleteType(OC.LocStart, CurrentType, 15850 diag::err_offsetof_incomplete_type)) 15851 return ExprError(); 15852 15853 // Look for the designated field. 15854 const RecordType *RC = CurrentType->getAs<RecordType>(); 15855 if (!RC) 15856 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15857 << CurrentType); 15858 RecordDecl *RD = RC->getDecl(); 15859 15860 // C++ [lib.support.types]p5: 15861 // The macro offsetof accepts a restricted set of type arguments in this 15862 // International Standard. type shall be a POD structure or a POD union 15863 // (clause 9). 15864 // C++11 [support.types]p4: 15865 // If type is not a standard-layout class (Clause 9), the results are 15866 // undefined. 15867 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15868 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15869 unsigned DiagID = 15870 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15871 : diag::ext_offsetof_non_pod_type; 15872 15873 if (!IsSafe && !DidWarnAboutNonPOD && 15874 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15875 PDiag(DiagID) 15876 << SourceRange(Components[0].LocStart, OC.LocEnd) 15877 << CurrentType)) 15878 DidWarnAboutNonPOD = true; 15879 } 15880 15881 // Look for the field. 15882 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15883 LookupQualifiedName(R, RD); 15884 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15885 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15886 if (!MemberDecl) { 15887 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15888 MemberDecl = IndirectMemberDecl->getAnonField(); 15889 } 15890 15891 if (!MemberDecl) 15892 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15893 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15894 OC.LocEnd)); 15895 15896 // C99 7.17p3: 15897 // (If the specified member is a bit-field, the behavior is undefined.) 15898 // 15899 // We diagnose this as an error. 15900 if (MemberDecl->isBitField()) { 15901 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15902 << MemberDecl->getDeclName() 15903 << SourceRange(BuiltinLoc, RParenLoc); 15904 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15905 return ExprError(); 15906 } 15907 15908 RecordDecl *Parent = MemberDecl->getParent(); 15909 if (IndirectMemberDecl) 15910 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15911 15912 // If the member was found in a base class, introduce OffsetOfNodes for 15913 // the base class indirections. 15914 CXXBasePaths Paths; 15915 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15916 Paths)) { 15917 if (Paths.getDetectedVirtual()) { 15918 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15919 << MemberDecl->getDeclName() 15920 << SourceRange(BuiltinLoc, RParenLoc); 15921 return ExprError(); 15922 } 15923 15924 CXXBasePath &Path = Paths.front(); 15925 for (const CXXBasePathElement &B : Path) 15926 Comps.push_back(OffsetOfNode(B.Base)); 15927 } 15928 15929 if (IndirectMemberDecl) { 15930 for (auto *FI : IndirectMemberDecl->chain()) { 15931 assert(isa<FieldDecl>(FI)); 15932 Comps.push_back(OffsetOfNode(OC.LocStart, 15933 cast<FieldDecl>(FI), OC.LocEnd)); 15934 } 15935 } else 15936 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15937 15938 CurrentType = MemberDecl->getType().getNonReferenceType(); 15939 } 15940 15941 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15942 Comps, Exprs, RParenLoc); 15943 } 15944 15945 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15946 SourceLocation BuiltinLoc, 15947 SourceLocation TypeLoc, 15948 ParsedType ParsedArgTy, 15949 ArrayRef<OffsetOfComponent> Components, 15950 SourceLocation RParenLoc) { 15951 15952 TypeSourceInfo *ArgTInfo; 15953 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15954 if (ArgTy.isNull()) 15955 return ExprError(); 15956 15957 if (!ArgTInfo) 15958 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15959 15960 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15961 } 15962 15963 15964 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15965 Expr *CondExpr, 15966 Expr *LHSExpr, Expr *RHSExpr, 15967 SourceLocation RPLoc) { 15968 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15969 15970 ExprValueKind VK = VK_PRValue; 15971 ExprObjectKind OK = OK_Ordinary; 15972 QualType resType; 15973 bool CondIsTrue = false; 15974 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15975 resType = Context.DependentTy; 15976 } else { 15977 // The conditional expression is required to be a constant expression. 15978 llvm::APSInt condEval(32); 15979 ExprResult CondICE = VerifyIntegerConstantExpression( 15980 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15981 if (CondICE.isInvalid()) 15982 return ExprError(); 15983 CondExpr = CondICE.get(); 15984 CondIsTrue = condEval.getZExtValue(); 15985 15986 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15987 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15988 15989 resType = ActiveExpr->getType(); 15990 VK = ActiveExpr->getValueKind(); 15991 OK = ActiveExpr->getObjectKind(); 15992 } 15993 15994 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15995 resType, VK, OK, RPLoc, CondIsTrue); 15996 } 15997 15998 //===----------------------------------------------------------------------===// 15999 // Clang Extensions. 16000 //===----------------------------------------------------------------------===// 16001 16002 /// ActOnBlockStart - This callback is invoked when a block literal is started. 16003 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 16004 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 16005 16006 if (LangOpts.CPlusPlus) { 16007 MangleNumberingContext *MCtx; 16008 Decl *ManglingContextDecl; 16009 std::tie(MCtx, ManglingContextDecl) = 16010 getCurrentMangleNumberContext(Block->getDeclContext()); 16011 if (MCtx) { 16012 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 16013 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 16014 } 16015 } 16016 16017 PushBlockScope(CurScope, Block); 16018 CurContext->addDecl(Block); 16019 if (CurScope) 16020 PushDeclContext(CurScope, Block); 16021 else 16022 CurContext = Block; 16023 16024 getCurBlock()->HasImplicitReturnType = true; 16025 16026 // Enter a new evaluation context to insulate the block from any 16027 // cleanups from the enclosing full-expression. 16028 PushExpressionEvaluationContext( 16029 ExpressionEvaluationContext::PotentiallyEvaluated); 16030 } 16031 16032 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 16033 Scope *CurScope) { 16034 assert(ParamInfo.getIdentifier() == nullptr && 16035 "block-id should have no identifier!"); 16036 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 16037 BlockScopeInfo *CurBlock = getCurBlock(); 16038 16039 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 16040 QualType T = Sig->getType(); 16041 16042 // FIXME: We should allow unexpanded parameter packs here, but that would, 16043 // in turn, make the block expression contain unexpanded parameter packs. 16044 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 16045 // Drop the parameters. 16046 FunctionProtoType::ExtProtoInfo EPI; 16047 EPI.HasTrailingReturn = false; 16048 EPI.TypeQuals.addConst(); 16049 T = Context.getFunctionType(Context.DependentTy, None, EPI); 16050 Sig = Context.getTrivialTypeSourceInfo(T); 16051 } 16052 16053 // GetTypeForDeclarator always produces a function type for a block 16054 // literal signature. Furthermore, it is always a FunctionProtoType 16055 // unless the function was written with a typedef. 16056 assert(T->isFunctionType() && 16057 "GetTypeForDeclarator made a non-function block signature"); 16058 16059 // Look for an explicit signature in that function type. 16060 FunctionProtoTypeLoc ExplicitSignature; 16061 16062 if ((ExplicitSignature = Sig->getTypeLoc() 16063 .getAsAdjusted<FunctionProtoTypeLoc>())) { 16064 16065 // Check whether that explicit signature was synthesized by 16066 // GetTypeForDeclarator. If so, don't save that as part of the 16067 // written signature. 16068 if (ExplicitSignature.getLocalRangeBegin() == 16069 ExplicitSignature.getLocalRangeEnd()) { 16070 // This would be much cheaper if we stored TypeLocs instead of 16071 // TypeSourceInfos. 16072 TypeLoc Result = ExplicitSignature.getReturnLoc(); 16073 unsigned Size = Result.getFullDataSize(); 16074 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 16075 Sig->getTypeLoc().initializeFullCopy(Result, Size); 16076 16077 ExplicitSignature = FunctionProtoTypeLoc(); 16078 } 16079 } 16080 16081 CurBlock->TheDecl->setSignatureAsWritten(Sig); 16082 CurBlock->FunctionType = T; 16083 16084 const auto *Fn = T->castAs<FunctionType>(); 16085 QualType RetTy = Fn->getReturnType(); 16086 bool isVariadic = 16087 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 16088 16089 CurBlock->TheDecl->setIsVariadic(isVariadic); 16090 16091 // Context.DependentTy is used as a placeholder for a missing block 16092 // return type. TODO: what should we do with declarators like: 16093 // ^ * { ... } 16094 // If the answer is "apply template argument deduction".... 16095 if (RetTy != Context.DependentTy) { 16096 CurBlock->ReturnType = RetTy; 16097 CurBlock->TheDecl->setBlockMissingReturnType(false); 16098 CurBlock->HasImplicitReturnType = false; 16099 } 16100 16101 // Push block parameters from the declarator if we had them. 16102 SmallVector<ParmVarDecl*, 8> Params; 16103 if (ExplicitSignature) { 16104 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 16105 ParmVarDecl *Param = ExplicitSignature.getParam(I); 16106 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 16107 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 16108 // Diagnose this as an extension in C17 and earlier. 16109 if (!getLangOpts().C2x) 16110 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 16111 } 16112 Params.push_back(Param); 16113 } 16114 16115 // Fake up parameter variables if we have a typedef, like 16116 // ^ fntype { ... } 16117 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 16118 for (const auto &I : Fn->param_types()) { 16119 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 16120 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 16121 Params.push_back(Param); 16122 } 16123 } 16124 16125 // Set the parameters on the block decl. 16126 if (!Params.empty()) { 16127 CurBlock->TheDecl->setParams(Params); 16128 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 16129 /*CheckParameterNames=*/false); 16130 } 16131 16132 // Finally we can process decl attributes. 16133 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 16134 16135 // Put the parameter variables in scope. 16136 for (auto AI : CurBlock->TheDecl->parameters()) { 16137 AI->setOwningFunction(CurBlock->TheDecl); 16138 16139 // If this has an identifier, add it to the scope stack. 16140 if (AI->getIdentifier()) { 16141 CheckShadow(CurBlock->TheScope, AI); 16142 16143 PushOnScopeChains(AI, CurBlock->TheScope); 16144 } 16145 } 16146 } 16147 16148 /// ActOnBlockError - If there is an error parsing a block, this callback 16149 /// is invoked to pop the information about the block from the action impl. 16150 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 16151 // Leave the expression-evaluation context. 16152 DiscardCleanupsInEvaluationContext(); 16153 PopExpressionEvaluationContext(); 16154 16155 // Pop off CurBlock, handle nested blocks. 16156 PopDeclContext(); 16157 PopFunctionScopeInfo(); 16158 } 16159 16160 /// ActOnBlockStmtExpr - This is called when the body of a block statement 16161 /// literal was successfully completed. ^(int x){...} 16162 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 16163 Stmt *Body, Scope *CurScope) { 16164 // If blocks are disabled, emit an error. 16165 if (!LangOpts.Blocks) 16166 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 16167 16168 // Leave the expression-evaluation context. 16169 if (hasAnyUnrecoverableErrorsInThisFunction()) 16170 DiscardCleanupsInEvaluationContext(); 16171 assert(!Cleanup.exprNeedsCleanups() && 16172 "cleanups within block not correctly bound!"); 16173 PopExpressionEvaluationContext(); 16174 16175 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 16176 BlockDecl *BD = BSI->TheDecl; 16177 16178 if (BSI->HasImplicitReturnType) 16179 deduceClosureReturnType(*BSI); 16180 16181 QualType RetTy = Context.VoidTy; 16182 if (!BSI->ReturnType.isNull()) 16183 RetTy = BSI->ReturnType; 16184 16185 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 16186 QualType BlockTy; 16187 16188 // If the user wrote a function type in some form, try to use that. 16189 if (!BSI->FunctionType.isNull()) { 16190 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 16191 16192 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 16193 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 16194 16195 // Turn protoless block types into nullary block types. 16196 if (isa<FunctionNoProtoType>(FTy)) { 16197 FunctionProtoType::ExtProtoInfo EPI; 16198 EPI.ExtInfo = Ext; 16199 BlockTy = Context.getFunctionType(RetTy, None, EPI); 16200 16201 // Otherwise, if we don't need to change anything about the function type, 16202 // preserve its sugar structure. 16203 } else if (FTy->getReturnType() == RetTy && 16204 (!NoReturn || FTy->getNoReturnAttr())) { 16205 BlockTy = BSI->FunctionType; 16206 16207 // Otherwise, make the minimal modifications to the function type. 16208 } else { 16209 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 16210 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 16211 EPI.TypeQuals = Qualifiers(); 16212 EPI.ExtInfo = Ext; 16213 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 16214 } 16215 16216 // If we don't have a function type, just build one from nothing. 16217 } else { 16218 FunctionProtoType::ExtProtoInfo EPI; 16219 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 16220 BlockTy = Context.getFunctionType(RetTy, None, EPI); 16221 } 16222 16223 DiagnoseUnusedParameters(BD->parameters()); 16224 BlockTy = Context.getBlockPointerType(BlockTy); 16225 16226 // If needed, diagnose invalid gotos and switches in the block. 16227 if (getCurFunction()->NeedsScopeChecking() && 16228 !PP.isCodeCompletionEnabled()) 16229 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 16230 16231 BD->setBody(cast<CompoundStmt>(Body)); 16232 16233 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 16234 DiagnoseUnguardedAvailabilityViolations(BD); 16235 16236 // Try to apply the named return value optimization. We have to check again 16237 // if we can do this, though, because blocks keep return statements around 16238 // to deduce an implicit return type. 16239 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 16240 !BD->isDependentContext()) 16241 computeNRVO(Body, BSI); 16242 16243 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 16244 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 16245 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 16246 NTCUK_Destruct|NTCUK_Copy); 16247 16248 PopDeclContext(); 16249 16250 // Set the captured variables on the block. 16251 SmallVector<BlockDecl::Capture, 4> Captures; 16252 for (Capture &Cap : BSI->Captures) { 16253 if (Cap.isInvalid() || Cap.isThisCapture()) 16254 continue; 16255 16256 VarDecl *Var = Cap.getVariable(); 16257 Expr *CopyExpr = nullptr; 16258 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 16259 if (const RecordType *Record = 16260 Cap.getCaptureType()->getAs<RecordType>()) { 16261 // The capture logic needs the destructor, so make sure we mark it. 16262 // Usually this is unnecessary because most local variables have 16263 // their destructors marked at declaration time, but parameters are 16264 // an exception because it's technically only the call site that 16265 // actually requires the destructor. 16266 if (isa<ParmVarDecl>(Var)) 16267 FinalizeVarWithDestructor(Var, Record); 16268 16269 // Enter a separate potentially-evaluated context while building block 16270 // initializers to isolate their cleanups from those of the block 16271 // itself. 16272 // FIXME: Is this appropriate even when the block itself occurs in an 16273 // unevaluated operand? 16274 EnterExpressionEvaluationContext EvalContext( 16275 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 16276 16277 SourceLocation Loc = Cap.getLocation(); 16278 16279 ExprResult Result = BuildDeclarationNameExpr( 16280 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 16281 16282 // According to the blocks spec, the capture of a variable from 16283 // the stack requires a const copy constructor. This is not true 16284 // of the copy/move done to move a __block variable to the heap. 16285 if (!Result.isInvalid() && 16286 !Result.get()->getType().isConstQualified()) { 16287 Result = ImpCastExprToType(Result.get(), 16288 Result.get()->getType().withConst(), 16289 CK_NoOp, VK_LValue); 16290 } 16291 16292 if (!Result.isInvalid()) { 16293 Result = PerformCopyInitialization( 16294 InitializedEntity::InitializeBlock(Var->getLocation(), 16295 Cap.getCaptureType()), 16296 Loc, Result.get()); 16297 } 16298 16299 // Build a full-expression copy expression if initialization 16300 // succeeded and used a non-trivial constructor. Recover from 16301 // errors by pretending that the copy isn't necessary. 16302 if (!Result.isInvalid() && 16303 !cast<CXXConstructExpr>(Result.get())->getConstructor() 16304 ->isTrivial()) { 16305 Result = MaybeCreateExprWithCleanups(Result); 16306 CopyExpr = Result.get(); 16307 } 16308 } 16309 } 16310 16311 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 16312 CopyExpr); 16313 Captures.push_back(NewCap); 16314 } 16315 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 16316 16317 // Pop the block scope now but keep it alive to the end of this function. 16318 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 16319 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 16320 16321 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 16322 16323 // If the block isn't obviously global, i.e. it captures anything at 16324 // all, then we need to do a few things in the surrounding context: 16325 if (Result->getBlockDecl()->hasCaptures()) { 16326 // First, this expression has a new cleanup object. 16327 ExprCleanupObjects.push_back(Result->getBlockDecl()); 16328 Cleanup.setExprNeedsCleanups(true); 16329 16330 // It also gets a branch-protected scope if any of the captured 16331 // variables needs destruction. 16332 for (const auto &CI : Result->getBlockDecl()->captures()) { 16333 const VarDecl *var = CI.getVariable(); 16334 if (var->getType().isDestructedType() != QualType::DK_none) { 16335 setFunctionHasBranchProtectedScope(); 16336 break; 16337 } 16338 } 16339 } 16340 16341 if (getCurFunction()) 16342 getCurFunction()->addBlock(BD); 16343 16344 return Result; 16345 } 16346 16347 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 16348 SourceLocation RPLoc) { 16349 TypeSourceInfo *TInfo; 16350 GetTypeFromParser(Ty, &TInfo); 16351 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 16352 } 16353 16354 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 16355 Expr *E, TypeSourceInfo *TInfo, 16356 SourceLocation RPLoc) { 16357 Expr *OrigExpr = E; 16358 bool IsMS = false; 16359 16360 // CUDA device code does not support varargs. 16361 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 16362 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 16363 CUDAFunctionTarget T = IdentifyCUDATarget(F); 16364 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 16365 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 16366 } 16367 } 16368 16369 // NVPTX does not support va_arg expression. 16370 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 16371 Context.getTargetInfo().getTriple().isNVPTX()) 16372 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 16373 16374 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 16375 // as Microsoft ABI on an actual Microsoft platform, where 16376 // __builtin_ms_va_list and __builtin_va_list are the same.) 16377 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 16378 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 16379 QualType MSVaListType = Context.getBuiltinMSVaListType(); 16380 if (Context.hasSameType(MSVaListType, E->getType())) { 16381 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 16382 return ExprError(); 16383 IsMS = true; 16384 } 16385 } 16386 16387 // Get the va_list type 16388 QualType VaListType = Context.getBuiltinVaListType(); 16389 if (!IsMS) { 16390 if (VaListType->isArrayType()) { 16391 // Deal with implicit array decay; for example, on x86-64, 16392 // va_list is an array, but it's supposed to decay to 16393 // a pointer for va_arg. 16394 VaListType = Context.getArrayDecayedType(VaListType); 16395 // Make sure the input expression also decays appropriately. 16396 ExprResult Result = UsualUnaryConversions(E); 16397 if (Result.isInvalid()) 16398 return ExprError(); 16399 E = Result.get(); 16400 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 16401 // If va_list is a record type and we are compiling in C++ mode, 16402 // check the argument using reference binding. 16403 InitializedEntity Entity = InitializedEntity::InitializeParameter( 16404 Context, Context.getLValueReferenceType(VaListType), false); 16405 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 16406 if (Init.isInvalid()) 16407 return ExprError(); 16408 E = Init.getAs<Expr>(); 16409 } else { 16410 // Otherwise, the va_list argument must be an l-value because 16411 // it is modified by va_arg. 16412 if (!E->isTypeDependent() && 16413 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 16414 return ExprError(); 16415 } 16416 } 16417 16418 if (!IsMS && !E->isTypeDependent() && 16419 !Context.hasSameType(VaListType, E->getType())) 16420 return ExprError( 16421 Diag(E->getBeginLoc(), 16422 diag::err_first_argument_to_va_arg_not_of_type_va_list) 16423 << OrigExpr->getType() << E->getSourceRange()); 16424 16425 if (!TInfo->getType()->isDependentType()) { 16426 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 16427 diag::err_second_parameter_to_va_arg_incomplete, 16428 TInfo->getTypeLoc())) 16429 return ExprError(); 16430 16431 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 16432 TInfo->getType(), 16433 diag::err_second_parameter_to_va_arg_abstract, 16434 TInfo->getTypeLoc())) 16435 return ExprError(); 16436 16437 if (!TInfo->getType().isPODType(Context)) { 16438 Diag(TInfo->getTypeLoc().getBeginLoc(), 16439 TInfo->getType()->isObjCLifetimeType() 16440 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 16441 : diag::warn_second_parameter_to_va_arg_not_pod) 16442 << TInfo->getType() 16443 << TInfo->getTypeLoc().getSourceRange(); 16444 } 16445 16446 // Check for va_arg where arguments of the given type will be promoted 16447 // (i.e. this va_arg is guaranteed to have undefined behavior). 16448 QualType PromoteType; 16449 if (TInfo->getType()->isPromotableIntegerType()) { 16450 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 16451 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 16452 // and C2x 7.16.1.1p2 says, in part: 16453 // If type is not compatible with the type of the actual next argument 16454 // (as promoted according to the default argument promotions), the 16455 // behavior is undefined, except for the following cases: 16456 // - both types are pointers to qualified or unqualified versions of 16457 // compatible types; 16458 // - one type is a signed integer type, the other type is the 16459 // corresponding unsigned integer type, and the value is 16460 // representable in both types; 16461 // - one type is pointer to qualified or unqualified void and the 16462 // other is a pointer to a qualified or unqualified character type. 16463 // Given that type compatibility is the primary requirement (ignoring 16464 // qualifications), you would think we could call typesAreCompatible() 16465 // directly to test this. However, in C++, that checks for *same type*, 16466 // which causes false positives when passing an enumeration type to 16467 // va_arg. Instead, get the underlying type of the enumeration and pass 16468 // that. 16469 QualType UnderlyingType = TInfo->getType(); 16470 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 16471 UnderlyingType = ET->getDecl()->getIntegerType(); 16472 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 16473 /*CompareUnqualified*/ true)) 16474 PromoteType = QualType(); 16475 16476 // If the types are still not compatible, we need to test whether the 16477 // promoted type and the underlying type are the same except for 16478 // signedness. Ask the AST for the correctly corresponding type and see 16479 // if that's compatible. 16480 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() && 16481 PromoteType->isUnsignedIntegerType() != 16482 UnderlyingType->isUnsignedIntegerType()) { 16483 UnderlyingType = 16484 UnderlyingType->isUnsignedIntegerType() 16485 ? Context.getCorrespondingSignedType(UnderlyingType) 16486 : Context.getCorrespondingUnsignedType(UnderlyingType); 16487 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 16488 /*CompareUnqualified*/ true)) 16489 PromoteType = QualType(); 16490 } 16491 } 16492 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 16493 PromoteType = Context.DoubleTy; 16494 if (!PromoteType.isNull()) 16495 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 16496 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 16497 << TInfo->getType() 16498 << PromoteType 16499 << TInfo->getTypeLoc().getSourceRange()); 16500 } 16501 16502 QualType T = TInfo->getType().getNonLValueExprType(Context); 16503 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 16504 } 16505 16506 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 16507 // The type of __null will be int or long, depending on the size of 16508 // pointers on the target. 16509 QualType Ty; 16510 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 16511 if (pw == Context.getTargetInfo().getIntWidth()) 16512 Ty = Context.IntTy; 16513 else if (pw == Context.getTargetInfo().getLongWidth()) 16514 Ty = Context.LongTy; 16515 else if (pw == Context.getTargetInfo().getLongLongWidth()) 16516 Ty = Context.LongLongTy; 16517 else { 16518 llvm_unreachable("I don't know size of pointer!"); 16519 } 16520 16521 return new (Context) GNUNullExpr(Ty, TokenLoc); 16522 } 16523 16524 static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) { 16525 CXXRecordDecl *ImplDecl = nullptr; 16526 16527 // Fetch the std::source_location::__impl decl. 16528 if (NamespaceDecl *Std = S.getStdNamespace()) { 16529 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"), 16530 Loc, Sema::LookupOrdinaryName); 16531 if (S.LookupQualifiedName(ResultSL, Std)) { 16532 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) { 16533 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"), 16534 Loc, Sema::LookupOrdinaryName); 16535 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) && 16536 S.LookupQualifiedName(ResultImpl, SLDecl)) { 16537 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>(); 16538 } 16539 } 16540 } 16541 } 16542 16543 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) { 16544 S.Diag(Loc, diag::err_std_source_location_impl_not_found); 16545 return nullptr; 16546 } 16547 16548 // Verify that __impl is a trivial struct type, with no base classes, and with 16549 // only the four expected fields. 16550 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() || 16551 ImplDecl->getNumBases() != 0) { 16552 S.Diag(Loc, diag::err_std_source_location_impl_malformed); 16553 return nullptr; 16554 } 16555 16556 unsigned Count = 0; 16557 for (FieldDecl *F : ImplDecl->fields()) { 16558 StringRef Name = F->getName(); 16559 16560 if (Name == "_M_file_name") { 16561 if (F->getType() != 16562 S.Context.getPointerType(S.Context.CharTy.withConst())) 16563 break; 16564 Count++; 16565 } else if (Name == "_M_function_name") { 16566 if (F->getType() != 16567 S.Context.getPointerType(S.Context.CharTy.withConst())) 16568 break; 16569 Count++; 16570 } else if (Name == "_M_line") { 16571 if (!F->getType()->isIntegerType()) 16572 break; 16573 Count++; 16574 } else if (Name == "_M_column") { 16575 if (!F->getType()->isIntegerType()) 16576 break; 16577 Count++; 16578 } else { 16579 Count = 100; // invalid 16580 break; 16581 } 16582 } 16583 if (Count != 4) { 16584 S.Diag(Loc, diag::err_std_source_location_impl_malformed); 16585 return nullptr; 16586 } 16587 16588 return ImplDecl; 16589 } 16590 16591 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 16592 SourceLocation BuiltinLoc, 16593 SourceLocation RPLoc) { 16594 QualType ResultTy; 16595 switch (Kind) { 16596 case SourceLocExpr::File: 16597 case SourceLocExpr::Function: { 16598 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0); 16599 ResultTy = 16600 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType()); 16601 break; 16602 } 16603 case SourceLocExpr::Line: 16604 case SourceLocExpr::Column: 16605 ResultTy = Context.UnsignedIntTy; 16606 break; 16607 case SourceLocExpr::SourceLocStruct: 16608 if (!StdSourceLocationImplDecl) { 16609 StdSourceLocationImplDecl = 16610 LookupStdSourceLocationImpl(*this, BuiltinLoc); 16611 if (!StdSourceLocationImplDecl) 16612 return ExprError(); 16613 } 16614 ResultTy = Context.getPointerType( 16615 Context.getRecordType(StdSourceLocationImplDecl).withConst()); 16616 break; 16617 } 16618 16619 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext); 16620 } 16621 16622 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 16623 QualType ResultTy, 16624 SourceLocation BuiltinLoc, 16625 SourceLocation RPLoc, 16626 DeclContext *ParentContext) { 16627 return new (Context) 16628 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext); 16629 } 16630 16631 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 16632 bool Diagnose) { 16633 if (!getLangOpts().ObjC) 16634 return false; 16635 16636 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 16637 if (!PT) 16638 return false; 16639 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 16640 16641 // Ignore any parens, implicit casts (should only be 16642 // array-to-pointer decays), and not-so-opaque values. The last is 16643 // important for making this trigger for property assignments. 16644 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 16645 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 16646 if (OV->getSourceExpr()) 16647 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 16648 16649 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 16650 if (!PT->isObjCIdType() && 16651 !(ID && ID->getIdentifier()->isStr("NSString"))) 16652 return false; 16653 if (!SL->isAscii()) 16654 return false; 16655 16656 if (Diagnose) { 16657 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 16658 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 16659 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 16660 } 16661 return true; 16662 } 16663 16664 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 16665 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 16666 isa<CXXBoolLiteralExpr>(SrcExpr)) && 16667 !SrcExpr->isNullPointerConstant( 16668 getASTContext(), Expr::NPC_NeverValueDependent)) { 16669 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 16670 return false; 16671 if (Diagnose) { 16672 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 16673 << /*number*/1 16674 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 16675 Expr *NumLit = 16676 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 16677 if (NumLit) 16678 Exp = NumLit; 16679 } 16680 return true; 16681 } 16682 16683 return false; 16684 } 16685 16686 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 16687 const Expr *SrcExpr) { 16688 if (!DstType->isFunctionPointerType() || 16689 !SrcExpr->getType()->isFunctionType()) 16690 return false; 16691 16692 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 16693 if (!DRE) 16694 return false; 16695 16696 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 16697 if (!FD) 16698 return false; 16699 16700 return !S.checkAddressOfFunctionIsAvailable(FD, 16701 /*Complain=*/true, 16702 SrcExpr->getBeginLoc()); 16703 } 16704 16705 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 16706 SourceLocation Loc, 16707 QualType DstType, QualType SrcType, 16708 Expr *SrcExpr, AssignmentAction Action, 16709 bool *Complained) { 16710 if (Complained) 16711 *Complained = false; 16712 16713 // Decode the result (notice that AST's are still created for extensions). 16714 bool CheckInferredResultType = false; 16715 bool isInvalid = false; 16716 unsigned DiagKind = 0; 16717 ConversionFixItGenerator ConvHints; 16718 bool MayHaveConvFixit = false; 16719 bool MayHaveFunctionDiff = false; 16720 const ObjCInterfaceDecl *IFace = nullptr; 16721 const ObjCProtocolDecl *PDecl = nullptr; 16722 16723 switch (ConvTy) { 16724 case Compatible: 16725 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 16726 return false; 16727 16728 case PointerToInt: 16729 if (getLangOpts().CPlusPlus) { 16730 DiagKind = diag::err_typecheck_convert_pointer_int; 16731 isInvalid = true; 16732 } else { 16733 DiagKind = diag::ext_typecheck_convert_pointer_int; 16734 } 16735 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16736 MayHaveConvFixit = true; 16737 break; 16738 case IntToPointer: 16739 if (getLangOpts().CPlusPlus) { 16740 DiagKind = diag::err_typecheck_convert_int_pointer; 16741 isInvalid = true; 16742 } else { 16743 DiagKind = diag::ext_typecheck_convert_int_pointer; 16744 } 16745 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16746 MayHaveConvFixit = true; 16747 break; 16748 case IncompatibleFunctionPointer: 16749 if (getLangOpts().CPlusPlus) { 16750 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 16751 isInvalid = true; 16752 } else { 16753 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 16754 } 16755 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16756 MayHaveConvFixit = true; 16757 break; 16758 case IncompatiblePointer: 16759 if (Action == AA_Passing_CFAudited) { 16760 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 16761 } else if (getLangOpts().CPlusPlus) { 16762 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 16763 isInvalid = true; 16764 } else { 16765 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 16766 } 16767 CheckInferredResultType = DstType->isObjCObjectPointerType() && 16768 SrcType->isObjCObjectPointerType(); 16769 if (!CheckInferredResultType) { 16770 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16771 } else if (CheckInferredResultType) { 16772 SrcType = SrcType.getUnqualifiedType(); 16773 DstType = DstType.getUnqualifiedType(); 16774 } 16775 MayHaveConvFixit = true; 16776 break; 16777 case IncompatiblePointerSign: 16778 if (getLangOpts().CPlusPlus) { 16779 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 16780 isInvalid = true; 16781 } else { 16782 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 16783 } 16784 break; 16785 case FunctionVoidPointer: 16786 if (getLangOpts().CPlusPlus) { 16787 DiagKind = diag::err_typecheck_convert_pointer_void_func; 16788 isInvalid = true; 16789 } else { 16790 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 16791 } 16792 break; 16793 case IncompatiblePointerDiscardsQualifiers: { 16794 // Perform array-to-pointer decay if necessary. 16795 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 16796 16797 isInvalid = true; 16798 16799 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 16800 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 16801 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 16802 DiagKind = diag::err_typecheck_incompatible_address_space; 16803 break; 16804 16805 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 16806 DiagKind = diag::err_typecheck_incompatible_ownership; 16807 break; 16808 } 16809 16810 llvm_unreachable("unknown error case for discarding qualifiers!"); 16811 // fallthrough 16812 } 16813 case CompatiblePointerDiscardsQualifiers: 16814 // If the qualifiers lost were because we were applying the 16815 // (deprecated) C++ conversion from a string literal to a char* 16816 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 16817 // Ideally, this check would be performed in 16818 // checkPointerTypesForAssignment. However, that would require a 16819 // bit of refactoring (so that the second argument is an 16820 // expression, rather than a type), which should be done as part 16821 // of a larger effort to fix checkPointerTypesForAssignment for 16822 // C++ semantics. 16823 if (getLangOpts().CPlusPlus && 16824 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 16825 return false; 16826 if (getLangOpts().CPlusPlus) { 16827 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 16828 isInvalid = true; 16829 } else { 16830 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 16831 } 16832 16833 break; 16834 case IncompatibleNestedPointerQualifiers: 16835 if (getLangOpts().CPlusPlus) { 16836 isInvalid = true; 16837 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 16838 } else { 16839 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16840 } 16841 break; 16842 case IncompatibleNestedPointerAddressSpaceMismatch: 16843 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16844 isInvalid = true; 16845 break; 16846 case IntToBlockPointer: 16847 DiagKind = diag::err_int_to_block_pointer; 16848 isInvalid = true; 16849 break; 16850 case IncompatibleBlockPointer: 16851 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16852 isInvalid = true; 16853 break; 16854 case IncompatibleObjCQualifiedId: { 16855 if (SrcType->isObjCQualifiedIdType()) { 16856 const ObjCObjectPointerType *srcOPT = 16857 SrcType->castAs<ObjCObjectPointerType>(); 16858 for (auto *srcProto : srcOPT->quals()) { 16859 PDecl = srcProto; 16860 break; 16861 } 16862 if (const ObjCInterfaceType *IFaceT = 16863 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16864 IFace = IFaceT->getDecl(); 16865 } 16866 else if (DstType->isObjCQualifiedIdType()) { 16867 const ObjCObjectPointerType *dstOPT = 16868 DstType->castAs<ObjCObjectPointerType>(); 16869 for (auto *dstProto : dstOPT->quals()) { 16870 PDecl = dstProto; 16871 break; 16872 } 16873 if (const ObjCInterfaceType *IFaceT = 16874 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16875 IFace = IFaceT->getDecl(); 16876 } 16877 if (getLangOpts().CPlusPlus) { 16878 DiagKind = diag::err_incompatible_qualified_id; 16879 isInvalid = true; 16880 } else { 16881 DiagKind = diag::warn_incompatible_qualified_id; 16882 } 16883 break; 16884 } 16885 case IncompatibleVectors: 16886 if (getLangOpts().CPlusPlus) { 16887 DiagKind = diag::err_incompatible_vectors; 16888 isInvalid = true; 16889 } else { 16890 DiagKind = diag::warn_incompatible_vectors; 16891 } 16892 break; 16893 case IncompatibleObjCWeakRef: 16894 DiagKind = diag::err_arc_weak_unavailable_assign; 16895 isInvalid = true; 16896 break; 16897 case Incompatible: 16898 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16899 if (Complained) 16900 *Complained = true; 16901 return true; 16902 } 16903 16904 DiagKind = diag::err_typecheck_convert_incompatible; 16905 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16906 MayHaveConvFixit = true; 16907 isInvalid = true; 16908 MayHaveFunctionDiff = true; 16909 break; 16910 } 16911 16912 QualType FirstType, SecondType; 16913 switch (Action) { 16914 case AA_Assigning: 16915 case AA_Initializing: 16916 // The destination type comes first. 16917 FirstType = DstType; 16918 SecondType = SrcType; 16919 break; 16920 16921 case AA_Returning: 16922 case AA_Passing: 16923 case AA_Passing_CFAudited: 16924 case AA_Converting: 16925 case AA_Sending: 16926 case AA_Casting: 16927 // The source type comes first. 16928 FirstType = SrcType; 16929 SecondType = DstType; 16930 break; 16931 } 16932 16933 PartialDiagnostic FDiag = PDiag(DiagKind); 16934 AssignmentAction ActionForDiag = Action; 16935 if (Action == AA_Passing_CFAudited) 16936 ActionForDiag = AA_Passing; 16937 16938 FDiag << FirstType << SecondType << ActionForDiag 16939 << SrcExpr->getSourceRange(); 16940 16941 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16942 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16943 auto isPlainChar = [](const clang::Type *Type) { 16944 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16945 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16946 }; 16947 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16948 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16949 } 16950 16951 // If we can fix the conversion, suggest the FixIts. 16952 if (!ConvHints.isNull()) { 16953 for (FixItHint &H : ConvHints.Hints) 16954 FDiag << H; 16955 } 16956 16957 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16958 16959 if (MayHaveFunctionDiff) 16960 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16961 16962 Diag(Loc, FDiag); 16963 if ((DiagKind == diag::warn_incompatible_qualified_id || 16964 DiagKind == diag::err_incompatible_qualified_id) && 16965 PDecl && IFace && !IFace->hasDefinition()) 16966 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16967 << IFace << PDecl; 16968 16969 if (SecondType == Context.OverloadTy) 16970 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16971 FirstType, /*TakingAddress=*/true); 16972 16973 if (CheckInferredResultType) 16974 EmitRelatedResultTypeNote(SrcExpr); 16975 16976 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16977 EmitRelatedResultTypeNoteForReturn(DstType); 16978 16979 if (Complained) 16980 *Complained = true; 16981 return isInvalid; 16982 } 16983 16984 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16985 llvm::APSInt *Result, 16986 AllowFoldKind CanFold) { 16987 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16988 public: 16989 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16990 QualType T) override { 16991 return S.Diag(Loc, diag::err_ice_not_integral) 16992 << T << S.LangOpts.CPlusPlus; 16993 } 16994 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16995 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16996 } 16997 } Diagnoser; 16998 16999 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 17000 } 17001 17002 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 17003 llvm::APSInt *Result, 17004 unsigned DiagID, 17005 AllowFoldKind CanFold) { 17006 class IDDiagnoser : public VerifyICEDiagnoser { 17007 unsigned DiagID; 17008 17009 public: 17010 IDDiagnoser(unsigned DiagID) 17011 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 17012 17013 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 17014 return S.Diag(Loc, DiagID); 17015 } 17016 } Diagnoser(DiagID); 17017 17018 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 17019 } 17020 17021 Sema::SemaDiagnosticBuilder 17022 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 17023 QualType T) { 17024 return diagnoseNotICE(S, Loc); 17025 } 17026 17027 Sema::SemaDiagnosticBuilder 17028 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 17029 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 17030 } 17031 17032 ExprResult 17033 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 17034 VerifyICEDiagnoser &Diagnoser, 17035 AllowFoldKind CanFold) { 17036 SourceLocation DiagLoc = E->getBeginLoc(); 17037 17038 if (getLangOpts().CPlusPlus11) { 17039 // C++11 [expr.const]p5: 17040 // If an expression of literal class type is used in a context where an 17041 // integral constant expression is required, then that class type shall 17042 // have a single non-explicit conversion function to an integral or 17043 // unscoped enumeration type 17044 ExprResult Converted; 17045 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 17046 VerifyICEDiagnoser &BaseDiagnoser; 17047 public: 17048 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 17049 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 17050 BaseDiagnoser.Suppress, true), 17051 BaseDiagnoser(BaseDiagnoser) {} 17052 17053 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 17054 QualType T) override { 17055 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 17056 } 17057 17058 SemaDiagnosticBuilder diagnoseIncomplete( 17059 Sema &S, SourceLocation Loc, QualType T) override { 17060 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 17061 } 17062 17063 SemaDiagnosticBuilder diagnoseExplicitConv( 17064 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 17065 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 17066 } 17067 17068 SemaDiagnosticBuilder noteExplicitConv( 17069 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 17070 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 17071 << ConvTy->isEnumeralType() << ConvTy; 17072 } 17073 17074 SemaDiagnosticBuilder diagnoseAmbiguous( 17075 Sema &S, SourceLocation Loc, QualType T) override { 17076 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 17077 } 17078 17079 SemaDiagnosticBuilder noteAmbiguous( 17080 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 17081 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 17082 << ConvTy->isEnumeralType() << ConvTy; 17083 } 17084 17085 SemaDiagnosticBuilder diagnoseConversion( 17086 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 17087 llvm_unreachable("conversion functions are permitted"); 17088 } 17089 } ConvertDiagnoser(Diagnoser); 17090 17091 Converted = PerformContextualImplicitConversion(DiagLoc, E, 17092 ConvertDiagnoser); 17093 if (Converted.isInvalid()) 17094 return Converted; 17095 E = Converted.get(); 17096 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 17097 return ExprError(); 17098 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 17099 // An ICE must be of integral or unscoped enumeration type. 17100 if (!Diagnoser.Suppress) 17101 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 17102 << E->getSourceRange(); 17103 return ExprError(); 17104 } 17105 17106 ExprResult RValueExpr = DefaultLvalueConversion(E); 17107 if (RValueExpr.isInvalid()) 17108 return ExprError(); 17109 17110 E = RValueExpr.get(); 17111 17112 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 17113 // in the non-ICE case. 17114 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 17115 if (Result) 17116 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 17117 if (!isa<ConstantExpr>(E)) 17118 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 17119 : ConstantExpr::Create(Context, E); 17120 return E; 17121 } 17122 17123 Expr::EvalResult EvalResult; 17124 SmallVector<PartialDiagnosticAt, 8> Notes; 17125 EvalResult.Diag = &Notes; 17126 17127 // Try to evaluate the expression, and produce diagnostics explaining why it's 17128 // not a constant expression as a side-effect. 17129 bool Folded = 17130 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 17131 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 17132 17133 if (!isa<ConstantExpr>(E)) 17134 E = ConstantExpr::Create(Context, E, EvalResult.Val); 17135 17136 // In C++11, we can rely on diagnostics being produced for any expression 17137 // which is not a constant expression. If no diagnostics were produced, then 17138 // this is a constant expression. 17139 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 17140 if (Result) 17141 *Result = EvalResult.Val.getInt(); 17142 return E; 17143 } 17144 17145 // If our only note is the usual "invalid subexpression" note, just point 17146 // the caret at its location rather than producing an essentially 17147 // redundant note. 17148 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 17149 diag::note_invalid_subexpr_in_const_expr) { 17150 DiagLoc = Notes[0].first; 17151 Notes.clear(); 17152 } 17153 17154 if (!Folded || !CanFold) { 17155 if (!Diagnoser.Suppress) { 17156 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 17157 for (const PartialDiagnosticAt &Note : Notes) 17158 Diag(Note.first, Note.second); 17159 } 17160 17161 return ExprError(); 17162 } 17163 17164 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 17165 for (const PartialDiagnosticAt &Note : Notes) 17166 Diag(Note.first, Note.second); 17167 17168 if (Result) 17169 *Result = EvalResult.Val.getInt(); 17170 return E; 17171 } 17172 17173 namespace { 17174 // Handle the case where we conclude a expression which we speculatively 17175 // considered to be unevaluated is actually evaluated. 17176 class TransformToPE : public TreeTransform<TransformToPE> { 17177 typedef TreeTransform<TransformToPE> BaseTransform; 17178 17179 public: 17180 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 17181 17182 // Make sure we redo semantic analysis 17183 bool AlwaysRebuild() { return true; } 17184 bool ReplacingOriginal() { return true; } 17185 17186 // We need to special-case DeclRefExprs referring to FieldDecls which 17187 // are not part of a member pointer formation; normal TreeTransforming 17188 // doesn't catch this case because of the way we represent them in the AST. 17189 // FIXME: This is a bit ugly; is it really the best way to handle this 17190 // case? 17191 // 17192 // Error on DeclRefExprs referring to FieldDecls. 17193 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 17194 if (isa<FieldDecl>(E->getDecl()) && 17195 !SemaRef.isUnevaluatedContext()) 17196 return SemaRef.Diag(E->getLocation(), 17197 diag::err_invalid_non_static_member_use) 17198 << E->getDecl() << E->getSourceRange(); 17199 17200 return BaseTransform::TransformDeclRefExpr(E); 17201 } 17202 17203 // Exception: filter out member pointer formation 17204 ExprResult TransformUnaryOperator(UnaryOperator *E) { 17205 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 17206 return E; 17207 17208 return BaseTransform::TransformUnaryOperator(E); 17209 } 17210 17211 // The body of a lambda-expression is in a separate expression evaluation 17212 // context so never needs to be transformed. 17213 // FIXME: Ideally we wouldn't transform the closure type either, and would 17214 // just recreate the capture expressions and lambda expression. 17215 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 17216 return SkipLambdaBody(E, Body); 17217 } 17218 }; 17219 } 17220 17221 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 17222 assert(isUnevaluatedContext() && 17223 "Should only transform unevaluated expressions"); 17224 ExprEvalContexts.back().Context = 17225 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 17226 if (isUnevaluatedContext()) 17227 return E; 17228 return TransformToPE(*this).TransformExpr(E); 17229 } 17230 17231 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) { 17232 assert(isUnevaluatedContext() && 17233 "Should only transform unevaluated expressions"); 17234 ExprEvalContexts.back().Context = 17235 ExprEvalContexts[ExprEvalContexts.size() - 2].Context; 17236 if (isUnevaluatedContext()) 17237 return TInfo; 17238 return TransformToPE(*this).TransformType(TInfo); 17239 } 17240 17241 void 17242 Sema::PushExpressionEvaluationContext( 17243 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 17244 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 17245 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 17246 LambdaContextDecl, ExprContext); 17247 17248 // Discarded statements and immediate contexts nested in other 17249 // discarded statements or immediate context are themselves 17250 // a discarded statement or an immediate context, respectively. 17251 ExprEvalContexts.back().InDiscardedStatement = 17252 ExprEvalContexts[ExprEvalContexts.size() - 2] 17253 .isDiscardedStatementContext(); 17254 ExprEvalContexts.back().InImmediateFunctionContext = 17255 ExprEvalContexts[ExprEvalContexts.size() - 2] 17256 .isImmediateFunctionContext(); 17257 17258 Cleanup.reset(); 17259 if (!MaybeODRUseExprs.empty()) 17260 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 17261 } 17262 17263 void 17264 Sema::PushExpressionEvaluationContext( 17265 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 17266 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 17267 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 17268 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 17269 } 17270 17271 namespace { 17272 17273 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 17274 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 17275 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 17276 if (E->getOpcode() == UO_Deref) 17277 return CheckPossibleDeref(S, E->getSubExpr()); 17278 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 17279 return CheckPossibleDeref(S, E->getBase()); 17280 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 17281 return CheckPossibleDeref(S, E->getBase()); 17282 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 17283 QualType Inner; 17284 QualType Ty = E->getType(); 17285 if (const auto *Ptr = Ty->getAs<PointerType>()) 17286 Inner = Ptr->getPointeeType(); 17287 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 17288 Inner = Arr->getElementType(); 17289 else 17290 return nullptr; 17291 17292 if (Inner->hasAttr(attr::NoDeref)) 17293 return E; 17294 } 17295 return nullptr; 17296 } 17297 17298 } // namespace 17299 17300 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 17301 for (const Expr *E : Rec.PossibleDerefs) { 17302 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 17303 if (DeclRef) { 17304 const ValueDecl *Decl = DeclRef->getDecl(); 17305 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 17306 << Decl->getName() << E->getSourceRange(); 17307 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 17308 } else { 17309 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 17310 << E->getSourceRange(); 17311 } 17312 } 17313 Rec.PossibleDerefs.clear(); 17314 } 17315 17316 /// Check whether E, which is either a discarded-value expression or an 17317 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 17318 /// and if so, remove it from the list of volatile-qualified assignments that 17319 /// we are going to warn are deprecated. 17320 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 17321 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 17322 return; 17323 17324 // Note: ignoring parens here is not justified by the standard rules, but 17325 // ignoring parentheses seems like a more reasonable approach, and this only 17326 // drives a deprecation warning so doesn't affect conformance. 17327 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 17328 if (BO->getOpcode() == BO_Assign) { 17329 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 17330 llvm::erase_value(LHSs, BO->getLHS()); 17331 } 17332 } 17333 } 17334 17335 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 17336 if (isUnevaluatedContext() || !E.isUsable() || !Decl || 17337 !Decl->isConsteval() || isConstantEvaluated() || 17338 RebuildingImmediateInvocation || isImmediateFunctionContext()) 17339 return E; 17340 17341 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 17342 /// It's OK if this fails; we'll also remove this in 17343 /// HandleImmediateInvocations, but catching it here allows us to avoid 17344 /// walking the AST looking for it in simple cases. 17345 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 17346 if (auto *DeclRef = 17347 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 17348 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 17349 17350 E = MaybeCreateExprWithCleanups(E); 17351 17352 ConstantExpr *Res = ConstantExpr::Create( 17353 getASTContext(), E.get(), 17354 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 17355 getASTContext()), 17356 /*IsImmediateInvocation*/ true); 17357 /// Value-dependent constant expressions should not be immediately 17358 /// evaluated until they are instantiated. 17359 if (!Res->isValueDependent()) 17360 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 17361 return Res; 17362 } 17363 17364 static void EvaluateAndDiagnoseImmediateInvocation( 17365 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 17366 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 17367 Expr::EvalResult Eval; 17368 Eval.Diag = &Notes; 17369 ConstantExpr *CE = Candidate.getPointer(); 17370 bool Result = CE->EvaluateAsConstantExpr( 17371 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 17372 if (!Result || !Notes.empty()) { 17373 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 17374 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 17375 InnerExpr = FunctionalCast->getSubExpr(); 17376 FunctionDecl *FD = nullptr; 17377 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 17378 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 17379 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 17380 FD = Call->getConstructor(); 17381 else 17382 llvm_unreachable("unhandled decl kind"); 17383 assert(FD->isConsteval()); 17384 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 17385 for (auto &Note : Notes) 17386 SemaRef.Diag(Note.first, Note.second); 17387 return; 17388 } 17389 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 17390 } 17391 17392 static void RemoveNestedImmediateInvocation( 17393 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 17394 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 17395 struct ComplexRemove : TreeTransform<ComplexRemove> { 17396 using Base = TreeTransform<ComplexRemove>; 17397 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 17398 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 17399 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 17400 CurrentII; 17401 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 17402 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 17403 SmallVector<Sema::ImmediateInvocationCandidate, 17404 4>::reverse_iterator Current) 17405 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 17406 void RemoveImmediateInvocation(ConstantExpr* E) { 17407 auto It = std::find_if(CurrentII, IISet.rend(), 17408 [E](Sema::ImmediateInvocationCandidate Elem) { 17409 return Elem.getPointer() == E; 17410 }); 17411 assert(It != IISet.rend() && 17412 "ConstantExpr marked IsImmediateInvocation should " 17413 "be present"); 17414 It->setInt(1); // Mark as deleted 17415 } 17416 ExprResult TransformConstantExpr(ConstantExpr *E) { 17417 if (!E->isImmediateInvocation()) 17418 return Base::TransformConstantExpr(E); 17419 RemoveImmediateInvocation(E); 17420 return Base::TransformExpr(E->getSubExpr()); 17421 } 17422 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 17423 /// we need to remove its DeclRefExpr from the DRSet. 17424 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 17425 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 17426 return Base::TransformCXXOperatorCallExpr(E); 17427 } 17428 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 17429 /// here. 17430 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 17431 if (!Init) 17432 return Init; 17433 /// ConstantExpr are the first layer of implicit node to be removed so if 17434 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 17435 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 17436 if (CE->isImmediateInvocation()) 17437 RemoveImmediateInvocation(CE); 17438 return Base::TransformInitializer(Init, NotCopyInit); 17439 } 17440 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 17441 DRSet.erase(E); 17442 return E; 17443 } 17444 bool AlwaysRebuild() { return false; } 17445 bool ReplacingOriginal() { return true; } 17446 bool AllowSkippingCXXConstructExpr() { 17447 bool Res = AllowSkippingFirstCXXConstructExpr; 17448 AllowSkippingFirstCXXConstructExpr = true; 17449 return Res; 17450 } 17451 bool AllowSkippingFirstCXXConstructExpr = true; 17452 } Transformer(SemaRef, Rec.ReferenceToConsteval, 17453 Rec.ImmediateInvocationCandidates, It); 17454 17455 /// CXXConstructExpr with a single argument are getting skipped by 17456 /// TreeTransform in some situtation because they could be implicit. This 17457 /// can only occur for the top-level CXXConstructExpr because it is used 17458 /// nowhere in the expression being transformed therefore will not be rebuilt. 17459 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 17460 /// skipping the first CXXConstructExpr. 17461 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 17462 Transformer.AllowSkippingFirstCXXConstructExpr = false; 17463 17464 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 17465 assert(Res.isUsable()); 17466 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 17467 It->getPointer()->setSubExpr(Res.get()); 17468 } 17469 17470 static void 17471 HandleImmediateInvocations(Sema &SemaRef, 17472 Sema::ExpressionEvaluationContextRecord &Rec) { 17473 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 17474 Rec.ReferenceToConsteval.size() == 0) || 17475 SemaRef.RebuildingImmediateInvocation) 17476 return; 17477 17478 /// When we have more then 1 ImmediateInvocationCandidates we need to check 17479 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 17480 /// need to remove ReferenceToConsteval in the immediate invocation. 17481 if (Rec.ImmediateInvocationCandidates.size() > 1) { 17482 17483 /// Prevent sema calls during the tree transform from adding pointers that 17484 /// are already in the sets. 17485 llvm::SaveAndRestore<bool> DisableIITracking( 17486 SemaRef.RebuildingImmediateInvocation, true); 17487 17488 /// Prevent diagnostic during tree transfrom as they are duplicates 17489 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 17490 17491 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 17492 It != Rec.ImmediateInvocationCandidates.rend(); It++) 17493 if (!It->getInt()) 17494 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 17495 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 17496 Rec.ReferenceToConsteval.size()) { 17497 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 17498 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 17499 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 17500 bool VisitDeclRefExpr(DeclRefExpr *E) { 17501 DRSet.erase(E); 17502 return DRSet.size(); 17503 } 17504 } Visitor(Rec.ReferenceToConsteval); 17505 Visitor.TraverseStmt( 17506 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 17507 } 17508 for (auto CE : Rec.ImmediateInvocationCandidates) 17509 if (!CE.getInt()) 17510 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 17511 for (auto DR : Rec.ReferenceToConsteval) { 17512 auto *FD = cast<FunctionDecl>(DR->getDecl()); 17513 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 17514 << FD; 17515 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 17516 } 17517 } 17518 17519 void Sema::PopExpressionEvaluationContext() { 17520 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 17521 unsigned NumTypos = Rec.NumTypos; 17522 17523 if (!Rec.Lambdas.empty()) { 17524 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 17525 if (!getLangOpts().CPlusPlus20 && 17526 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 17527 Rec.isUnevaluated() || 17528 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 17529 unsigned D; 17530 if (Rec.isUnevaluated()) { 17531 // C++11 [expr.prim.lambda]p2: 17532 // A lambda-expression shall not appear in an unevaluated operand 17533 // (Clause 5). 17534 D = diag::err_lambda_unevaluated_operand; 17535 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 17536 // C++1y [expr.const]p2: 17537 // A conditional-expression e is a core constant expression unless the 17538 // evaluation of e, following the rules of the abstract machine, would 17539 // evaluate [...] a lambda-expression. 17540 D = diag::err_lambda_in_constant_expression; 17541 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 17542 // C++17 [expr.prim.lamda]p2: 17543 // A lambda-expression shall not appear [...] in a template-argument. 17544 D = diag::err_lambda_in_invalid_context; 17545 } else 17546 llvm_unreachable("Couldn't infer lambda error message."); 17547 17548 for (const auto *L : Rec.Lambdas) 17549 Diag(L->getBeginLoc(), D); 17550 } 17551 } 17552 17553 WarnOnPendingNoDerefs(Rec); 17554 HandleImmediateInvocations(*this, Rec); 17555 17556 // Warn on any volatile-qualified simple-assignments that are not discarded- 17557 // value expressions nor unevaluated operands (those cases get removed from 17558 // this list by CheckUnusedVolatileAssignment). 17559 for (auto *BO : Rec.VolatileAssignmentLHSs) 17560 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 17561 << BO->getType(); 17562 17563 // When are coming out of an unevaluated context, clear out any 17564 // temporaries that we may have created as part of the evaluation of 17565 // the expression in that context: they aren't relevant because they 17566 // will never be constructed. 17567 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 17568 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 17569 ExprCleanupObjects.end()); 17570 Cleanup = Rec.ParentCleanup; 17571 CleanupVarDeclMarking(); 17572 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 17573 // Otherwise, merge the contexts together. 17574 } else { 17575 Cleanup.mergeFrom(Rec.ParentCleanup); 17576 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 17577 Rec.SavedMaybeODRUseExprs.end()); 17578 } 17579 17580 // Pop the current expression evaluation context off the stack. 17581 ExprEvalContexts.pop_back(); 17582 17583 // The global expression evaluation context record is never popped. 17584 ExprEvalContexts.back().NumTypos += NumTypos; 17585 } 17586 17587 void Sema::DiscardCleanupsInEvaluationContext() { 17588 ExprCleanupObjects.erase( 17589 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 17590 ExprCleanupObjects.end()); 17591 Cleanup.reset(); 17592 MaybeODRUseExprs.clear(); 17593 } 17594 17595 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 17596 ExprResult Result = CheckPlaceholderExpr(E); 17597 if (Result.isInvalid()) 17598 return ExprError(); 17599 E = Result.get(); 17600 if (!E->getType()->isVariablyModifiedType()) 17601 return E; 17602 return TransformToPotentiallyEvaluated(E); 17603 } 17604 17605 /// Are we in a context that is potentially constant evaluated per C++20 17606 /// [expr.const]p12? 17607 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 17608 /// C++2a [expr.const]p12: 17609 // An expression or conversion is potentially constant evaluated if it is 17610 switch (SemaRef.ExprEvalContexts.back().Context) { 17611 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17612 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 17613 17614 // -- a manifestly constant-evaluated expression, 17615 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17616 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17617 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17618 // -- a potentially-evaluated expression, 17619 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17620 // -- an immediate subexpression of a braced-init-list, 17621 17622 // -- [FIXME] an expression of the form & cast-expression that occurs 17623 // within a templated entity 17624 // -- a subexpression of one of the above that is not a subexpression of 17625 // a nested unevaluated operand. 17626 return true; 17627 17628 case Sema::ExpressionEvaluationContext::Unevaluated: 17629 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17630 // Expressions in this context are never evaluated. 17631 return false; 17632 } 17633 llvm_unreachable("Invalid context"); 17634 } 17635 17636 /// Return true if this function has a calling convention that requires mangling 17637 /// in the size of the parameter pack. 17638 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 17639 // These manglings don't do anything on non-Windows or non-x86 platforms, so 17640 // we don't need parameter type sizes. 17641 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 17642 if (!TT.isOSWindows() || !TT.isX86()) 17643 return false; 17644 17645 // If this is C++ and this isn't an extern "C" function, parameters do not 17646 // need to be complete. In this case, C++ mangling will apply, which doesn't 17647 // use the size of the parameters. 17648 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 17649 return false; 17650 17651 // Stdcall, fastcall, and vectorcall need this special treatment. 17652 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 17653 switch (CC) { 17654 case CC_X86StdCall: 17655 case CC_X86FastCall: 17656 case CC_X86VectorCall: 17657 return true; 17658 default: 17659 break; 17660 } 17661 return false; 17662 } 17663 17664 /// Require that all of the parameter types of function be complete. Normally, 17665 /// parameter types are only required to be complete when a function is called 17666 /// or defined, but to mangle functions with certain calling conventions, the 17667 /// mangler needs to know the size of the parameter list. In this situation, 17668 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 17669 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 17670 /// result in a linker error. Clang doesn't implement this behavior, and instead 17671 /// attempts to error at compile time. 17672 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 17673 SourceLocation Loc) { 17674 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 17675 FunctionDecl *FD; 17676 ParmVarDecl *Param; 17677 17678 public: 17679 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 17680 : FD(FD), Param(Param) {} 17681 17682 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17683 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 17684 StringRef CCName; 17685 switch (CC) { 17686 case CC_X86StdCall: 17687 CCName = "stdcall"; 17688 break; 17689 case CC_X86FastCall: 17690 CCName = "fastcall"; 17691 break; 17692 case CC_X86VectorCall: 17693 CCName = "vectorcall"; 17694 break; 17695 default: 17696 llvm_unreachable("CC does not need mangling"); 17697 } 17698 17699 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 17700 << Param->getDeclName() << FD->getDeclName() << CCName; 17701 } 17702 }; 17703 17704 for (ParmVarDecl *Param : FD->parameters()) { 17705 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 17706 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 17707 } 17708 } 17709 17710 namespace { 17711 enum class OdrUseContext { 17712 /// Declarations in this context are not odr-used. 17713 None, 17714 /// Declarations in this context are formally odr-used, but this is a 17715 /// dependent context. 17716 Dependent, 17717 /// Declarations in this context are odr-used but not actually used (yet). 17718 FormallyOdrUsed, 17719 /// Declarations in this context are used. 17720 Used 17721 }; 17722 } 17723 17724 /// Are we within a context in which references to resolved functions or to 17725 /// variables result in odr-use? 17726 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 17727 OdrUseContext Result; 17728 17729 switch (SemaRef.ExprEvalContexts.back().Context) { 17730 case Sema::ExpressionEvaluationContext::Unevaluated: 17731 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17732 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17733 return OdrUseContext::None; 17734 17735 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17736 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 17737 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17738 Result = OdrUseContext::Used; 17739 break; 17740 17741 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17742 Result = OdrUseContext::FormallyOdrUsed; 17743 break; 17744 17745 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17746 // A default argument formally results in odr-use, but doesn't actually 17747 // result in a use in any real sense until it itself is used. 17748 Result = OdrUseContext::FormallyOdrUsed; 17749 break; 17750 } 17751 17752 if (SemaRef.CurContext->isDependentContext()) 17753 return OdrUseContext::Dependent; 17754 17755 return Result; 17756 } 17757 17758 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 17759 if (!Func->isConstexpr()) 17760 return false; 17761 17762 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 17763 return true; 17764 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 17765 return CCD && CCD->getInheritedConstructor(); 17766 } 17767 17768 /// Mark a function referenced, and check whether it is odr-used 17769 /// (C++ [basic.def.odr]p2, C99 6.9p3) 17770 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 17771 bool MightBeOdrUse) { 17772 assert(Func && "No function?"); 17773 17774 Func->setReferenced(); 17775 17776 // Recursive functions aren't really used until they're used from some other 17777 // context. 17778 bool IsRecursiveCall = CurContext == Func; 17779 17780 // C++11 [basic.def.odr]p3: 17781 // A function whose name appears as a potentially-evaluated expression is 17782 // odr-used if it is the unique lookup result or the selected member of a 17783 // set of overloaded functions [...]. 17784 // 17785 // We (incorrectly) mark overload resolution as an unevaluated context, so we 17786 // can just check that here. 17787 OdrUseContext OdrUse = 17788 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 17789 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 17790 OdrUse = OdrUseContext::FormallyOdrUsed; 17791 17792 // Trivial default constructors and destructors are never actually used. 17793 // FIXME: What about other special members? 17794 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 17795 OdrUse == OdrUseContext::Used) { 17796 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 17797 if (Constructor->isDefaultConstructor()) 17798 OdrUse = OdrUseContext::FormallyOdrUsed; 17799 if (isa<CXXDestructorDecl>(Func)) 17800 OdrUse = OdrUseContext::FormallyOdrUsed; 17801 } 17802 17803 // C++20 [expr.const]p12: 17804 // A function [...] is needed for constant evaluation if it is [...] a 17805 // constexpr function that is named by an expression that is potentially 17806 // constant evaluated 17807 bool NeededForConstantEvaluation = 17808 isPotentiallyConstantEvaluatedContext(*this) && 17809 isImplicitlyDefinableConstexprFunction(Func); 17810 17811 // Determine whether we require a function definition to exist, per 17812 // C++11 [temp.inst]p3: 17813 // Unless a function template specialization has been explicitly 17814 // instantiated or explicitly specialized, the function template 17815 // specialization is implicitly instantiated when the specialization is 17816 // referenced in a context that requires a function definition to exist. 17817 // C++20 [temp.inst]p7: 17818 // The existence of a definition of a [...] function is considered to 17819 // affect the semantics of the program if the [...] function is needed for 17820 // constant evaluation by an expression 17821 // C++20 [basic.def.odr]p10: 17822 // Every program shall contain exactly one definition of every non-inline 17823 // function or variable that is odr-used in that program outside of a 17824 // discarded statement 17825 // C++20 [special]p1: 17826 // The implementation will implicitly define [defaulted special members] 17827 // if they are odr-used or needed for constant evaluation. 17828 // 17829 // Note that we skip the implicit instantiation of templates that are only 17830 // used in unused default arguments or by recursive calls to themselves. 17831 // This is formally non-conforming, but seems reasonable in practice. 17832 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 17833 NeededForConstantEvaluation); 17834 17835 // C++14 [temp.expl.spec]p6: 17836 // If a template [...] is explicitly specialized then that specialization 17837 // shall be declared before the first use of that specialization that would 17838 // cause an implicit instantiation to take place, in every translation unit 17839 // in which such a use occurs 17840 if (NeedDefinition && 17841 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 17842 Func->getMemberSpecializationInfo())) 17843 checkSpecializationVisibility(Loc, Func); 17844 17845 if (getLangOpts().CUDA) 17846 CheckCUDACall(Loc, Func); 17847 17848 if (getLangOpts().SYCLIsDevice) 17849 checkSYCLDeviceFunction(Loc, Func); 17850 17851 // If we need a definition, try to create one. 17852 if (NeedDefinition && !Func->getBody()) { 17853 runWithSufficientStackSpace(Loc, [&] { 17854 if (CXXConstructorDecl *Constructor = 17855 dyn_cast<CXXConstructorDecl>(Func)) { 17856 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 17857 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 17858 if (Constructor->isDefaultConstructor()) { 17859 if (Constructor->isTrivial() && 17860 !Constructor->hasAttr<DLLExportAttr>()) 17861 return; 17862 DefineImplicitDefaultConstructor(Loc, Constructor); 17863 } else if (Constructor->isCopyConstructor()) { 17864 DefineImplicitCopyConstructor(Loc, Constructor); 17865 } else if (Constructor->isMoveConstructor()) { 17866 DefineImplicitMoveConstructor(Loc, Constructor); 17867 } 17868 } else if (Constructor->getInheritedConstructor()) { 17869 DefineInheritingConstructor(Loc, Constructor); 17870 } 17871 } else if (CXXDestructorDecl *Destructor = 17872 dyn_cast<CXXDestructorDecl>(Func)) { 17873 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17874 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17875 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17876 return; 17877 DefineImplicitDestructor(Loc, Destructor); 17878 } 17879 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17880 MarkVTableUsed(Loc, Destructor->getParent()); 17881 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17882 if (MethodDecl->isOverloadedOperator() && 17883 MethodDecl->getOverloadedOperator() == OO_Equal) { 17884 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17885 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17886 if (MethodDecl->isCopyAssignmentOperator()) 17887 DefineImplicitCopyAssignment(Loc, MethodDecl); 17888 else if (MethodDecl->isMoveAssignmentOperator()) 17889 DefineImplicitMoveAssignment(Loc, MethodDecl); 17890 } 17891 } else if (isa<CXXConversionDecl>(MethodDecl) && 17892 MethodDecl->getParent()->isLambda()) { 17893 CXXConversionDecl *Conversion = 17894 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17895 if (Conversion->isLambdaToBlockPointerConversion()) 17896 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17897 else 17898 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17899 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17900 MarkVTableUsed(Loc, MethodDecl->getParent()); 17901 } 17902 17903 if (Func->isDefaulted() && !Func->isDeleted()) { 17904 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17905 if (DCK != DefaultedComparisonKind::None) 17906 DefineDefaultedComparison(Loc, Func, DCK); 17907 } 17908 17909 // Implicit instantiation of function templates and member functions of 17910 // class templates. 17911 if (Func->isImplicitlyInstantiable()) { 17912 TemplateSpecializationKind TSK = 17913 Func->getTemplateSpecializationKindForInstantiation(); 17914 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17915 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17916 if (FirstInstantiation) { 17917 PointOfInstantiation = Loc; 17918 if (auto *MSI = Func->getMemberSpecializationInfo()) 17919 MSI->setPointOfInstantiation(Loc); 17920 // FIXME: Notify listener. 17921 else 17922 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17923 } else if (TSK != TSK_ImplicitInstantiation) { 17924 // Use the point of use as the point of instantiation, instead of the 17925 // point of explicit instantiation (which we track as the actual point 17926 // of instantiation). This gives better backtraces in diagnostics. 17927 PointOfInstantiation = Loc; 17928 } 17929 17930 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17931 Func->isConstexpr()) { 17932 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17933 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17934 CodeSynthesisContexts.size()) 17935 PendingLocalImplicitInstantiations.push_back( 17936 std::make_pair(Func, PointOfInstantiation)); 17937 else if (Func->isConstexpr()) 17938 // Do not defer instantiations of constexpr functions, to avoid the 17939 // expression evaluator needing to call back into Sema if it sees a 17940 // call to such a function. 17941 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17942 else { 17943 Func->setInstantiationIsPending(true); 17944 PendingInstantiations.push_back( 17945 std::make_pair(Func, PointOfInstantiation)); 17946 // Notify the consumer that a function was implicitly instantiated. 17947 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17948 } 17949 } 17950 } else { 17951 // Walk redefinitions, as some of them may be instantiable. 17952 for (auto i : Func->redecls()) { 17953 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17954 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17955 } 17956 } 17957 }); 17958 } 17959 17960 // C++14 [except.spec]p17: 17961 // An exception-specification is considered to be needed when: 17962 // - the function is odr-used or, if it appears in an unevaluated operand, 17963 // would be odr-used if the expression were potentially-evaluated; 17964 // 17965 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17966 // function is a pure virtual function we're calling, and in that case the 17967 // function was selected by overload resolution and we need to resolve its 17968 // exception specification for a different reason. 17969 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17970 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17971 ResolveExceptionSpec(Loc, FPT); 17972 17973 // If this is the first "real" use, act on that. 17974 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17975 // Keep track of used but undefined functions. 17976 if (!Func->isDefined()) { 17977 if (mightHaveNonExternalLinkage(Func)) 17978 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17979 else if (Func->getMostRecentDecl()->isInlined() && 17980 !LangOpts.GNUInline && 17981 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17982 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17983 else if (isExternalWithNoLinkageType(Func)) 17984 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17985 } 17986 17987 // Some x86 Windows calling conventions mangle the size of the parameter 17988 // pack into the name. Computing the size of the parameters requires the 17989 // parameter types to be complete. Check that now. 17990 if (funcHasParameterSizeMangling(*this, Func)) 17991 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17992 17993 // In the MS C++ ABI, the compiler emits destructor variants where they are 17994 // used. If the destructor is used here but defined elsewhere, mark the 17995 // virtual base destructors referenced. If those virtual base destructors 17996 // are inline, this will ensure they are defined when emitting the complete 17997 // destructor variant. This checking may be redundant if the destructor is 17998 // provided later in this TU. 17999 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 18000 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 18001 CXXRecordDecl *Parent = Dtor->getParent(); 18002 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 18003 CheckCompleteDestructorVariant(Loc, Dtor); 18004 } 18005 } 18006 18007 Func->markUsed(Context); 18008 } 18009 } 18010 18011 /// Directly mark a variable odr-used. Given a choice, prefer to use 18012 /// MarkVariableReferenced since it does additional checks and then 18013 /// calls MarkVarDeclODRUsed. 18014 /// If the variable must be captured: 18015 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 18016 /// - else capture it in the DeclContext that maps to the 18017 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 18018 static void 18019 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 18020 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 18021 // Keep track of used but undefined variables. 18022 // FIXME: We shouldn't suppress this warning for static data members. 18023 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 18024 (!Var->isExternallyVisible() || Var->isInline() || 18025 SemaRef.isExternalWithNoLinkageType(Var)) && 18026 !(Var->isStaticDataMember() && Var->hasInit())) { 18027 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 18028 if (old.isInvalid()) 18029 old = Loc; 18030 } 18031 QualType CaptureType, DeclRefType; 18032 if (SemaRef.LangOpts.OpenMP) 18033 SemaRef.tryCaptureOpenMPLambdas(Var); 18034 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 18035 /*EllipsisLoc*/ SourceLocation(), 18036 /*BuildAndDiagnose*/ true, 18037 CaptureType, DeclRefType, 18038 FunctionScopeIndexToStopAt); 18039 18040 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) { 18041 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 18042 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 18043 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 18044 if (VarTarget == Sema::CVT_Host && 18045 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 18046 UserTarget == Sema::CFT_Global)) { 18047 // Diagnose ODR-use of host global variables in device functions. 18048 // Reference of device global variables in host functions is allowed 18049 // through shadow variables therefore it is not diagnosed. 18050 if (SemaRef.LangOpts.CUDAIsDevice) { 18051 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 18052 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 18053 SemaRef.targetDiag(Var->getLocation(), 18054 Var->getType().isConstQualified() 18055 ? diag::note_cuda_const_var_unpromoted 18056 : diag::note_cuda_host_var); 18057 } 18058 } else if (VarTarget == Sema::CVT_Device && 18059 (UserTarget == Sema::CFT_Host || 18060 UserTarget == Sema::CFT_HostDevice)) { 18061 // Record a CUDA/HIP device side variable if it is ODR-used 18062 // by host code. This is done conservatively, when the variable is 18063 // referenced in any of the following contexts: 18064 // - a non-function context 18065 // - a host function 18066 // - a host device function 18067 // This makes the ODR-use of the device side variable by host code to 18068 // be visible in the device compilation for the compiler to be able to 18069 // emit template variables instantiated by host code only and to 18070 // externalize the static device side variable ODR-used by host code. 18071 if (!Var->hasExternalStorage()) 18072 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 18073 else if (SemaRef.LangOpts.GPURelocatableDeviceCode) 18074 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var); 18075 } 18076 } 18077 18078 Var->markUsed(SemaRef.Context); 18079 } 18080 18081 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 18082 SourceLocation Loc, 18083 unsigned CapturingScopeIndex) { 18084 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 18085 } 18086 18087 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 18088 ValueDecl *var) { 18089 DeclContext *VarDC = var->getDeclContext(); 18090 18091 // If the parameter still belongs to the translation unit, then 18092 // we're actually just using one parameter in the declaration of 18093 // the next. 18094 if (isa<ParmVarDecl>(var) && 18095 isa<TranslationUnitDecl>(VarDC)) 18096 return; 18097 18098 // For C code, don't diagnose about capture if we're not actually in code 18099 // right now; it's impossible to write a non-constant expression outside of 18100 // function context, so we'll get other (more useful) diagnostics later. 18101 // 18102 // For C++, things get a bit more nasty... it would be nice to suppress this 18103 // diagnostic for certain cases like using a local variable in an array bound 18104 // for a member of a local class, but the correct predicate is not obvious. 18105 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 18106 return; 18107 18108 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 18109 unsigned ContextKind = 3; // unknown 18110 if (isa<CXXMethodDecl>(VarDC) && 18111 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 18112 ContextKind = 2; 18113 } else if (isa<FunctionDecl>(VarDC)) { 18114 ContextKind = 0; 18115 } else if (isa<BlockDecl>(VarDC)) { 18116 ContextKind = 1; 18117 } 18118 18119 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 18120 << var << ValueKind << ContextKind << VarDC; 18121 S.Diag(var->getLocation(), diag::note_entity_declared_at) 18122 << var; 18123 18124 // FIXME: Add additional diagnostic info about class etc. which prevents 18125 // capture. 18126 } 18127 18128 18129 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 18130 bool &SubCapturesAreNested, 18131 QualType &CaptureType, 18132 QualType &DeclRefType) { 18133 // Check whether we've already captured it. 18134 if (CSI->CaptureMap.count(Var)) { 18135 // If we found a capture, any subcaptures are nested. 18136 SubCapturesAreNested = true; 18137 18138 // Retrieve the capture type for this variable. 18139 CaptureType = CSI->getCapture(Var).getCaptureType(); 18140 18141 // Compute the type of an expression that refers to this variable. 18142 DeclRefType = CaptureType.getNonReferenceType(); 18143 18144 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 18145 // are mutable in the sense that user can change their value - they are 18146 // private instances of the captured declarations. 18147 const Capture &Cap = CSI->getCapture(Var); 18148 if (Cap.isCopyCapture() && 18149 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 18150 !(isa<CapturedRegionScopeInfo>(CSI) && 18151 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 18152 DeclRefType.addConst(); 18153 return true; 18154 } 18155 return false; 18156 } 18157 18158 // Only block literals, captured statements, and lambda expressions can 18159 // capture; other scopes don't work. 18160 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 18161 SourceLocation Loc, 18162 const bool Diagnose, Sema &S) { 18163 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 18164 return getLambdaAwareParentOfDeclContext(DC); 18165 else if (Var->hasLocalStorage()) { 18166 if (Diagnose) 18167 diagnoseUncapturableValueReference(S, Loc, Var); 18168 } 18169 return nullptr; 18170 } 18171 18172 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18173 // certain types of variables (unnamed, variably modified types etc.) 18174 // so check for eligibility. 18175 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 18176 SourceLocation Loc, 18177 const bool Diagnose, Sema &S) { 18178 18179 bool IsBlock = isa<BlockScopeInfo>(CSI); 18180 bool IsLambda = isa<LambdaScopeInfo>(CSI); 18181 18182 // Lambdas are not allowed to capture unnamed variables 18183 // (e.g. anonymous unions). 18184 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 18185 // assuming that's the intent. 18186 if (IsLambda && !Var->getDeclName()) { 18187 if (Diagnose) { 18188 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 18189 S.Diag(Var->getLocation(), diag::note_declared_at); 18190 } 18191 return false; 18192 } 18193 18194 // Prohibit variably-modified types in blocks; they're difficult to deal with. 18195 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 18196 if (Diagnose) { 18197 S.Diag(Loc, diag::err_ref_vm_type); 18198 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18199 } 18200 return false; 18201 } 18202 // Prohibit structs with flexible array members too. 18203 // We cannot capture what is in the tail end of the struct. 18204 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 18205 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 18206 if (Diagnose) { 18207 if (IsBlock) 18208 S.Diag(Loc, diag::err_ref_flexarray_type); 18209 else 18210 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 18211 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18212 } 18213 return false; 18214 } 18215 } 18216 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 18217 // Lambdas and captured statements are not allowed to capture __block 18218 // variables; they don't support the expected semantics. 18219 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 18220 if (Diagnose) { 18221 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 18222 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18223 } 18224 return false; 18225 } 18226 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 18227 if (S.getLangOpts().OpenCL && IsBlock && 18228 Var->getType()->isBlockPointerType()) { 18229 if (Diagnose) 18230 S.Diag(Loc, diag::err_opencl_block_ref_block); 18231 return false; 18232 } 18233 18234 return true; 18235 } 18236 18237 // Returns true if the capture by block was successful. 18238 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 18239 SourceLocation Loc, 18240 const bool BuildAndDiagnose, 18241 QualType &CaptureType, 18242 QualType &DeclRefType, 18243 const bool Nested, 18244 Sema &S, bool Invalid) { 18245 bool ByRef = false; 18246 18247 // Blocks are not allowed to capture arrays, excepting OpenCL. 18248 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 18249 // (decayed to pointers). 18250 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 18251 if (BuildAndDiagnose) { 18252 S.Diag(Loc, diag::err_ref_array_type); 18253 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18254 Invalid = true; 18255 } else { 18256 return false; 18257 } 18258 } 18259 18260 // Forbid the block-capture of autoreleasing variables. 18261 if (!Invalid && 18262 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 18263 if (BuildAndDiagnose) { 18264 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 18265 << /*block*/ 0; 18266 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18267 Invalid = true; 18268 } else { 18269 return false; 18270 } 18271 } 18272 18273 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 18274 if (const auto *PT = CaptureType->getAs<PointerType>()) { 18275 QualType PointeeTy = PT->getPointeeType(); 18276 18277 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 18278 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 18279 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 18280 if (BuildAndDiagnose) { 18281 SourceLocation VarLoc = Var->getLocation(); 18282 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 18283 S.Diag(VarLoc, diag::note_declare_parameter_strong); 18284 } 18285 } 18286 } 18287 18288 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 18289 if (HasBlocksAttr || CaptureType->isReferenceType() || 18290 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 18291 // Block capture by reference does not change the capture or 18292 // declaration reference types. 18293 ByRef = true; 18294 } else { 18295 // Block capture by copy introduces 'const'. 18296 CaptureType = CaptureType.getNonReferenceType().withConst(); 18297 DeclRefType = CaptureType; 18298 } 18299 18300 // Actually capture the variable. 18301 if (BuildAndDiagnose) 18302 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 18303 CaptureType, Invalid); 18304 18305 return !Invalid; 18306 } 18307 18308 18309 /// Capture the given variable in the captured region. 18310 static bool captureInCapturedRegion( 18311 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 18312 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 18313 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 18314 bool IsTopScope, Sema &S, bool Invalid) { 18315 // By default, capture variables by reference. 18316 bool ByRef = true; 18317 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 18318 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 18319 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 18320 // Using an LValue reference type is consistent with Lambdas (see below). 18321 if (S.isOpenMPCapturedDecl(Var)) { 18322 bool HasConst = DeclRefType.isConstQualified(); 18323 DeclRefType = DeclRefType.getUnqualifiedType(); 18324 // Don't lose diagnostics about assignments to const. 18325 if (HasConst) 18326 DeclRefType.addConst(); 18327 } 18328 // Do not capture firstprivates in tasks. 18329 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 18330 OMPC_unknown) 18331 return true; 18332 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 18333 RSI->OpenMPCaptureLevel); 18334 } 18335 18336 if (ByRef) 18337 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 18338 else 18339 CaptureType = DeclRefType; 18340 18341 // Actually capture the variable. 18342 if (BuildAndDiagnose) 18343 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 18344 Loc, SourceLocation(), CaptureType, Invalid); 18345 18346 return !Invalid; 18347 } 18348 18349 /// Capture the given variable in the lambda. 18350 static bool captureInLambda(LambdaScopeInfo *LSI, 18351 VarDecl *Var, 18352 SourceLocation Loc, 18353 const bool BuildAndDiagnose, 18354 QualType &CaptureType, 18355 QualType &DeclRefType, 18356 const bool RefersToCapturedVariable, 18357 const Sema::TryCaptureKind Kind, 18358 SourceLocation EllipsisLoc, 18359 const bool IsTopScope, 18360 Sema &S, bool Invalid) { 18361 // Determine whether we are capturing by reference or by value. 18362 bool ByRef = false; 18363 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 18364 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 18365 } else { 18366 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 18367 } 18368 18369 // Compute the type of the field that will capture this variable. 18370 if (ByRef) { 18371 // C++11 [expr.prim.lambda]p15: 18372 // An entity is captured by reference if it is implicitly or 18373 // explicitly captured but not captured by copy. It is 18374 // unspecified whether additional unnamed non-static data 18375 // members are declared in the closure type for entities 18376 // captured by reference. 18377 // 18378 // FIXME: It is not clear whether we want to build an lvalue reference 18379 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 18380 // to do the former, while EDG does the latter. Core issue 1249 will 18381 // clarify, but for now we follow GCC because it's a more permissive and 18382 // easily defensible position. 18383 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 18384 } else { 18385 // C++11 [expr.prim.lambda]p14: 18386 // For each entity captured by copy, an unnamed non-static 18387 // data member is declared in the closure type. The 18388 // declaration order of these members is unspecified. The type 18389 // of such a data member is the type of the corresponding 18390 // captured entity if the entity is not a reference to an 18391 // object, or the referenced type otherwise. [Note: If the 18392 // captured entity is a reference to a function, the 18393 // corresponding data member is also a reference to a 18394 // function. - end note ] 18395 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 18396 if (!RefType->getPointeeType()->isFunctionType()) 18397 CaptureType = RefType->getPointeeType(); 18398 } 18399 18400 // Forbid the lambda copy-capture of autoreleasing variables. 18401 if (!Invalid && 18402 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 18403 if (BuildAndDiagnose) { 18404 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 18405 S.Diag(Var->getLocation(), diag::note_previous_decl) 18406 << Var->getDeclName(); 18407 Invalid = true; 18408 } else { 18409 return false; 18410 } 18411 } 18412 18413 // Make sure that by-copy captures are of a complete and non-abstract type. 18414 if (!Invalid && BuildAndDiagnose) { 18415 if (!CaptureType->isDependentType() && 18416 S.RequireCompleteSizedType( 18417 Loc, CaptureType, 18418 diag::err_capture_of_incomplete_or_sizeless_type, 18419 Var->getDeclName())) 18420 Invalid = true; 18421 else if (S.RequireNonAbstractType(Loc, CaptureType, 18422 diag::err_capture_of_abstract_type)) 18423 Invalid = true; 18424 } 18425 } 18426 18427 // Compute the type of a reference to this captured variable. 18428 if (ByRef) 18429 DeclRefType = CaptureType.getNonReferenceType(); 18430 else { 18431 // C++ [expr.prim.lambda]p5: 18432 // The closure type for a lambda-expression has a public inline 18433 // function call operator [...]. This function call operator is 18434 // declared const (9.3.1) if and only if the lambda-expression's 18435 // parameter-declaration-clause is not followed by mutable. 18436 DeclRefType = CaptureType.getNonReferenceType(); 18437 if (!LSI->Mutable && !CaptureType->isReferenceType()) 18438 DeclRefType.addConst(); 18439 } 18440 18441 // Add the capture. 18442 if (BuildAndDiagnose) 18443 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 18444 Loc, EllipsisLoc, CaptureType, Invalid); 18445 18446 return !Invalid; 18447 } 18448 18449 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 18450 // Offer a Copy fix even if the type is dependent. 18451 if (Var->getType()->isDependentType()) 18452 return true; 18453 QualType T = Var->getType().getNonReferenceType(); 18454 if (T.isTriviallyCopyableType(Context)) 18455 return true; 18456 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 18457 18458 if (!(RD = RD->getDefinition())) 18459 return false; 18460 if (RD->hasSimpleCopyConstructor()) 18461 return true; 18462 if (RD->hasUserDeclaredCopyConstructor()) 18463 for (CXXConstructorDecl *Ctor : RD->ctors()) 18464 if (Ctor->isCopyConstructor()) 18465 return !Ctor->isDeleted(); 18466 } 18467 return false; 18468 } 18469 18470 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 18471 /// default capture. Fixes may be omitted if they aren't allowed by the 18472 /// standard, for example we can't emit a default copy capture fix-it if we 18473 /// already explicitly copy capture capture another variable. 18474 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 18475 VarDecl *Var) { 18476 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 18477 // Don't offer Capture by copy of default capture by copy fixes if Var is 18478 // known not to be copy constructible. 18479 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 18480 18481 SmallString<32> FixBuffer; 18482 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 18483 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 18484 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 18485 if (ShouldOfferCopyFix) { 18486 // Offer fixes to insert an explicit capture for the variable. 18487 // [] -> [VarName] 18488 // [OtherCapture] -> [OtherCapture, VarName] 18489 FixBuffer.assign({Separator, Var->getName()}); 18490 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 18491 << Var << /*value*/ 0 18492 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 18493 } 18494 // As above but capture by reference. 18495 FixBuffer.assign({Separator, "&", Var->getName()}); 18496 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 18497 << Var << /*reference*/ 1 18498 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 18499 } 18500 18501 // Only try to offer default capture if there are no captures excluding this 18502 // and init captures. 18503 // [this]: OK. 18504 // [X = Y]: OK. 18505 // [&A, &B]: Don't offer. 18506 // [A, B]: Don't offer. 18507 if (llvm::any_of(LSI->Captures, [](Capture &C) { 18508 return !C.isThisCapture() && !C.isInitCapture(); 18509 })) 18510 return; 18511 18512 // The default capture specifiers, '=' or '&', must appear first in the 18513 // capture body. 18514 SourceLocation DefaultInsertLoc = 18515 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 18516 18517 if (ShouldOfferCopyFix) { 18518 bool CanDefaultCopyCapture = true; 18519 // [=, *this] OK since c++17 18520 // [=, this] OK since c++20 18521 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 18522 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 18523 ? LSI->getCXXThisCapture().isCopyCapture() 18524 : false; 18525 // We can't use default capture by copy if any captures already specified 18526 // capture by copy. 18527 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 18528 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 18529 })) { 18530 FixBuffer.assign({"=", Separator}); 18531 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 18532 << /*value*/ 0 18533 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 18534 } 18535 } 18536 18537 // We can't use default capture by reference if any captures already specified 18538 // capture by reference. 18539 if (llvm::none_of(LSI->Captures, [](Capture &C) { 18540 return !C.isInitCapture() && C.isReferenceCapture() && 18541 !C.isThisCapture(); 18542 })) { 18543 FixBuffer.assign({"&", Separator}); 18544 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 18545 << /*reference*/ 1 18546 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 18547 } 18548 } 18549 18550 bool Sema::tryCaptureVariable( 18551 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 18552 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 18553 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 18554 // An init-capture is notionally from the context surrounding its 18555 // declaration, but its parent DC is the lambda class. 18556 DeclContext *VarDC = Var->getDeclContext(); 18557 if (Var->isInitCapture()) 18558 VarDC = VarDC->getParent(); 18559 18560 DeclContext *DC = CurContext; 18561 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 18562 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 18563 // We need to sync up the Declaration Context with the 18564 // FunctionScopeIndexToStopAt 18565 if (FunctionScopeIndexToStopAt) { 18566 unsigned FSIndex = FunctionScopes.size() - 1; 18567 while (FSIndex != MaxFunctionScopesIndex) { 18568 DC = getLambdaAwareParentOfDeclContext(DC); 18569 --FSIndex; 18570 } 18571 } 18572 18573 18574 // If the variable is declared in the current context, there is no need to 18575 // capture it. 18576 if (VarDC == DC) return true; 18577 18578 // Capture global variables if it is required to use private copy of this 18579 // variable. 18580 bool IsGlobal = !Var->hasLocalStorage(); 18581 if (IsGlobal && 18582 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 18583 MaxFunctionScopesIndex))) 18584 return true; 18585 Var = Var->getCanonicalDecl(); 18586 18587 // Walk up the stack to determine whether we can capture the variable, 18588 // performing the "simple" checks that don't depend on type. We stop when 18589 // we've either hit the declared scope of the variable or find an existing 18590 // capture of that variable. We start from the innermost capturing-entity 18591 // (the DC) and ensure that all intervening capturing-entities 18592 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 18593 // declcontext can either capture the variable or have already captured 18594 // the variable. 18595 CaptureType = Var->getType(); 18596 DeclRefType = CaptureType.getNonReferenceType(); 18597 bool Nested = false; 18598 bool Explicit = (Kind != TryCapture_Implicit); 18599 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 18600 do { 18601 // Only block literals, captured statements, and lambda expressions can 18602 // capture; other scopes don't work. 18603 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 18604 ExprLoc, 18605 BuildAndDiagnose, 18606 *this); 18607 // We need to check for the parent *first* because, if we *have* 18608 // private-captured a global variable, we need to recursively capture it in 18609 // intermediate blocks, lambdas, etc. 18610 if (!ParentDC) { 18611 if (IsGlobal) { 18612 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 18613 break; 18614 } 18615 return true; 18616 } 18617 18618 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 18619 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 18620 18621 18622 // Check whether we've already captured it. 18623 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 18624 DeclRefType)) { 18625 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 18626 break; 18627 } 18628 // If we are instantiating a generic lambda call operator body, 18629 // we do not want to capture new variables. What was captured 18630 // during either a lambdas transformation or initial parsing 18631 // should be used. 18632 if (isGenericLambdaCallOperatorSpecialization(DC)) { 18633 if (BuildAndDiagnose) { 18634 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18635 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 18636 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18637 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18638 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18639 buildLambdaCaptureFixit(*this, LSI, Var); 18640 } else 18641 diagnoseUncapturableValueReference(*this, ExprLoc, Var); 18642 } 18643 return true; 18644 } 18645 18646 // Try to capture variable-length arrays types. 18647 if (Var->getType()->isVariablyModifiedType()) { 18648 // We're going to walk down into the type and look for VLA 18649 // expressions. 18650 QualType QTy = Var->getType(); 18651 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 18652 QTy = PVD->getOriginalType(); 18653 captureVariablyModifiedType(Context, QTy, CSI); 18654 } 18655 18656 if (getLangOpts().OpenMP) { 18657 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18658 // OpenMP private variables should not be captured in outer scope, so 18659 // just break here. Similarly, global variables that are captured in a 18660 // target region should not be captured outside the scope of the region. 18661 if (RSI->CapRegionKind == CR_OpenMP) { 18662 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 18663 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 18664 // If the variable is private (i.e. not captured) and has variably 18665 // modified type, we still need to capture the type for correct 18666 // codegen in all regions, associated with the construct. Currently, 18667 // it is captured in the innermost captured region only. 18668 if (IsOpenMPPrivateDecl != OMPC_unknown && 18669 Var->getType()->isVariablyModifiedType()) { 18670 QualType QTy = Var->getType(); 18671 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 18672 QTy = PVD->getOriginalType(); 18673 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 18674 I < E; ++I) { 18675 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 18676 FunctionScopes[FunctionScopesIndex - I]); 18677 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 18678 "Wrong number of captured regions associated with the " 18679 "OpenMP construct."); 18680 captureVariablyModifiedType(Context, QTy, OuterRSI); 18681 } 18682 } 18683 bool IsTargetCap = 18684 IsOpenMPPrivateDecl != OMPC_private && 18685 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 18686 RSI->OpenMPCaptureLevel); 18687 // Do not capture global if it is not privatized in outer regions. 18688 bool IsGlobalCap = 18689 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 18690 RSI->OpenMPCaptureLevel); 18691 18692 // When we detect target captures we are looking from inside the 18693 // target region, therefore we need to propagate the capture from the 18694 // enclosing region. Therefore, the capture is not initially nested. 18695 if (IsTargetCap) 18696 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 18697 18698 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 18699 (IsGlobal && !IsGlobalCap)) { 18700 Nested = !IsTargetCap; 18701 bool HasConst = DeclRefType.isConstQualified(); 18702 DeclRefType = DeclRefType.getUnqualifiedType(); 18703 // Don't lose diagnostics about assignments to const. 18704 if (HasConst) 18705 DeclRefType.addConst(); 18706 CaptureType = Context.getLValueReferenceType(DeclRefType); 18707 break; 18708 } 18709 } 18710 } 18711 } 18712 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 18713 // No capture-default, and this is not an explicit capture 18714 // so cannot capture this variable. 18715 if (BuildAndDiagnose) { 18716 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18717 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18718 auto *LSI = cast<LambdaScopeInfo>(CSI); 18719 if (LSI->Lambda) { 18720 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18721 buildLambdaCaptureFixit(*this, LSI, Var); 18722 } 18723 // FIXME: If we error out because an outer lambda can not implicitly 18724 // capture a variable that an inner lambda explicitly captures, we 18725 // should have the inner lambda do the explicit capture - because 18726 // it makes for cleaner diagnostics later. This would purely be done 18727 // so that the diagnostic does not misleadingly claim that a variable 18728 // can not be captured by a lambda implicitly even though it is captured 18729 // explicitly. Suggestion: 18730 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 18731 // at the function head 18732 // - cache the StartingDeclContext - this must be a lambda 18733 // - captureInLambda in the innermost lambda the variable. 18734 } 18735 return true; 18736 } 18737 18738 FunctionScopesIndex--; 18739 DC = ParentDC; 18740 Explicit = false; 18741 } while (!VarDC->Equals(DC)); 18742 18743 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 18744 // computing the type of the capture at each step, checking type-specific 18745 // requirements, and adding captures if requested. 18746 // If the variable had already been captured previously, we start capturing 18747 // at the lambda nested within that one. 18748 bool Invalid = false; 18749 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 18750 ++I) { 18751 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 18752 18753 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18754 // certain types of variables (unnamed, variably modified types etc.) 18755 // so check for eligibility. 18756 if (!Invalid) 18757 Invalid = 18758 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 18759 18760 // After encountering an error, if we're actually supposed to capture, keep 18761 // capturing in nested contexts to suppress any follow-on diagnostics. 18762 if (Invalid && !BuildAndDiagnose) 18763 return true; 18764 18765 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 18766 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18767 DeclRefType, Nested, *this, Invalid); 18768 Nested = true; 18769 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18770 Invalid = !captureInCapturedRegion( 18771 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 18772 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 18773 Nested = true; 18774 } else { 18775 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18776 Invalid = 18777 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18778 DeclRefType, Nested, Kind, EllipsisLoc, 18779 /*IsTopScope*/ I == N - 1, *this, Invalid); 18780 Nested = true; 18781 } 18782 18783 if (Invalid && !BuildAndDiagnose) 18784 return true; 18785 } 18786 return Invalid; 18787 } 18788 18789 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 18790 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 18791 QualType CaptureType; 18792 QualType DeclRefType; 18793 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 18794 /*BuildAndDiagnose=*/true, CaptureType, 18795 DeclRefType, nullptr); 18796 } 18797 18798 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 18799 QualType CaptureType; 18800 QualType DeclRefType; 18801 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18802 /*BuildAndDiagnose=*/false, CaptureType, 18803 DeclRefType, nullptr); 18804 } 18805 18806 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 18807 QualType CaptureType; 18808 QualType DeclRefType; 18809 18810 // Determine whether we can capture this variable. 18811 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18812 /*BuildAndDiagnose=*/false, CaptureType, 18813 DeclRefType, nullptr)) 18814 return QualType(); 18815 18816 return DeclRefType; 18817 } 18818 18819 namespace { 18820 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 18821 // The produced TemplateArgumentListInfo* points to data stored within this 18822 // object, so should only be used in contexts where the pointer will not be 18823 // used after the CopiedTemplateArgs object is destroyed. 18824 class CopiedTemplateArgs { 18825 bool HasArgs; 18826 TemplateArgumentListInfo TemplateArgStorage; 18827 public: 18828 template<typename RefExpr> 18829 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 18830 if (HasArgs) 18831 E->copyTemplateArgumentsInto(TemplateArgStorage); 18832 } 18833 operator TemplateArgumentListInfo*() 18834 #ifdef __has_cpp_attribute 18835 #if __has_cpp_attribute(clang::lifetimebound) 18836 [[clang::lifetimebound]] 18837 #endif 18838 #endif 18839 { 18840 return HasArgs ? &TemplateArgStorage : nullptr; 18841 } 18842 }; 18843 } 18844 18845 /// Walk the set of potential results of an expression and mark them all as 18846 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 18847 /// 18848 /// \return A new expression if we found any potential results, ExprEmpty() if 18849 /// not, and ExprError() if we diagnosed an error. 18850 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 18851 NonOdrUseReason NOUR) { 18852 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 18853 // an object that satisfies the requirements for appearing in a 18854 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 18855 // is immediately applied." This function handles the lvalue-to-rvalue 18856 // conversion part. 18857 // 18858 // If we encounter a node that claims to be an odr-use but shouldn't be, we 18859 // transform it into the relevant kind of non-odr-use node and rebuild the 18860 // tree of nodes leading to it. 18861 // 18862 // This is a mini-TreeTransform that only transforms a restricted subset of 18863 // nodes (and only certain operands of them). 18864 18865 // Rebuild a subexpression. 18866 auto Rebuild = [&](Expr *Sub) { 18867 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 18868 }; 18869 18870 // Check whether a potential result satisfies the requirements of NOUR. 18871 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 18872 // Any entity other than a VarDecl is always odr-used whenever it's named 18873 // in a potentially-evaluated expression. 18874 auto *VD = dyn_cast<VarDecl>(D); 18875 if (!VD) 18876 return true; 18877 18878 // C++2a [basic.def.odr]p4: 18879 // A variable x whose name appears as a potentially-evalauted expression 18880 // e is odr-used by e unless 18881 // -- x is a reference that is usable in constant expressions, or 18882 // -- x is a variable of non-reference type that is usable in constant 18883 // expressions and has no mutable subobjects, and e is an element of 18884 // the set of potential results of an expression of 18885 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18886 // conversion is applied, or 18887 // -- x is a variable of non-reference type, and e is an element of the 18888 // set of potential results of a discarded-value expression to which 18889 // the lvalue-to-rvalue conversion is not applied 18890 // 18891 // We check the first bullet and the "potentially-evaluated" condition in 18892 // BuildDeclRefExpr. We check the type requirements in the second bullet 18893 // in CheckLValueToRValueConversionOperand below. 18894 switch (NOUR) { 18895 case NOUR_None: 18896 case NOUR_Unevaluated: 18897 llvm_unreachable("unexpected non-odr-use-reason"); 18898 18899 case NOUR_Constant: 18900 // Constant references were handled when they were built. 18901 if (VD->getType()->isReferenceType()) 18902 return true; 18903 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18904 if (RD->hasMutableFields()) 18905 return true; 18906 if (!VD->isUsableInConstantExpressions(S.Context)) 18907 return true; 18908 break; 18909 18910 case NOUR_Discarded: 18911 if (VD->getType()->isReferenceType()) 18912 return true; 18913 break; 18914 } 18915 return false; 18916 }; 18917 18918 // Mark that this expression does not constitute an odr-use. 18919 auto MarkNotOdrUsed = [&] { 18920 S.MaybeODRUseExprs.remove(E); 18921 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18922 LSI->markVariableExprAsNonODRUsed(E); 18923 }; 18924 18925 // C++2a [basic.def.odr]p2: 18926 // The set of potential results of an expression e is defined as follows: 18927 switch (E->getStmtClass()) { 18928 // -- If e is an id-expression, ... 18929 case Expr::DeclRefExprClass: { 18930 auto *DRE = cast<DeclRefExpr>(E); 18931 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18932 break; 18933 18934 // Rebuild as a non-odr-use DeclRefExpr. 18935 MarkNotOdrUsed(); 18936 return DeclRefExpr::Create( 18937 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18938 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18939 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18940 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18941 } 18942 18943 case Expr::FunctionParmPackExprClass: { 18944 auto *FPPE = cast<FunctionParmPackExpr>(E); 18945 // If any of the declarations in the pack is odr-used, then the expression 18946 // as a whole constitutes an odr-use. 18947 for (VarDecl *D : *FPPE) 18948 if (IsPotentialResultOdrUsed(D)) 18949 return ExprEmpty(); 18950 18951 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18952 // nothing cares about whether we marked this as an odr-use, but it might 18953 // be useful for non-compiler tools. 18954 MarkNotOdrUsed(); 18955 break; 18956 } 18957 18958 // -- If e is a subscripting operation with an array operand... 18959 case Expr::ArraySubscriptExprClass: { 18960 auto *ASE = cast<ArraySubscriptExpr>(E); 18961 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18962 if (!OldBase->getType()->isArrayType()) 18963 break; 18964 ExprResult Base = Rebuild(OldBase); 18965 if (!Base.isUsable()) 18966 return Base; 18967 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18968 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18969 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18970 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18971 ASE->getRBracketLoc()); 18972 } 18973 18974 case Expr::MemberExprClass: { 18975 auto *ME = cast<MemberExpr>(E); 18976 // -- If e is a class member access expression [...] naming a non-static 18977 // data member... 18978 if (isa<FieldDecl>(ME->getMemberDecl())) { 18979 ExprResult Base = Rebuild(ME->getBase()); 18980 if (!Base.isUsable()) 18981 return Base; 18982 return MemberExpr::Create( 18983 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18984 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18985 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18986 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18987 ME->getObjectKind(), ME->isNonOdrUse()); 18988 } 18989 18990 if (ME->getMemberDecl()->isCXXInstanceMember()) 18991 break; 18992 18993 // -- If e is a class member access expression naming a static data member, 18994 // ... 18995 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18996 break; 18997 18998 // Rebuild as a non-odr-use MemberExpr. 18999 MarkNotOdrUsed(); 19000 return MemberExpr::Create( 19001 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 19002 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 19003 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 19004 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 19005 } 19006 19007 case Expr::BinaryOperatorClass: { 19008 auto *BO = cast<BinaryOperator>(E); 19009 Expr *LHS = BO->getLHS(); 19010 Expr *RHS = BO->getRHS(); 19011 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 19012 if (BO->getOpcode() == BO_PtrMemD) { 19013 ExprResult Sub = Rebuild(LHS); 19014 if (!Sub.isUsable()) 19015 return Sub; 19016 LHS = Sub.get(); 19017 // -- If e is a comma expression, ... 19018 } else if (BO->getOpcode() == BO_Comma) { 19019 ExprResult Sub = Rebuild(RHS); 19020 if (!Sub.isUsable()) 19021 return Sub; 19022 RHS = Sub.get(); 19023 } else { 19024 break; 19025 } 19026 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 19027 LHS, RHS); 19028 } 19029 19030 // -- If e has the form (e1)... 19031 case Expr::ParenExprClass: { 19032 auto *PE = cast<ParenExpr>(E); 19033 ExprResult Sub = Rebuild(PE->getSubExpr()); 19034 if (!Sub.isUsable()) 19035 return Sub; 19036 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 19037 } 19038 19039 // -- If e is a glvalue conditional expression, ... 19040 // We don't apply this to a binary conditional operator. FIXME: Should we? 19041 case Expr::ConditionalOperatorClass: { 19042 auto *CO = cast<ConditionalOperator>(E); 19043 ExprResult LHS = Rebuild(CO->getLHS()); 19044 if (LHS.isInvalid()) 19045 return ExprError(); 19046 ExprResult RHS = Rebuild(CO->getRHS()); 19047 if (RHS.isInvalid()) 19048 return ExprError(); 19049 if (!LHS.isUsable() && !RHS.isUsable()) 19050 return ExprEmpty(); 19051 if (!LHS.isUsable()) 19052 LHS = CO->getLHS(); 19053 if (!RHS.isUsable()) 19054 RHS = CO->getRHS(); 19055 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 19056 CO->getCond(), LHS.get(), RHS.get()); 19057 } 19058 19059 // [Clang extension] 19060 // -- If e has the form __extension__ e1... 19061 case Expr::UnaryOperatorClass: { 19062 auto *UO = cast<UnaryOperator>(E); 19063 if (UO->getOpcode() != UO_Extension) 19064 break; 19065 ExprResult Sub = Rebuild(UO->getSubExpr()); 19066 if (!Sub.isUsable()) 19067 return Sub; 19068 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 19069 Sub.get()); 19070 } 19071 19072 // [Clang extension] 19073 // -- If e has the form _Generic(...), the set of potential results is the 19074 // union of the sets of potential results of the associated expressions. 19075 case Expr::GenericSelectionExprClass: { 19076 auto *GSE = cast<GenericSelectionExpr>(E); 19077 19078 SmallVector<Expr *, 4> AssocExprs; 19079 bool AnyChanged = false; 19080 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 19081 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 19082 if (AssocExpr.isInvalid()) 19083 return ExprError(); 19084 if (AssocExpr.isUsable()) { 19085 AssocExprs.push_back(AssocExpr.get()); 19086 AnyChanged = true; 19087 } else { 19088 AssocExprs.push_back(OrigAssocExpr); 19089 } 19090 } 19091 19092 return AnyChanged ? S.CreateGenericSelectionExpr( 19093 GSE->getGenericLoc(), GSE->getDefaultLoc(), 19094 GSE->getRParenLoc(), GSE->getControllingExpr(), 19095 GSE->getAssocTypeSourceInfos(), AssocExprs) 19096 : ExprEmpty(); 19097 } 19098 19099 // [Clang extension] 19100 // -- If e has the form __builtin_choose_expr(...), the set of potential 19101 // results is the union of the sets of potential results of the 19102 // second and third subexpressions. 19103 case Expr::ChooseExprClass: { 19104 auto *CE = cast<ChooseExpr>(E); 19105 19106 ExprResult LHS = Rebuild(CE->getLHS()); 19107 if (LHS.isInvalid()) 19108 return ExprError(); 19109 19110 ExprResult RHS = Rebuild(CE->getLHS()); 19111 if (RHS.isInvalid()) 19112 return ExprError(); 19113 19114 if (!LHS.get() && !RHS.get()) 19115 return ExprEmpty(); 19116 if (!LHS.isUsable()) 19117 LHS = CE->getLHS(); 19118 if (!RHS.isUsable()) 19119 RHS = CE->getRHS(); 19120 19121 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 19122 RHS.get(), CE->getRParenLoc()); 19123 } 19124 19125 // Step through non-syntactic nodes. 19126 case Expr::ConstantExprClass: { 19127 auto *CE = cast<ConstantExpr>(E); 19128 ExprResult Sub = Rebuild(CE->getSubExpr()); 19129 if (!Sub.isUsable()) 19130 return Sub; 19131 return ConstantExpr::Create(S.Context, Sub.get()); 19132 } 19133 19134 // We could mostly rely on the recursive rebuilding to rebuild implicit 19135 // casts, but not at the top level, so rebuild them here. 19136 case Expr::ImplicitCastExprClass: { 19137 auto *ICE = cast<ImplicitCastExpr>(E); 19138 // Only step through the narrow set of cast kinds we expect to encounter. 19139 // Anything else suggests we've left the region in which potential results 19140 // can be found. 19141 switch (ICE->getCastKind()) { 19142 case CK_NoOp: 19143 case CK_DerivedToBase: 19144 case CK_UncheckedDerivedToBase: { 19145 ExprResult Sub = Rebuild(ICE->getSubExpr()); 19146 if (!Sub.isUsable()) 19147 return Sub; 19148 CXXCastPath Path(ICE->path()); 19149 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 19150 ICE->getValueKind(), &Path); 19151 } 19152 19153 default: 19154 break; 19155 } 19156 break; 19157 } 19158 19159 default: 19160 break; 19161 } 19162 19163 // Can't traverse through this node. Nothing to do. 19164 return ExprEmpty(); 19165 } 19166 19167 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 19168 // Check whether the operand is or contains an object of non-trivial C union 19169 // type. 19170 if (E->getType().isVolatileQualified() && 19171 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 19172 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 19173 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 19174 Sema::NTCUC_LValueToRValueVolatile, 19175 NTCUK_Destruct|NTCUK_Copy); 19176 19177 // C++2a [basic.def.odr]p4: 19178 // [...] an expression of non-volatile-qualified non-class type to which 19179 // the lvalue-to-rvalue conversion is applied [...] 19180 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 19181 return E; 19182 19183 ExprResult Result = 19184 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 19185 if (Result.isInvalid()) 19186 return ExprError(); 19187 return Result.get() ? Result : E; 19188 } 19189 19190 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 19191 Res = CorrectDelayedTyposInExpr(Res); 19192 19193 if (!Res.isUsable()) 19194 return Res; 19195 19196 // If a constant-expression is a reference to a variable where we delay 19197 // deciding whether it is an odr-use, just assume we will apply the 19198 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 19199 // (a non-type template argument), we have special handling anyway. 19200 return CheckLValueToRValueConversionOperand(Res.get()); 19201 } 19202 19203 void Sema::CleanupVarDeclMarking() { 19204 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 19205 // call. 19206 MaybeODRUseExprSet LocalMaybeODRUseExprs; 19207 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 19208 19209 for (Expr *E : LocalMaybeODRUseExprs) { 19210 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 19211 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 19212 DRE->getLocation(), *this); 19213 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 19214 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 19215 *this); 19216 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 19217 for (VarDecl *VD : *FP) 19218 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 19219 } else { 19220 llvm_unreachable("Unexpected expression"); 19221 } 19222 } 19223 19224 assert(MaybeODRUseExprs.empty() && 19225 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 19226 } 19227 19228 static void DoMarkVarDeclReferenced( 19229 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 19230 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 19231 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 19232 isa<FunctionParmPackExpr>(E)) && 19233 "Invalid Expr argument to DoMarkVarDeclReferenced"); 19234 Var->setReferenced(); 19235 19236 if (Var->isInvalidDecl()) 19237 return; 19238 19239 auto *MSI = Var->getMemberSpecializationInfo(); 19240 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 19241 : Var->getTemplateSpecializationKind(); 19242 19243 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 19244 bool UsableInConstantExpr = 19245 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 19246 19247 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 19248 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 19249 } 19250 19251 // C++20 [expr.const]p12: 19252 // A variable [...] is needed for constant evaluation if it is [...] a 19253 // variable whose name appears as a potentially constant evaluated 19254 // expression that is either a contexpr variable or is of non-volatile 19255 // const-qualified integral type or of reference type 19256 bool NeededForConstantEvaluation = 19257 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 19258 19259 bool NeedDefinition = 19260 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 19261 19262 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 19263 "Can't instantiate a partial template specialization."); 19264 19265 // If this might be a member specialization of a static data member, check 19266 // the specialization is visible. We already did the checks for variable 19267 // template specializations when we created them. 19268 if (NeedDefinition && TSK != TSK_Undeclared && 19269 !isa<VarTemplateSpecializationDecl>(Var)) 19270 SemaRef.checkSpecializationVisibility(Loc, Var); 19271 19272 // Perform implicit instantiation of static data members, static data member 19273 // templates of class templates, and variable template specializations. Delay 19274 // instantiations of variable templates, except for those that could be used 19275 // in a constant expression. 19276 if (NeedDefinition && isTemplateInstantiation(TSK)) { 19277 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 19278 // instantiation declaration if a variable is usable in a constant 19279 // expression (among other cases). 19280 bool TryInstantiating = 19281 TSK == TSK_ImplicitInstantiation || 19282 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 19283 19284 if (TryInstantiating) { 19285 SourceLocation PointOfInstantiation = 19286 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 19287 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 19288 if (FirstInstantiation) { 19289 PointOfInstantiation = Loc; 19290 if (MSI) 19291 MSI->setPointOfInstantiation(PointOfInstantiation); 19292 // FIXME: Notify listener. 19293 else 19294 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 19295 } 19296 19297 if (UsableInConstantExpr) { 19298 // Do not defer instantiations of variables that could be used in a 19299 // constant expression. 19300 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 19301 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 19302 }); 19303 19304 // Re-set the member to trigger a recomputation of the dependence bits 19305 // for the expression. 19306 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 19307 DRE->setDecl(DRE->getDecl()); 19308 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 19309 ME->setMemberDecl(ME->getMemberDecl()); 19310 } else if (FirstInstantiation || 19311 isa<VarTemplateSpecializationDecl>(Var)) { 19312 // FIXME: For a specialization of a variable template, we don't 19313 // distinguish between "declaration and type implicitly instantiated" 19314 // and "implicit instantiation of definition requested", so we have 19315 // no direct way to avoid enqueueing the pending instantiation 19316 // multiple times. 19317 SemaRef.PendingInstantiations 19318 .push_back(std::make_pair(Var, PointOfInstantiation)); 19319 } 19320 } 19321 } 19322 19323 // C++2a [basic.def.odr]p4: 19324 // A variable x whose name appears as a potentially-evaluated expression e 19325 // is odr-used by e unless 19326 // -- x is a reference that is usable in constant expressions 19327 // -- x is a variable of non-reference type that is usable in constant 19328 // expressions and has no mutable subobjects [FIXME], and e is an 19329 // element of the set of potential results of an expression of 19330 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 19331 // conversion is applied 19332 // -- x is a variable of non-reference type, and e is an element of the set 19333 // of potential results of a discarded-value expression to which the 19334 // lvalue-to-rvalue conversion is not applied [FIXME] 19335 // 19336 // We check the first part of the second bullet here, and 19337 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 19338 // FIXME: To get the third bullet right, we need to delay this even for 19339 // variables that are not usable in constant expressions. 19340 19341 // If we already know this isn't an odr-use, there's nothing more to do. 19342 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 19343 if (DRE->isNonOdrUse()) 19344 return; 19345 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 19346 if (ME->isNonOdrUse()) 19347 return; 19348 19349 switch (OdrUse) { 19350 case OdrUseContext::None: 19351 assert((!E || isa<FunctionParmPackExpr>(E)) && 19352 "missing non-odr-use marking for unevaluated decl ref"); 19353 break; 19354 19355 case OdrUseContext::FormallyOdrUsed: 19356 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 19357 // behavior. 19358 break; 19359 19360 case OdrUseContext::Used: 19361 // If we might later find that this expression isn't actually an odr-use, 19362 // delay the marking. 19363 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 19364 SemaRef.MaybeODRUseExprs.insert(E); 19365 else 19366 MarkVarDeclODRUsed(Var, Loc, SemaRef); 19367 break; 19368 19369 case OdrUseContext::Dependent: 19370 // If this is a dependent context, we don't need to mark variables as 19371 // odr-used, but we may still need to track them for lambda capture. 19372 // FIXME: Do we also need to do this inside dependent typeid expressions 19373 // (which are modeled as unevaluated at this point)? 19374 const bool RefersToEnclosingScope = 19375 (SemaRef.CurContext != Var->getDeclContext() && 19376 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 19377 if (RefersToEnclosingScope) { 19378 LambdaScopeInfo *const LSI = 19379 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 19380 if (LSI && (!LSI->CallOperator || 19381 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 19382 // If a variable could potentially be odr-used, defer marking it so 19383 // until we finish analyzing the full expression for any 19384 // lvalue-to-rvalue 19385 // or discarded value conversions that would obviate odr-use. 19386 // Add it to the list of potential captures that will be analyzed 19387 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 19388 // unless the variable is a reference that was initialized by a constant 19389 // expression (this will never need to be captured or odr-used). 19390 // 19391 // FIXME: We can simplify this a lot after implementing P0588R1. 19392 assert(E && "Capture variable should be used in an expression."); 19393 if (!Var->getType()->isReferenceType() || 19394 !Var->isUsableInConstantExpressions(SemaRef.Context)) 19395 LSI->addPotentialCapture(E->IgnoreParens()); 19396 } 19397 } 19398 break; 19399 } 19400 } 19401 19402 /// Mark a variable referenced, and check whether it is odr-used 19403 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 19404 /// used directly for normal expressions referring to VarDecl. 19405 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 19406 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 19407 } 19408 19409 static void 19410 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 19411 bool MightBeOdrUse, 19412 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 19413 if (SemaRef.isInOpenMPDeclareTargetContext()) 19414 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 19415 19416 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 19417 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 19418 return; 19419 } 19420 19421 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 19422 19423 // If this is a call to a method via a cast, also mark the method in the 19424 // derived class used in case codegen can devirtualize the call. 19425 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 19426 if (!ME) 19427 return; 19428 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 19429 if (!MD) 19430 return; 19431 // Only attempt to devirtualize if this is truly a virtual call. 19432 bool IsVirtualCall = MD->isVirtual() && 19433 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 19434 if (!IsVirtualCall) 19435 return; 19436 19437 // If it's possible to devirtualize the call, mark the called function 19438 // referenced. 19439 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 19440 ME->getBase(), SemaRef.getLangOpts().AppleKext); 19441 if (DM) 19442 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 19443 } 19444 19445 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 19446 /// 19447 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 19448 /// handled with care if the DeclRefExpr is not newly-created. 19449 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 19450 // TODO: update this with DR# once a defect report is filed. 19451 // C++11 defect. The address of a pure member should not be an ODR use, even 19452 // if it's a qualified reference. 19453 bool OdrUse = true; 19454 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 19455 if (Method->isVirtual() && 19456 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 19457 OdrUse = false; 19458 19459 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 19460 if (!isUnevaluatedContext() && !isConstantEvaluated() && 19461 FD->isConsteval() && !RebuildingImmediateInvocation) 19462 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 19463 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 19464 RefsMinusAssignments); 19465 } 19466 19467 /// Perform reference-marking and odr-use handling for a MemberExpr. 19468 void Sema::MarkMemberReferenced(MemberExpr *E) { 19469 // C++11 [basic.def.odr]p2: 19470 // A non-overloaded function whose name appears as a potentially-evaluated 19471 // expression or a member of a set of candidate functions, if selected by 19472 // overload resolution when referred to from a potentially-evaluated 19473 // expression, is odr-used, unless it is a pure virtual function and its 19474 // name is not explicitly qualified. 19475 bool MightBeOdrUse = true; 19476 if (E->performsVirtualDispatch(getLangOpts())) { 19477 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 19478 if (Method->isPure()) 19479 MightBeOdrUse = false; 19480 } 19481 SourceLocation Loc = 19482 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 19483 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 19484 RefsMinusAssignments); 19485 } 19486 19487 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 19488 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 19489 for (VarDecl *VD : *E) 19490 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 19491 RefsMinusAssignments); 19492 } 19493 19494 /// Perform marking for a reference to an arbitrary declaration. It 19495 /// marks the declaration referenced, and performs odr-use checking for 19496 /// functions and variables. This method should not be used when building a 19497 /// normal expression which refers to a variable. 19498 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 19499 bool MightBeOdrUse) { 19500 if (MightBeOdrUse) { 19501 if (auto *VD = dyn_cast<VarDecl>(D)) { 19502 MarkVariableReferenced(Loc, VD); 19503 return; 19504 } 19505 } 19506 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 19507 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 19508 return; 19509 } 19510 D->setReferenced(); 19511 } 19512 19513 namespace { 19514 // Mark all of the declarations used by a type as referenced. 19515 // FIXME: Not fully implemented yet! We need to have a better understanding 19516 // of when we're entering a context we should not recurse into. 19517 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 19518 // TreeTransforms rebuilding the type in a new context. Rather than 19519 // duplicating the TreeTransform logic, we should consider reusing it here. 19520 // Currently that causes problems when rebuilding LambdaExprs. 19521 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 19522 Sema &S; 19523 SourceLocation Loc; 19524 19525 public: 19526 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 19527 19528 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 19529 19530 bool TraverseTemplateArgument(const TemplateArgument &Arg); 19531 }; 19532 } 19533 19534 bool MarkReferencedDecls::TraverseTemplateArgument( 19535 const TemplateArgument &Arg) { 19536 { 19537 // A non-type template argument is a constant-evaluated context. 19538 EnterExpressionEvaluationContext Evaluated( 19539 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 19540 if (Arg.getKind() == TemplateArgument::Declaration) { 19541 if (Decl *D = Arg.getAsDecl()) 19542 S.MarkAnyDeclReferenced(Loc, D, true); 19543 } else if (Arg.getKind() == TemplateArgument::Expression) { 19544 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 19545 } 19546 } 19547 19548 return Inherited::TraverseTemplateArgument(Arg); 19549 } 19550 19551 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 19552 MarkReferencedDecls Marker(*this, Loc); 19553 Marker.TraverseType(T); 19554 } 19555 19556 namespace { 19557 /// Helper class that marks all of the declarations referenced by 19558 /// potentially-evaluated subexpressions as "referenced". 19559 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 19560 public: 19561 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 19562 bool SkipLocalVariables; 19563 ArrayRef<const Expr *> StopAt; 19564 19565 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables, 19566 ArrayRef<const Expr *> StopAt) 19567 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {} 19568 19569 void visitUsedDecl(SourceLocation Loc, Decl *D) { 19570 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 19571 } 19572 19573 void Visit(Expr *E) { 19574 if (std::find(StopAt.begin(), StopAt.end(), E) != StopAt.end()) 19575 return; 19576 Inherited::Visit(E); 19577 } 19578 19579 void VisitDeclRefExpr(DeclRefExpr *E) { 19580 // If we were asked not to visit local variables, don't. 19581 if (SkipLocalVariables) { 19582 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 19583 if (VD->hasLocalStorage()) 19584 return; 19585 } 19586 19587 // FIXME: This can trigger the instantiation of the initializer of a 19588 // variable, which can cause the expression to become value-dependent 19589 // or error-dependent. Do we need to propagate the new dependence bits? 19590 S.MarkDeclRefReferenced(E); 19591 } 19592 19593 void VisitMemberExpr(MemberExpr *E) { 19594 S.MarkMemberReferenced(E); 19595 Visit(E->getBase()); 19596 } 19597 }; 19598 } // namespace 19599 19600 /// Mark any declarations that appear within this expression or any 19601 /// potentially-evaluated subexpressions as "referenced". 19602 /// 19603 /// \param SkipLocalVariables If true, don't mark local variables as 19604 /// 'referenced'. 19605 /// \param StopAt Subexpressions that we shouldn't recurse into. 19606 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 19607 bool SkipLocalVariables, 19608 ArrayRef<const Expr*> StopAt) { 19609 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E); 19610 } 19611 19612 /// Emit a diagnostic when statements are reachable. 19613 /// FIXME: check for reachability even in expressions for which we don't build a 19614 /// CFG (eg, in the initializer of a global or in a constant expression). 19615 /// For example, 19616 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; } 19617 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, 19618 const PartialDiagnostic &PD) { 19619 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 19620 if (!FunctionScopes.empty()) 19621 FunctionScopes.back()->PossiblyUnreachableDiags.push_back( 19622 sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 19623 return true; 19624 } 19625 19626 // The initializer of a constexpr variable or of the first declaration of a 19627 // static data member is not syntactically a constant evaluated constant, 19628 // but nonetheless is always required to be a constant expression, so we 19629 // can skip diagnosing. 19630 // FIXME: Using the mangling context here is a hack. 19631 if (auto *VD = dyn_cast_or_null<VarDecl>( 19632 ExprEvalContexts.back().ManglingContextDecl)) { 19633 if (VD->isConstexpr() || 19634 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 19635 return false; 19636 // FIXME: For any other kind of variable, we should build a CFG for its 19637 // initializer and check whether the context in question is reachable. 19638 } 19639 19640 Diag(Loc, PD); 19641 return true; 19642 } 19643 19644 /// Emit a diagnostic that describes an effect on the run-time behavior 19645 /// of the program being compiled. 19646 /// 19647 /// This routine emits the given diagnostic when the code currently being 19648 /// type-checked is "potentially evaluated", meaning that there is a 19649 /// possibility that the code will actually be executable. Code in sizeof() 19650 /// expressions, code used only during overload resolution, etc., are not 19651 /// potentially evaluated. This routine will suppress such diagnostics or, 19652 /// in the absolutely nutty case of potentially potentially evaluated 19653 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 19654 /// later. 19655 /// 19656 /// This routine should be used for all diagnostics that describe the run-time 19657 /// behavior of a program, such as passing a non-POD value through an ellipsis. 19658 /// Failure to do so will likely result in spurious diagnostics or failures 19659 /// during overload resolution or within sizeof/alignof/typeof/typeid. 19660 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 19661 const PartialDiagnostic &PD) { 19662 19663 if (ExprEvalContexts.back().isDiscardedStatementContext()) 19664 return false; 19665 19666 switch (ExprEvalContexts.back().Context) { 19667 case ExpressionEvaluationContext::Unevaluated: 19668 case ExpressionEvaluationContext::UnevaluatedList: 19669 case ExpressionEvaluationContext::UnevaluatedAbstract: 19670 case ExpressionEvaluationContext::DiscardedStatement: 19671 // The argument will never be evaluated, so don't complain. 19672 break; 19673 19674 case ExpressionEvaluationContext::ConstantEvaluated: 19675 case ExpressionEvaluationContext::ImmediateFunctionContext: 19676 // Relevant diagnostics should be produced by constant evaluation. 19677 break; 19678 19679 case ExpressionEvaluationContext::PotentiallyEvaluated: 19680 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 19681 return DiagIfReachable(Loc, Stmts, PD); 19682 } 19683 19684 return false; 19685 } 19686 19687 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 19688 const PartialDiagnostic &PD) { 19689 return DiagRuntimeBehavior( 19690 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 19691 } 19692 19693 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 19694 CallExpr *CE, FunctionDecl *FD) { 19695 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 19696 return false; 19697 19698 // If we're inside a decltype's expression, don't check for a valid return 19699 // type or construct temporaries until we know whether this is the last call. 19700 if (ExprEvalContexts.back().ExprContext == 19701 ExpressionEvaluationContextRecord::EK_Decltype) { 19702 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 19703 return false; 19704 } 19705 19706 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 19707 FunctionDecl *FD; 19708 CallExpr *CE; 19709 19710 public: 19711 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 19712 : FD(FD), CE(CE) { } 19713 19714 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 19715 if (!FD) { 19716 S.Diag(Loc, diag::err_call_incomplete_return) 19717 << T << CE->getSourceRange(); 19718 return; 19719 } 19720 19721 S.Diag(Loc, diag::err_call_function_incomplete_return) 19722 << CE->getSourceRange() << FD << T; 19723 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 19724 << FD->getDeclName(); 19725 } 19726 } Diagnoser(FD, CE); 19727 19728 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 19729 return true; 19730 19731 return false; 19732 } 19733 19734 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 19735 // will prevent this condition from triggering, which is what we want. 19736 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 19737 SourceLocation Loc; 19738 19739 unsigned diagnostic = diag::warn_condition_is_assignment; 19740 bool IsOrAssign = false; 19741 19742 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 19743 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 19744 return; 19745 19746 IsOrAssign = Op->getOpcode() == BO_OrAssign; 19747 19748 // Greylist some idioms by putting them into a warning subcategory. 19749 if (ObjCMessageExpr *ME 19750 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 19751 Selector Sel = ME->getSelector(); 19752 19753 // self = [<foo> init...] 19754 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 19755 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19756 19757 // <foo> = [<bar> nextObject] 19758 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 19759 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19760 } 19761 19762 Loc = Op->getOperatorLoc(); 19763 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 19764 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 19765 return; 19766 19767 IsOrAssign = Op->getOperator() == OO_PipeEqual; 19768 Loc = Op->getOperatorLoc(); 19769 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 19770 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 19771 else { 19772 // Not an assignment. 19773 return; 19774 } 19775 19776 Diag(Loc, diagnostic) << E->getSourceRange(); 19777 19778 SourceLocation Open = E->getBeginLoc(); 19779 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 19780 Diag(Loc, diag::note_condition_assign_silence) 19781 << FixItHint::CreateInsertion(Open, "(") 19782 << FixItHint::CreateInsertion(Close, ")"); 19783 19784 if (IsOrAssign) 19785 Diag(Loc, diag::note_condition_or_assign_to_comparison) 19786 << FixItHint::CreateReplacement(Loc, "!="); 19787 else 19788 Diag(Loc, diag::note_condition_assign_to_comparison) 19789 << FixItHint::CreateReplacement(Loc, "=="); 19790 } 19791 19792 /// Redundant parentheses over an equality comparison can indicate 19793 /// that the user intended an assignment used as condition. 19794 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 19795 // Don't warn if the parens came from a macro. 19796 SourceLocation parenLoc = ParenE->getBeginLoc(); 19797 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 19798 return; 19799 // Don't warn for dependent expressions. 19800 if (ParenE->isTypeDependent()) 19801 return; 19802 19803 Expr *E = ParenE->IgnoreParens(); 19804 19805 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 19806 if (opE->getOpcode() == BO_EQ && 19807 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 19808 == Expr::MLV_Valid) { 19809 SourceLocation Loc = opE->getOperatorLoc(); 19810 19811 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 19812 SourceRange ParenERange = ParenE->getSourceRange(); 19813 Diag(Loc, diag::note_equality_comparison_silence) 19814 << FixItHint::CreateRemoval(ParenERange.getBegin()) 19815 << FixItHint::CreateRemoval(ParenERange.getEnd()); 19816 Diag(Loc, diag::note_equality_comparison_to_assign) 19817 << FixItHint::CreateReplacement(Loc, "="); 19818 } 19819 } 19820 19821 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 19822 bool IsConstexpr) { 19823 DiagnoseAssignmentAsCondition(E); 19824 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 19825 DiagnoseEqualityWithExtraParens(parenE); 19826 19827 ExprResult result = CheckPlaceholderExpr(E); 19828 if (result.isInvalid()) return ExprError(); 19829 E = result.get(); 19830 19831 if (!E->isTypeDependent()) { 19832 if (getLangOpts().CPlusPlus) 19833 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 19834 19835 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 19836 if (ERes.isInvalid()) 19837 return ExprError(); 19838 E = ERes.get(); 19839 19840 QualType T = E->getType(); 19841 if (!T->isScalarType()) { // C99 6.8.4.1p1 19842 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 19843 << T << E->getSourceRange(); 19844 return ExprError(); 19845 } 19846 CheckBoolLikeConversion(E, Loc); 19847 } 19848 19849 return E; 19850 } 19851 19852 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 19853 Expr *SubExpr, ConditionKind CK, 19854 bool MissingOK) { 19855 // MissingOK indicates whether having no condition expression is valid 19856 // (for loop) or invalid (e.g. while loop). 19857 if (!SubExpr) 19858 return MissingOK ? ConditionResult() : ConditionError(); 19859 19860 ExprResult Cond; 19861 switch (CK) { 19862 case ConditionKind::Boolean: 19863 Cond = CheckBooleanCondition(Loc, SubExpr); 19864 break; 19865 19866 case ConditionKind::ConstexprIf: 19867 Cond = CheckBooleanCondition(Loc, SubExpr, true); 19868 break; 19869 19870 case ConditionKind::Switch: 19871 Cond = CheckSwitchCondition(Loc, SubExpr); 19872 break; 19873 } 19874 if (Cond.isInvalid()) { 19875 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 19876 {SubExpr}, PreferredConditionType(CK)); 19877 if (!Cond.get()) 19878 return ConditionError(); 19879 } 19880 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 19881 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 19882 if (!FullExpr.get()) 19883 return ConditionError(); 19884 19885 return ConditionResult(*this, nullptr, FullExpr, 19886 CK == ConditionKind::ConstexprIf); 19887 } 19888 19889 namespace { 19890 /// A visitor for rebuilding a call to an __unknown_any expression 19891 /// to have an appropriate type. 19892 struct RebuildUnknownAnyFunction 19893 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 19894 19895 Sema &S; 19896 19897 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 19898 19899 ExprResult VisitStmt(Stmt *S) { 19900 llvm_unreachable("unexpected statement!"); 19901 } 19902 19903 ExprResult VisitExpr(Expr *E) { 19904 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 19905 << E->getSourceRange(); 19906 return ExprError(); 19907 } 19908 19909 /// Rebuild an expression which simply semantically wraps another 19910 /// expression which it shares the type and value kind of. 19911 template <class T> ExprResult rebuildSugarExpr(T *E) { 19912 ExprResult SubResult = Visit(E->getSubExpr()); 19913 if (SubResult.isInvalid()) return ExprError(); 19914 19915 Expr *SubExpr = SubResult.get(); 19916 E->setSubExpr(SubExpr); 19917 E->setType(SubExpr->getType()); 19918 E->setValueKind(SubExpr->getValueKind()); 19919 assert(E->getObjectKind() == OK_Ordinary); 19920 return E; 19921 } 19922 19923 ExprResult VisitParenExpr(ParenExpr *E) { 19924 return rebuildSugarExpr(E); 19925 } 19926 19927 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19928 return rebuildSugarExpr(E); 19929 } 19930 19931 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19932 ExprResult SubResult = Visit(E->getSubExpr()); 19933 if (SubResult.isInvalid()) return ExprError(); 19934 19935 Expr *SubExpr = SubResult.get(); 19936 E->setSubExpr(SubExpr); 19937 E->setType(S.Context.getPointerType(SubExpr->getType())); 19938 assert(E->isPRValue()); 19939 assert(E->getObjectKind() == OK_Ordinary); 19940 return E; 19941 } 19942 19943 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19944 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19945 19946 E->setType(VD->getType()); 19947 19948 assert(E->isPRValue()); 19949 if (S.getLangOpts().CPlusPlus && 19950 !(isa<CXXMethodDecl>(VD) && 19951 cast<CXXMethodDecl>(VD)->isInstance())) 19952 E->setValueKind(VK_LValue); 19953 19954 return E; 19955 } 19956 19957 ExprResult VisitMemberExpr(MemberExpr *E) { 19958 return resolveDecl(E, E->getMemberDecl()); 19959 } 19960 19961 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19962 return resolveDecl(E, E->getDecl()); 19963 } 19964 }; 19965 } 19966 19967 /// Given a function expression of unknown-any type, try to rebuild it 19968 /// to have a function type. 19969 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19970 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19971 if (Result.isInvalid()) return ExprError(); 19972 return S.DefaultFunctionArrayConversion(Result.get()); 19973 } 19974 19975 namespace { 19976 /// A visitor for rebuilding an expression of type __unknown_anytype 19977 /// into one which resolves the type directly on the referring 19978 /// expression. Strict preservation of the original source 19979 /// structure is not a goal. 19980 struct RebuildUnknownAnyExpr 19981 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19982 19983 Sema &S; 19984 19985 /// The current destination type. 19986 QualType DestType; 19987 19988 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19989 : S(S), DestType(CastType) {} 19990 19991 ExprResult VisitStmt(Stmt *S) { 19992 llvm_unreachable("unexpected statement!"); 19993 } 19994 19995 ExprResult VisitExpr(Expr *E) { 19996 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19997 << E->getSourceRange(); 19998 return ExprError(); 19999 } 20000 20001 ExprResult VisitCallExpr(CallExpr *E); 20002 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 20003 20004 /// Rebuild an expression which simply semantically wraps another 20005 /// expression which it shares the type and value kind of. 20006 template <class T> ExprResult rebuildSugarExpr(T *E) { 20007 ExprResult SubResult = Visit(E->getSubExpr()); 20008 if (SubResult.isInvalid()) return ExprError(); 20009 Expr *SubExpr = SubResult.get(); 20010 E->setSubExpr(SubExpr); 20011 E->setType(SubExpr->getType()); 20012 E->setValueKind(SubExpr->getValueKind()); 20013 assert(E->getObjectKind() == OK_Ordinary); 20014 return E; 20015 } 20016 20017 ExprResult VisitParenExpr(ParenExpr *E) { 20018 return rebuildSugarExpr(E); 20019 } 20020 20021 ExprResult VisitUnaryExtension(UnaryOperator *E) { 20022 return rebuildSugarExpr(E); 20023 } 20024 20025 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 20026 const PointerType *Ptr = DestType->getAs<PointerType>(); 20027 if (!Ptr) { 20028 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 20029 << E->getSourceRange(); 20030 return ExprError(); 20031 } 20032 20033 if (isa<CallExpr>(E->getSubExpr())) { 20034 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 20035 << E->getSourceRange(); 20036 return ExprError(); 20037 } 20038 20039 assert(E->isPRValue()); 20040 assert(E->getObjectKind() == OK_Ordinary); 20041 E->setType(DestType); 20042 20043 // Build the sub-expression as if it were an object of the pointee type. 20044 DestType = Ptr->getPointeeType(); 20045 ExprResult SubResult = Visit(E->getSubExpr()); 20046 if (SubResult.isInvalid()) return ExprError(); 20047 E->setSubExpr(SubResult.get()); 20048 return E; 20049 } 20050 20051 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 20052 20053 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 20054 20055 ExprResult VisitMemberExpr(MemberExpr *E) { 20056 return resolveDecl(E, E->getMemberDecl()); 20057 } 20058 20059 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 20060 return resolveDecl(E, E->getDecl()); 20061 } 20062 }; 20063 } 20064 20065 /// Rebuilds a call expression which yielded __unknown_anytype. 20066 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 20067 Expr *CalleeExpr = E->getCallee(); 20068 20069 enum FnKind { 20070 FK_MemberFunction, 20071 FK_FunctionPointer, 20072 FK_BlockPointer 20073 }; 20074 20075 FnKind Kind; 20076 QualType CalleeType = CalleeExpr->getType(); 20077 if (CalleeType == S.Context.BoundMemberTy) { 20078 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 20079 Kind = FK_MemberFunction; 20080 CalleeType = Expr::findBoundMemberType(CalleeExpr); 20081 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 20082 CalleeType = Ptr->getPointeeType(); 20083 Kind = FK_FunctionPointer; 20084 } else { 20085 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 20086 Kind = FK_BlockPointer; 20087 } 20088 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 20089 20090 // Verify that this is a legal result type of a function. 20091 if (DestType->isArrayType() || DestType->isFunctionType()) { 20092 unsigned diagID = diag::err_func_returning_array_function; 20093 if (Kind == FK_BlockPointer) 20094 diagID = diag::err_block_returning_array_function; 20095 20096 S.Diag(E->getExprLoc(), diagID) 20097 << DestType->isFunctionType() << DestType; 20098 return ExprError(); 20099 } 20100 20101 // Otherwise, go ahead and set DestType as the call's result. 20102 E->setType(DestType.getNonLValueExprType(S.Context)); 20103 E->setValueKind(Expr::getValueKindForType(DestType)); 20104 assert(E->getObjectKind() == OK_Ordinary); 20105 20106 // Rebuild the function type, replacing the result type with DestType. 20107 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 20108 if (Proto) { 20109 // __unknown_anytype(...) is a special case used by the debugger when 20110 // it has no idea what a function's signature is. 20111 // 20112 // We want to build this call essentially under the K&R 20113 // unprototyped rules, but making a FunctionNoProtoType in C++ 20114 // would foul up all sorts of assumptions. However, we cannot 20115 // simply pass all arguments as variadic arguments, nor can we 20116 // portably just call the function under a non-variadic type; see 20117 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 20118 // However, it turns out that in practice it is generally safe to 20119 // call a function declared as "A foo(B,C,D);" under the prototype 20120 // "A foo(B,C,D,...);". The only known exception is with the 20121 // Windows ABI, where any variadic function is implicitly cdecl 20122 // regardless of its normal CC. Therefore we change the parameter 20123 // types to match the types of the arguments. 20124 // 20125 // This is a hack, but it is far superior to moving the 20126 // corresponding target-specific code from IR-gen to Sema/AST. 20127 20128 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 20129 SmallVector<QualType, 8> ArgTypes; 20130 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 20131 ArgTypes.reserve(E->getNumArgs()); 20132 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 20133 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); 20134 } 20135 ParamTypes = ArgTypes; 20136 } 20137 DestType = S.Context.getFunctionType(DestType, ParamTypes, 20138 Proto->getExtProtoInfo()); 20139 } else { 20140 DestType = S.Context.getFunctionNoProtoType(DestType, 20141 FnType->getExtInfo()); 20142 } 20143 20144 // Rebuild the appropriate pointer-to-function type. 20145 switch (Kind) { 20146 case FK_MemberFunction: 20147 // Nothing to do. 20148 break; 20149 20150 case FK_FunctionPointer: 20151 DestType = S.Context.getPointerType(DestType); 20152 break; 20153 20154 case FK_BlockPointer: 20155 DestType = S.Context.getBlockPointerType(DestType); 20156 break; 20157 } 20158 20159 // Finally, we can recurse. 20160 ExprResult CalleeResult = Visit(CalleeExpr); 20161 if (!CalleeResult.isUsable()) return ExprError(); 20162 E->setCallee(CalleeResult.get()); 20163 20164 // Bind a temporary if necessary. 20165 return S.MaybeBindToTemporary(E); 20166 } 20167 20168 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 20169 // Verify that this is a legal result type of a call. 20170 if (DestType->isArrayType() || DestType->isFunctionType()) { 20171 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 20172 << DestType->isFunctionType() << DestType; 20173 return ExprError(); 20174 } 20175 20176 // Rewrite the method result type if available. 20177 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 20178 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 20179 Method->setReturnType(DestType); 20180 } 20181 20182 // Change the type of the message. 20183 E->setType(DestType.getNonReferenceType()); 20184 E->setValueKind(Expr::getValueKindForType(DestType)); 20185 20186 return S.MaybeBindToTemporary(E); 20187 } 20188 20189 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 20190 // The only case we should ever see here is a function-to-pointer decay. 20191 if (E->getCastKind() == CK_FunctionToPointerDecay) { 20192 assert(E->isPRValue()); 20193 assert(E->getObjectKind() == OK_Ordinary); 20194 20195 E->setType(DestType); 20196 20197 // Rebuild the sub-expression as the pointee (function) type. 20198 DestType = DestType->castAs<PointerType>()->getPointeeType(); 20199 20200 ExprResult Result = Visit(E->getSubExpr()); 20201 if (!Result.isUsable()) return ExprError(); 20202 20203 E->setSubExpr(Result.get()); 20204 return E; 20205 } else if (E->getCastKind() == CK_LValueToRValue) { 20206 assert(E->isPRValue()); 20207 assert(E->getObjectKind() == OK_Ordinary); 20208 20209 assert(isa<BlockPointerType>(E->getType())); 20210 20211 E->setType(DestType); 20212 20213 // The sub-expression has to be a lvalue reference, so rebuild it as such. 20214 DestType = S.Context.getLValueReferenceType(DestType); 20215 20216 ExprResult Result = Visit(E->getSubExpr()); 20217 if (!Result.isUsable()) return ExprError(); 20218 20219 E->setSubExpr(Result.get()); 20220 return E; 20221 } else { 20222 llvm_unreachable("Unhandled cast type!"); 20223 } 20224 } 20225 20226 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 20227 ExprValueKind ValueKind = VK_LValue; 20228 QualType Type = DestType; 20229 20230 // We know how to make this work for certain kinds of decls: 20231 20232 // - functions 20233 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 20234 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 20235 DestType = Ptr->getPointeeType(); 20236 ExprResult Result = resolveDecl(E, VD); 20237 if (Result.isInvalid()) return ExprError(); 20238 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 20239 VK_PRValue); 20240 } 20241 20242 if (!Type->isFunctionType()) { 20243 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 20244 << VD << E->getSourceRange(); 20245 return ExprError(); 20246 } 20247 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 20248 // We must match the FunctionDecl's type to the hack introduced in 20249 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 20250 // type. See the lengthy commentary in that routine. 20251 QualType FDT = FD->getType(); 20252 const FunctionType *FnType = FDT->castAs<FunctionType>(); 20253 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 20254 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 20255 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 20256 SourceLocation Loc = FD->getLocation(); 20257 FunctionDecl *NewFD = FunctionDecl::Create( 20258 S.Context, FD->getDeclContext(), Loc, Loc, 20259 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 20260 SC_None, S.getCurFPFeatures().isFPConstrained(), 20261 false /*isInlineSpecified*/, FD->hasPrototype(), 20262 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 20263 20264 if (FD->getQualifier()) 20265 NewFD->setQualifierInfo(FD->getQualifierLoc()); 20266 20267 SmallVector<ParmVarDecl*, 16> Params; 20268 for (const auto &AI : FT->param_types()) { 20269 ParmVarDecl *Param = 20270 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 20271 Param->setScopeInfo(0, Params.size()); 20272 Params.push_back(Param); 20273 } 20274 NewFD->setParams(Params); 20275 DRE->setDecl(NewFD); 20276 VD = DRE->getDecl(); 20277 } 20278 } 20279 20280 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 20281 if (MD->isInstance()) { 20282 ValueKind = VK_PRValue; 20283 Type = S.Context.BoundMemberTy; 20284 } 20285 20286 // Function references aren't l-values in C. 20287 if (!S.getLangOpts().CPlusPlus) 20288 ValueKind = VK_PRValue; 20289 20290 // - variables 20291 } else if (isa<VarDecl>(VD)) { 20292 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 20293 Type = RefTy->getPointeeType(); 20294 } else if (Type->isFunctionType()) { 20295 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 20296 << VD << E->getSourceRange(); 20297 return ExprError(); 20298 } 20299 20300 // - nothing else 20301 } else { 20302 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 20303 << VD << E->getSourceRange(); 20304 return ExprError(); 20305 } 20306 20307 // Modifying the declaration like this is friendly to IR-gen but 20308 // also really dangerous. 20309 VD->setType(DestType); 20310 E->setType(Type); 20311 E->setValueKind(ValueKind); 20312 return E; 20313 } 20314 20315 /// Check a cast of an unknown-any type. We intentionally only 20316 /// trigger this for C-style casts. 20317 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 20318 Expr *CastExpr, CastKind &CastKind, 20319 ExprValueKind &VK, CXXCastPath &Path) { 20320 // The type we're casting to must be either void or complete. 20321 if (!CastType->isVoidType() && 20322 RequireCompleteType(TypeRange.getBegin(), CastType, 20323 diag::err_typecheck_cast_to_incomplete)) 20324 return ExprError(); 20325 20326 // Rewrite the casted expression from scratch. 20327 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 20328 if (!result.isUsable()) return ExprError(); 20329 20330 CastExpr = result.get(); 20331 VK = CastExpr->getValueKind(); 20332 CastKind = CK_NoOp; 20333 20334 return CastExpr; 20335 } 20336 20337 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 20338 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 20339 } 20340 20341 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 20342 Expr *arg, QualType ¶mType) { 20343 // If the syntactic form of the argument is not an explicit cast of 20344 // any sort, just do default argument promotion. 20345 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 20346 if (!castArg) { 20347 ExprResult result = DefaultArgumentPromotion(arg); 20348 if (result.isInvalid()) return ExprError(); 20349 paramType = result.get()->getType(); 20350 return result; 20351 } 20352 20353 // Otherwise, use the type that was written in the explicit cast. 20354 assert(!arg->hasPlaceholderType()); 20355 paramType = castArg->getTypeAsWritten(); 20356 20357 // Copy-initialize a parameter of that type. 20358 InitializedEntity entity = 20359 InitializedEntity::InitializeParameter(Context, paramType, 20360 /*consumed*/ false); 20361 return PerformCopyInitialization(entity, callLoc, arg); 20362 } 20363 20364 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 20365 Expr *orig = E; 20366 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 20367 while (true) { 20368 E = E->IgnoreParenImpCasts(); 20369 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 20370 E = call->getCallee(); 20371 diagID = diag::err_uncasted_call_of_unknown_any; 20372 } else { 20373 break; 20374 } 20375 } 20376 20377 SourceLocation loc; 20378 NamedDecl *d; 20379 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 20380 loc = ref->getLocation(); 20381 d = ref->getDecl(); 20382 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 20383 loc = mem->getMemberLoc(); 20384 d = mem->getMemberDecl(); 20385 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 20386 diagID = diag::err_uncasted_call_of_unknown_any; 20387 loc = msg->getSelectorStartLoc(); 20388 d = msg->getMethodDecl(); 20389 if (!d) { 20390 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 20391 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 20392 << orig->getSourceRange(); 20393 return ExprError(); 20394 } 20395 } else { 20396 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 20397 << E->getSourceRange(); 20398 return ExprError(); 20399 } 20400 20401 S.Diag(loc, diagID) << d << orig->getSourceRange(); 20402 20403 // Never recoverable. 20404 return ExprError(); 20405 } 20406 20407 /// Check for operands with placeholder types and complain if found. 20408 /// Returns ExprError() if there was an error and no recovery was possible. 20409 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 20410 if (!Context.isDependenceAllowed()) { 20411 // C cannot handle TypoExpr nodes on either side of a binop because it 20412 // doesn't handle dependent types properly, so make sure any TypoExprs have 20413 // been dealt with before checking the operands. 20414 ExprResult Result = CorrectDelayedTyposInExpr(E); 20415 if (!Result.isUsable()) return ExprError(); 20416 E = Result.get(); 20417 } 20418 20419 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 20420 if (!placeholderType) return E; 20421 20422 switch (placeholderType->getKind()) { 20423 20424 // Overloaded expressions. 20425 case BuiltinType::Overload: { 20426 // Try to resolve a single function template specialization. 20427 // This is obligatory. 20428 ExprResult Result = E; 20429 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 20430 return Result; 20431 20432 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 20433 // leaves Result unchanged on failure. 20434 Result = E; 20435 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 20436 return Result; 20437 20438 // If that failed, try to recover with a call. 20439 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 20440 /*complain*/ true); 20441 return Result; 20442 } 20443 20444 // Bound member functions. 20445 case BuiltinType::BoundMember: { 20446 ExprResult result = E; 20447 const Expr *BME = E->IgnoreParens(); 20448 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 20449 // Try to give a nicer diagnostic if it is a bound member that we recognize. 20450 if (isa<CXXPseudoDestructorExpr>(BME)) { 20451 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 20452 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 20453 if (ME->getMemberNameInfo().getName().getNameKind() == 20454 DeclarationName::CXXDestructorName) 20455 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 20456 } 20457 tryToRecoverWithCall(result, PD, 20458 /*complain*/ true); 20459 return result; 20460 } 20461 20462 // ARC unbridged casts. 20463 case BuiltinType::ARCUnbridgedCast: { 20464 Expr *realCast = stripARCUnbridgedCast(E); 20465 diagnoseARCUnbridgedCast(realCast); 20466 return realCast; 20467 } 20468 20469 // Expressions of unknown type. 20470 case BuiltinType::UnknownAny: 20471 return diagnoseUnknownAnyExpr(*this, E); 20472 20473 // Pseudo-objects. 20474 case BuiltinType::PseudoObject: 20475 return checkPseudoObjectRValue(E); 20476 20477 case BuiltinType::BuiltinFn: { 20478 // Accept __noop without parens by implicitly converting it to a call expr. 20479 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 20480 if (DRE) { 20481 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 20482 unsigned BuiltinID = FD->getBuiltinID(); 20483 if (BuiltinID == Builtin::BI__noop) { 20484 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 20485 CK_BuiltinFnToFnPtr) 20486 .get(); 20487 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 20488 VK_PRValue, SourceLocation(), 20489 FPOptionsOverride()); 20490 } 20491 20492 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) { 20493 // Any use of these other than a direct call is ill-formed as of C++20, 20494 // because they are not addressable functions. In earlier language 20495 // modes, warn and force an instantiation of the real body. 20496 Diag(E->getBeginLoc(), 20497 getLangOpts().CPlusPlus20 20498 ? diag::err_use_of_unaddressable_function 20499 : diag::warn_cxx20_compat_use_of_unaddressable_function); 20500 if (FD->isImplicitlyInstantiable()) { 20501 // Require a definition here because a normal attempt at 20502 // instantiation for a builtin will be ignored, and we won't try 20503 // again later. We assume that the definition of the template 20504 // precedes this use. 20505 InstantiateFunctionDefinition(E->getBeginLoc(), FD, 20506 /*Recursive=*/false, 20507 /*DefinitionRequired=*/true, 20508 /*AtEndOfTU=*/false); 20509 } 20510 // Produce a properly-typed reference to the function. 20511 CXXScopeSpec SS; 20512 SS.Adopt(DRE->getQualifierLoc()); 20513 TemplateArgumentListInfo TemplateArgs; 20514 DRE->copyTemplateArgumentsInto(TemplateArgs); 20515 return BuildDeclRefExpr( 20516 FD, FD->getType(), VK_LValue, DRE->getNameInfo(), 20517 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(), 20518 DRE->getTemplateKeywordLoc(), 20519 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr); 20520 } 20521 } 20522 20523 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 20524 return ExprError(); 20525 } 20526 20527 case BuiltinType::IncompleteMatrixIdx: 20528 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 20529 ->getRowIdx() 20530 ->getBeginLoc(), 20531 diag::err_matrix_incomplete_index); 20532 return ExprError(); 20533 20534 // Expressions of unknown type. 20535 case BuiltinType::OMPArraySection: 20536 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 20537 return ExprError(); 20538 20539 // Expressions of unknown type. 20540 case BuiltinType::OMPArrayShaping: 20541 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 20542 20543 case BuiltinType::OMPIterator: 20544 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 20545 20546 // Everything else should be impossible. 20547 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 20548 case BuiltinType::Id: 20549 #include "clang/Basic/OpenCLImageTypes.def" 20550 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 20551 case BuiltinType::Id: 20552 #include "clang/Basic/OpenCLExtensionTypes.def" 20553 #define SVE_TYPE(Name, Id, SingletonId) \ 20554 case BuiltinType::Id: 20555 #include "clang/Basic/AArch64SVEACLETypes.def" 20556 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 20557 case BuiltinType::Id: 20558 #include "clang/Basic/PPCTypes.def" 20559 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 20560 #include "clang/Basic/RISCVVTypes.def" 20561 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 20562 #define PLACEHOLDER_TYPE(Id, SingletonId) 20563 #include "clang/AST/BuiltinTypes.def" 20564 break; 20565 } 20566 20567 llvm_unreachable("invalid placeholder type!"); 20568 } 20569 20570 bool Sema::CheckCaseExpression(Expr *E) { 20571 if (E->isTypeDependent()) 20572 return true; 20573 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 20574 return E->getType()->isIntegralOrEnumerationType(); 20575 return false; 20576 } 20577 20578 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 20579 ExprResult 20580 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 20581 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 20582 "Unknown Objective-C Boolean value!"); 20583 QualType BoolT = Context.ObjCBuiltinBoolTy; 20584 if (!Context.getBOOLDecl()) { 20585 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 20586 Sema::LookupOrdinaryName); 20587 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 20588 NamedDecl *ND = Result.getFoundDecl(); 20589 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 20590 Context.setBOOLDecl(TD); 20591 } 20592 } 20593 if (Context.getBOOLDecl()) 20594 BoolT = Context.getBOOLType(); 20595 return new (Context) 20596 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 20597 } 20598 20599 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 20600 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 20601 SourceLocation RParen) { 20602 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { 20603 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 20604 return Spec.getPlatform() == Platform; 20605 }); 20606 // Transcribe the "ios" availability check to "maccatalyst" when compiling 20607 // for "maccatalyst" if "maccatalyst" is not specified. 20608 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { 20609 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 20610 return Spec.getPlatform() == "ios"; 20611 }); 20612 } 20613 if (Spec == AvailSpecs.end()) 20614 return None; 20615 return Spec->getVersion(); 20616 }; 20617 20618 VersionTuple Version; 20619 if (auto MaybeVersion = 20620 FindSpecVersion(Context.getTargetInfo().getPlatformName())) 20621 Version = *MaybeVersion; 20622 20623 // The use of `@available` in the enclosing context should be analyzed to 20624 // warn when it's used inappropriately (i.e. not if(@available)). 20625 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 20626 Context->HasPotentialAvailabilityViolations = true; 20627 20628 return new (Context) 20629 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 20630 } 20631 20632 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 20633 ArrayRef<Expr *> SubExprs, QualType T) { 20634 if (!Context.getLangOpts().RecoveryAST) 20635 return ExprError(); 20636 20637 if (isSFINAEContext()) 20638 return ExprError(); 20639 20640 if (T.isNull() || T->isUndeducedType() || 20641 !Context.getLangOpts().RecoveryASTType) 20642 // We don't know the concrete type, fallback to dependent type. 20643 T = Context.DependentTy; 20644 20645 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 20646 } 20647