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 else { 1689 // Because the controlling expression undergoes lvalue conversion, 1690 // array conversion, and function conversion, an association which is 1691 // of array type, function type, or is qualified can never be 1692 // reached. We will warn about this so users are less surprised by 1693 // the unreachable association. However, we don't have to handle 1694 // function types; that's not an object type, so it's handled above. 1695 unsigned Reason = 0; 1696 QualType QT = Types[i]->getType(); 1697 if (QT->isArrayType()) 1698 Reason = 1; 1699 else if (QT.hasQualifiers()) 1700 Reason = 2; 1701 1702 if (Reason) 1703 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1704 diag::warn_unreachable_association) 1705 << QT << (Reason - 1); 1706 } 1707 1708 if (D != 0) { 1709 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1710 << Types[i]->getTypeLoc().getSourceRange() 1711 << Types[i]->getType(); 1712 TypeErrorFound = true; 1713 } 1714 1715 // C11 6.5.1.1p2 "No two generic associations in the same generic 1716 // selection shall specify compatible types." 1717 for (unsigned j = i+1; j < NumAssocs; ++j) 1718 if (Types[j] && !Types[j]->getType()->isDependentType() && 1719 Context.typesAreCompatible(Types[i]->getType(), 1720 Types[j]->getType())) { 1721 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1722 diag::err_assoc_compatible_types) 1723 << Types[j]->getTypeLoc().getSourceRange() 1724 << Types[j]->getType() 1725 << Types[i]->getType(); 1726 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1727 diag::note_compat_assoc) 1728 << Types[i]->getTypeLoc().getSourceRange() 1729 << Types[i]->getType(); 1730 TypeErrorFound = true; 1731 } 1732 } 1733 } 1734 } 1735 if (TypeErrorFound) 1736 return ExprError(); 1737 1738 // If we determined that the generic selection is result-dependent, don't 1739 // try to compute the result expression. 1740 if (IsResultDependent) 1741 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1742 Exprs, DefaultLoc, RParenLoc, 1743 ContainsUnexpandedParameterPack); 1744 1745 SmallVector<unsigned, 1> CompatIndices; 1746 unsigned DefaultIndex = -1U; 1747 for (unsigned i = 0; i < NumAssocs; ++i) { 1748 if (!Types[i]) 1749 DefaultIndex = i; 1750 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1751 Types[i]->getType())) 1752 CompatIndices.push_back(i); 1753 } 1754 1755 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1756 // type compatible with at most one of the types named in its generic 1757 // association list." 1758 if (CompatIndices.size() > 1) { 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_multi_match) 1763 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1764 << (unsigned)CompatIndices.size(); 1765 for (unsigned I : CompatIndices) { 1766 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1767 diag::note_compat_assoc) 1768 << Types[I]->getTypeLoc().getSourceRange() 1769 << Types[I]->getType(); 1770 } 1771 return ExprError(); 1772 } 1773 1774 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1775 // its controlling expression shall have type compatible with exactly one of 1776 // the types named in its generic association list." 1777 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1778 // We strip parens here because the controlling expression is typically 1779 // parenthesized in macro definitions. 1780 ControllingExpr = ControllingExpr->IgnoreParens(); 1781 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1782 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1783 return ExprError(); 1784 } 1785 1786 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1787 // type name that is compatible with the type of the controlling expression, 1788 // then the result expression of the generic selection is the expression 1789 // in that generic association. Otherwise, the result expression of the 1790 // generic selection is the expression in the default generic association." 1791 unsigned ResultIndex = 1792 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1793 1794 return GenericSelectionExpr::Create( 1795 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1796 ContainsUnexpandedParameterPack, ResultIndex); 1797 } 1798 1799 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1800 /// location of the token and the offset of the ud-suffix within it. 1801 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1802 unsigned Offset) { 1803 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1804 S.getLangOpts()); 1805 } 1806 1807 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1808 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1809 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1810 IdentifierInfo *UDSuffix, 1811 SourceLocation UDSuffixLoc, 1812 ArrayRef<Expr*> Args, 1813 SourceLocation LitEndLoc) { 1814 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1815 1816 QualType ArgTy[2]; 1817 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1818 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1819 if (ArgTy[ArgIdx]->isArrayType()) 1820 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1821 } 1822 1823 DeclarationName OpName = 1824 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1825 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1826 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1827 1828 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1829 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1830 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1831 /*AllowStringTemplatePack*/ false, 1832 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1833 return ExprError(); 1834 1835 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1836 } 1837 1838 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1839 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1840 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1841 /// multiple tokens. However, the common case is that StringToks points to one 1842 /// string. 1843 /// 1844 ExprResult 1845 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1846 assert(!StringToks.empty() && "Must have at least one string!"); 1847 1848 StringLiteralParser Literal(StringToks, PP); 1849 if (Literal.hadError) 1850 return ExprError(); 1851 1852 SmallVector<SourceLocation, 4> StringTokLocs; 1853 for (const Token &Tok : StringToks) 1854 StringTokLocs.push_back(Tok.getLocation()); 1855 1856 QualType CharTy = Context.CharTy; 1857 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1858 if (Literal.isWide()) { 1859 CharTy = Context.getWideCharType(); 1860 Kind = StringLiteral::Wide; 1861 } else if (Literal.isUTF8()) { 1862 if (getLangOpts().Char8) 1863 CharTy = Context.Char8Ty; 1864 Kind = StringLiteral::UTF8; 1865 } else if (Literal.isUTF16()) { 1866 CharTy = Context.Char16Ty; 1867 Kind = StringLiteral::UTF16; 1868 } else if (Literal.isUTF32()) { 1869 CharTy = Context.Char32Ty; 1870 Kind = StringLiteral::UTF32; 1871 } else if (Literal.isPascal()) { 1872 CharTy = Context.UnsignedCharTy; 1873 } 1874 1875 // Warn on initializing an array of char from a u8 string literal; this 1876 // becomes ill-formed in C++2a. 1877 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1878 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1879 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1880 1881 // Create removals for all 'u8' prefixes in the string literal(s). This 1882 // ensures C++2a compatibility (but may change the program behavior when 1883 // built by non-Clang compilers for which the execution character set is 1884 // not always UTF-8). 1885 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1886 SourceLocation RemovalDiagLoc; 1887 for (const Token &Tok : StringToks) { 1888 if (Tok.getKind() == tok::utf8_string_literal) { 1889 if (RemovalDiagLoc.isInvalid()) 1890 RemovalDiagLoc = Tok.getLocation(); 1891 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1892 Tok.getLocation(), 1893 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1894 getSourceManager(), getLangOpts()))); 1895 } 1896 } 1897 Diag(RemovalDiagLoc, RemovalDiag); 1898 } 1899 1900 QualType StrTy = 1901 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1902 1903 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1904 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1905 Kind, Literal.Pascal, StrTy, 1906 &StringTokLocs[0], 1907 StringTokLocs.size()); 1908 if (Literal.getUDSuffix().empty()) 1909 return Lit; 1910 1911 // We're building a user-defined literal. 1912 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1913 SourceLocation UDSuffixLoc = 1914 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1915 Literal.getUDSuffixOffset()); 1916 1917 // Make sure we're allowed user-defined literals here. 1918 if (!UDLScope) 1919 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1920 1921 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1922 // operator "" X (str, len) 1923 QualType SizeType = Context.getSizeType(); 1924 1925 DeclarationName OpName = 1926 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1927 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1928 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1929 1930 QualType ArgTy[] = { 1931 Context.getArrayDecayedType(StrTy), SizeType 1932 }; 1933 1934 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1935 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1936 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1937 /*AllowStringTemplatePack*/ true, 1938 /*DiagnoseMissing*/ true, Lit)) { 1939 1940 case LOLR_Cooked: { 1941 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1942 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1943 StringTokLocs[0]); 1944 Expr *Args[] = { Lit, LenArg }; 1945 1946 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1947 } 1948 1949 case LOLR_Template: { 1950 TemplateArgumentListInfo ExplicitArgs; 1951 TemplateArgument Arg(Lit); 1952 TemplateArgumentLocInfo ArgInfo(Lit); 1953 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1954 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1955 &ExplicitArgs); 1956 } 1957 1958 case LOLR_StringTemplatePack: { 1959 TemplateArgumentListInfo ExplicitArgs; 1960 1961 unsigned CharBits = Context.getIntWidth(CharTy); 1962 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1963 llvm::APSInt Value(CharBits, CharIsUnsigned); 1964 1965 TemplateArgument TypeArg(CharTy); 1966 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1967 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1968 1969 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1970 Value = Lit->getCodeUnit(I); 1971 TemplateArgument Arg(Context, Value, CharTy); 1972 TemplateArgumentLocInfo ArgInfo; 1973 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1974 } 1975 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1976 &ExplicitArgs); 1977 } 1978 case LOLR_Raw: 1979 case LOLR_ErrorNoDiagnostic: 1980 llvm_unreachable("unexpected literal operator lookup result"); 1981 case LOLR_Error: 1982 return ExprError(); 1983 } 1984 llvm_unreachable("unexpected literal operator lookup result"); 1985 } 1986 1987 DeclRefExpr * 1988 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1989 SourceLocation Loc, 1990 const CXXScopeSpec *SS) { 1991 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1992 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1993 } 1994 1995 DeclRefExpr * 1996 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1997 const DeclarationNameInfo &NameInfo, 1998 const CXXScopeSpec *SS, NamedDecl *FoundD, 1999 SourceLocation TemplateKWLoc, 2000 const TemplateArgumentListInfo *TemplateArgs) { 2001 NestedNameSpecifierLoc NNS = 2002 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 2003 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 2004 TemplateArgs); 2005 } 2006 2007 // CUDA/HIP: Check whether a captured reference variable is referencing a 2008 // host variable in a device or host device lambda. 2009 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 2010 VarDecl *VD) { 2011 if (!S.getLangOpts().CUDA || !VD->hasInit()) 2012 return false; 2013 assert(VD->getType()->isReferenceType()); 2014 2015 // Check whether the reference variable is referencing a host variable. 2016 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 2017 if (!DRE) 2018 return false; 2019 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 2020 if (!Referee || !Referee->hasGlobalStorage() || 2021 Referee->hasAttr<CUDADeviceAttr>()) 2022 return false; 2023 2024 // Check whether the current function is a device or host device lambda. 2025 // Check whether the reference variable is a capture by getDeclContext() 2026 // since refersToEnclosingVariableOrCapture() is not ready at this point. 2027 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 2028 if (MD && MD->getParent()->isLambda() && 2029 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 2030 VD->getDeclContext() != MD) 2031 return true; 2032 2033 return false; 2034 } 2035 2036 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 2037 // A declaration named in an unevaluated operand never constitutes an odr-use. 2038 if (isUnevaluatedContext()) 2039 return NOUR_Unevaluated; 2040 2041 // C++2a [basic.def.odr]p4: 2042 // A variable x whose name appears as a potentially-evaluated expression e 2043 // is odr-used by e unless [...] x is a reference that is usable in 2044 // constant expressions. 2045 // CUDA/HIP: 2046 // If a reference variable referencing a host variable is captured in a 2047 // device or host device lambda, the value of the referee must be copied 2048 // to the capture and the reference variable must be treated as odr-use 2049 // since the value of the referee is not known at compile time and must 2050 // be loaded from the captured. 2051 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2052 if (VD->getType()->isReferenceType() && 2053 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 2054 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 2055 VD->isUsableInConstantExpressions(Context)) 2056 return NOUR_Constant; 2057 } 2058 2059 // All remaining non-variable cases constitute an odr-use. For variables, we 2060 // need to wait and see how the expression is used. 2061 return NOUR_None; 2062 } 2063 2064 /// BuildDeclRefExpr - Build an expression that references a 2065 /// declaration that does not require a closure capture. 2066 DeclRefExpr * 2067 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2068 const DeclarationNameInfo &NameInfo, 2069 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2070 SourceLocation TemplateKWLoc, 2071 const TemplateArgumentListInfo *TemplateArgs) { 2072 bool RefersToCapturedVariable = 2073 isa<VarDecl>(D) && 2074 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2075 2076 DeclRefExpr *E = DeclRefExpr::Create( 2077 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2078 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2079 MarkDeclRefReferenced(E); 2080 2081 // C++ [except.spec]p17: 2082 // An exception-specification is considered to be needed when: 2083 // - in an expression, the function is the unique lookup result or 2084 // the selected member of a set of overloaded functions. 2085 // 2086 // We delay doing this until after we've built the function reference and 2087 // marked it as used so that: 2088 // a) if the function is defaulted, we get errors from defining it before / 2089 // instead of errors from computing its exception specification, and 2090 // b) if the function is a defaulted comparison, we can use the body we 2091 // build when defining it as input to the exception specification 2092 // computation rather than computing a new body. 2093 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2094 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2095 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2096 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2097 } 2098 } 2099 2100 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2101 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2102 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2103 getCurFunction()->recordUseOfWeak(E); 2104 2105 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2106 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2107 FD = IFD->getAnonField(); 2108 if (FD) { 2109 UnusedPrivateFields.remove(FD); 2110 // Just in case we're building an illegal pointer-to-member. 2111 if (FD->isBitField()) 2112 E->setObjectKind(OK_BitField); 2113 } 2114 2115 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2116 // designates a bit-field. 2117 if (auto *BD = dyn_cast<BindingDecl>(D)) 2118 if (auto *BE = BD->getBinding()) 2119 E->setObjectKind(BE->getObjectKind()); 2120 2121 return E; 2122 } 2123 2124 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2125 /// possibly a list of template arguments. 2126 /// 2127 /// If this produces template arguments, it is permitted to call 2128 /// DecomposeTemplateName. 2129 /// 2130 /// This actually loses a lot of source location information for 2131 /// non-standard name kinds; we should consider preserving that in 2132 /// some way. 2133 void 2134 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2135 TemplateArgumentListInfo &Buffer, 2136 DeclarationNameInfo &NameInfo, 2137 const TemplateArgumentListInfo *&TemplateArgs) { 2138 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2139 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2140 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2141 2142 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2143 Id.TemplateId->NumArgs); 2144 translateTemplateArguments(TemplateArgsPtr, Buffer); 2145 2146 TemplateName TName = Id.TemplateId->Template.get(); 2147 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2148 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2149 TemplateArgs = &Buffer; 2150 } else { 2151 NameInfo = GetNameFromUnqualifiedId(Id); 2152 TemplateArgs = nullptr; 2153 } 2154 } 2155 2156 static void emitEmptyLookupTypoDiagnostic( 2157 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2158 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2159 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2160 DeclContext *Ctx = 2161 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2162 if (!TC) { 2163 // Emit a special diagnostic for failed member lookups. 2164 // FIXME: computing the declaration context might fail here (?) 2165 if (Ctx) 2166 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2167 << SS.getRange(); 2168 else 2169 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2170 return; 2171 } 2172 2173 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2174 bool DroppedSpecifier = 2175 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2176 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2177 ? diag::note_implicit_param_decl 2178 : diag::note_previous_decl; 2179 if (!Ctx) 2180 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2181 SemaRef.PDiag(NoteID)); 2182 else 2183 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2184 << Typo << Ctx << DroppedSpecifier 2185 << SS.getRange(), 2186 SemaRef.PDiag(NoteID)); 2187 } 2188 2189 /// Diagnose a lookup that found results in an enclosing class during error 2190 /// recovery. This usually indicates that the results were found in a dependent 2191 /// base class that could not be searched as part of a template definition. 2192 /// Always issues a diagnostic (though this may be only a warning in MS 2193 /// compatibility mode). 2194 /// 2195 /// Return \c true if the error is unrecoverable, or \c false if the caller 2196 /// should attempt to recover using these lookup results. 2197 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2198 // During a default argument instantiation the CurContext points 2199 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2200 // function parameter list, hence add an explicit check. 2201 bool isDefaultArgument = 2202 !CodeSynthesisContexts.empty() && 2203 CodeSynthesisContexts.back().Kind == 2204 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2205 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2206 bool isInstance = CurMethod && CurMethod->isInstance() && 2207 R.getNamingClass() == CurMethod->getParent() && 2208 !isDefaultArgument; 2209 2210 // There are two ways we can find a class-scope declaration during template 2211 // instantiation that we did not find in the template definition: if it is a 2212 // member of a dependent base class, or if it is declared after the point of 2213 // use in the same class. Distinguish these by comparing the class in which 2214 // the member was found to the naming class of the lookup. 2215 unsigned DiagID = diag::err_found_in_dependent_base; 2216 unsigned NoteID = diag::note_member_declared_at; 2217 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2218 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2219 : diag::err_found_later_in_class; 2220 } else if (getLangOpts().MSVCCompat) { 2221 DiagID = diag::ext_found_in_dependent_base; 2222 NoteID = diag::note_dependent_member_use; 2223 } 2224 2225 if (isInstance) { 2226 // Give a code modification hint to insert 'this->'. 2227 Diag(R.getNameLoc(), DiagID) 2228 << R.getLookupName() 2229 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2230 CheckCXXThisCapture(R.getNameLoc()); 2231 } else { 2232 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2233 // they're not shadowed). 2234 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2235 } 2236 2237 for (NamedDecl *D : R) 2238 Diag(D->getLocation(), NoteID); 2239 2240 // Return true if we are inside a default argument instantiation 2241 // and the found name refers to an instance member function, otherwise 2242 // the caller will try to create an implicit member call and this is wrong 2243 // for default arguments. 2244 // 2245 // FIXME: Is this special case necessary? We could allow the caller to 2246 // diagnose this. 2247 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2248 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2249 return true; 2250 } 2251 2252 // Tell the callee to try to recover. 2253 return false; 2254 } 2255 2256 /// Diagnose an empty lookup. 2257 /// 2258 /// \return false if new lookup candidates were found 2259 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2260 CorrectionCandidateCallback &CCC, 2261 TemplateArgumentListInfo *ExplicitTemplateArgs, 2262 ArrayRef<Expr *> Args, TypoExpr **Out) { 2263 DeclarationName Name = R.getLookupName(); 2264 2265 unsigned diagnostic = diag::err_undeclared_var_use; 2266 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2267 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2268 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2269 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2270 diagnostic = diag::err_undeclared_use; 2271 diagnostic_suggest = diag::err_undeclared_use_suggest; 2272 } 2273 2274 // If the original lookup was an unqualified lookup, fake an 2275 // unqualified lookup. This is useful when (for example) the 2276 // original lookup would not have found something because it was a 2277 // dependent name. 2278 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2279 while (DC) { 2280 if (isa<CXXRecordDecl>(DC)) { 2281 LookupQualifiedName(R, DC); 2282 2283 if (!R.empty()) { 2284 // Don't give errors about ambiguities in this lookup. 2285 R.suppressDiagnostics(); 2286 2287 // If there's a best viable function among the results, only mention 2288 // that one in the notes. 2289 OverloadCandidateSet Candidates(R.getNameLoc(), 2290 OverloadCandidateSet::CSK_Normal); 2291 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2292 OverloadCandidateSet::iterator Best; 2293 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2294 OR_Success) { 2295 R.clear(); 2296 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2297 R.resolveKind(); 2298 } 2299 2300 return DiagnoseDependentMemberLookup(R); 2301 } 2302 2303 R.clear(); 2304 } 2305 2306 DC = DC->getLookupParent(); 2307 } 2308 2309 // We didn't find anything, so try to correct for a typo. 2310 TypoCorrection Corrected; 2311 if (S && Out) { 2312 SourceLocation TypoLoc = R.getNameLoc(); 2313 assert(!ExplicitTemplateArgs && 2314 "Diagnosing an empty lookup with explicit template args!"); 2315 *Out = CorrectTypoDelayed( 2316 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2317 [=](const TypoCorrection &TC) { 2318 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2319 diagnostic, diagnostic_suggest); 2320 }, 2321 nullptr, CTK_ErrorRecovery); 2322 if (*Out) 2323 return true; 2324 } else if (S && 2325 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2326 S, &SS, CCC, CTK_ErrorRecovery))) { 2327 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2328 bool DroppedSpecifier = 2329 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2330 R.setLookupName(Corrected.getCorrection()); 2331 2332 bool AcceptableWithRecovery = false; 2333 bool AcceptableWithoutRecovery = false; 2334 NamedDecl *ND = Corrected.getFoundDecl(); 2335 if (ND) { 2336 if (Corrected.isOverloaded()) { 2337 OverloadCandidateSet OCS(R.getNameLoc(), 2338 OverloadCandidateSet::CSK_Normal); 2339 OverloadCandidateSet::iterator Best; 2340 for (NamedDecl *CD : Corrected) { 2341 if (FunctionTemplateDecl *FTD = 2342 dyn_cast<FunctionTemplateDecl>(CD)) 2343 AddTemplateOverloadCandidate( 2344 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2345 Args, OCS); 2346 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2347 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2348 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2349 Args, OCS); 2350 } 2351 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2352 case OR_Success: 2353 ND = Best->FoundDecl; 2354 Corrected.setCorrectionDecl(ND); 2355 break; 2356 default: 2357 // FIXME: Arbitrarily pick the first declaration for the note. 2358 Corrected.setCorrectionDecl(ND); 2359 break; 2360 } 2361 } 2362 R.addDecl(ND); 2363 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2364 CXXRecordDecl *Record = nullptr; 2365 if (Corrected.getCorrectionSpecifier()) { 2366 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2367 Record = Ty->getAsCXXRecordDecl(); 2368 } 2369 if (!Record) 2370 Record = cast<CXXRecordDecl>( 2371 ND->getDeclContext()->getRedeclContext()); 2372 R.setNamingClass(Record); 2373 } 2374 2375 auto *UnderlyingND = ND->getUnderlyingDecl(); 2376 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2377 isa<FunctionTemplateDecl>(UnderlyingND); 2378 // FIXME: If we ended up with a typo for a type name or 2379 // Objective-C class name, we're in trouble because the parser 2380 // is in the wrong place to recover. Suggest the typo 2381 // correction, but don't make it a fix-it since we're not going 2382 // to recover well anyway. 2383 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2384 getAsTypeTemplateDecl(UnderlyingND) || 2385 isa<ObjCInterfaceDecl>(UnderlyingND); 2386 } else { 2387 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2388 // because we aren't able to recover. 2389 AcceptableWithoutRecovery = true; 2390 } 2391 2392 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2393 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2394 ? diag::note_implicit_param_decl 2395 : diag::note_previous_decl; 2396 if (SS.isEmpty()) 2397 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2398 PDiag(NoteID), AcceptableWithRecovery); 2399 else 2400 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2401 << Name << computeDeclContext(SS, false) 2402 << DroppedSpecifier << SS.getRange(), 2403 PDiag(NoteID), AcceptableWithRecovery); 2404 2405 // Tell the callee whether to try to recover. 2406 return !AcceptableWithRecovery; 2407 } 2408 } 2409 R.clear(); 2410 2411 // Emit a special diagnostic for failed member lookups. 2412 // FIXME: computing the declaration context might fail here (?) 2413 if (!SS.isEmpty()) { 2414 Diag(R.getNameLoc(), diag::err_no_member) 2415 << Name << computeDeclContext(SS, false) 2416 << SS.getRange(); 2417 return true; 2418 } 2419 2420 // Give up, we can't recover. 2421 Diag(R.getNameLoc(), diagnostic) << Name; 2422 return true; 2423 } 2424 2425 /// In Microsoft mode, if we are inside a template class whose parent class has 2426 /// dependent base classes, and we can't resolve an unqualified identifier, then 2427 /// assume the identifier is a member of a dependent base class. We can only 2428 /// recover successfully in static methods, instance methods, and other contexts 2429 /// where 'this' is available. This doesn't precisely match MSVC's 2430 /// instantiation model, but it's close enough. 2431 static Expr * 2432 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2433 DeclarationNameInfo &NameInfo, 2434 SourceLocation TemplateKWLoc, 2435 const TemplateArgumentListInfo *TemplateArgs) { 2436 // Only try to recover from lookup into dependent bases in static methods or 2437 // contexts where 'this' is available. 2438 QualType ThisType = S.getCurrentThisType(); 2439 const CXXRecordDecl *RD = nullptr; 2440 if (!ThisType.isNull()) 2441 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2442 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2443 RD = MD->getParent(); 2444 if (!RD || !RD->hasAnyDependentBases()) 2445 return nullptr; 2446 2447 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2448 // is available, suggest inserting 'this->' as a fixit. 2449 SourceLocation Loc = NameInfo.getLoc(); 2450 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2451 DB << NameInfo.getName() << RD; 2452 2453 if (!ThisType.isNull()) { 2454 DB << FixItHint::CreateInsertion(Loc, "this->"); 2455 return CXXDependentScopeMemberExpr::Create( 2456 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2457 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2458 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2459 } 2460 2461 // Synthesize a fake NNS that points to the derived class. This will 2462 // perform name lookup during template instantiation. 2463 CXXScopeSpec SS; 2464 auto *NNS = 2465 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2466 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2467 return DependentScopeDeclRefExpr::Create( 2468 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2469 TemplateArgs); 2470 } 2471 2472 ExprResult 2473 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2474 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2475 bool HasTrailingLParen, bool IsAddressOfOperand, 2476 CorrectionCandidateCallback *CCC, 2477 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2478 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2479 "cannot be direct & operand and have a trailing lparen"); 2480 if (SS.isInvalid()) 2481 return ExprError(); 2482 2483 TemplateArgumentListInfo TemplateArgsBuffer; 2484 2485 // Decompose the UnqualifiedId into the following data. 2486 DeclarationNameInfo NameInfo; 2487 const TemplateArgumentListInfo *TemplateArgs; 2488 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2489 2490 DeclarationName Name = NameInfo.getName(); 2491 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2492 SourceLocation NameLoc = NameInfo.getLoc(); 2493 2494 if (II && II->isEditorPlaceholder()) { 2495 // FIXME: When typed placeholders are supported we can create a typed 2496 // placeholder expression node. 2497 return ExprError(); 2498 } 2499 2500 // C++ [temp.dep.expr]p3: 2501 // An id-expression is type-dependent if it contains: 2502 // -- an identifier that was declared with a dependent type, 2503 // (note: handled after lookup) 2504 // -- a template-id that is dependent, 2505 // (note: handled in BuildTemplateIdExpr) 2506 // -- a conversion-function-id that specifies a dependent type, 2507 // -- a nested-name-specifier that contains a class-name that 2508 // names a dependent type. 2509 // Determine whether this is a member of an unknown specialization; 2510 // we need to handle these differently. 2511 bool DependentID = false; 2512 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2513 Name.getCXXNameType()->isDependentType()) { 2514 DependentID = true; 2515 } else if (SS.isSet()) { 2516 if (DeclContext *DC = computeDeclContext(SS, false)) { 2517 if (RequireCompleteDeclContext(SS, DC)) 2518 return ExprError(); 2519 } else { 2520 DependentID = true; 2521 } 2522 } 2523 2524 if (DependentID) 2525 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2526 IsAddressOfOperand, TemplateArgs); 2527 2528 // Perform the required lookup. 2529 LookupResult R(*this, NameInfo, 2530 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2531 ? LookupObjCImplicitSelfParam 2532 : LookupOrdinaryName); 2533 if (TemplateKWLoc.isValid() || TemplateArgs) { 2534 // Lookup the template name again to correctly establish the context in 2535 // which it was found. This is really unfortunate as we already did the 2536 // lookup to determine that it was a template name in the first place. If 2537 // this becomes a performance hit, we can work harder to preserve those 2538 // results until we get here but it's likely not worth it. 2539 bool MemberOfUnknownSpecialization; 2540 AssumedTemplateKind AssumedTemplate; 2541 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2542 MemberOfUnknownSpecialization, TemplateKWLoc, 2543 &AssumedTemplate)) 2544 return ExprError(); 2545 2546 if (MemberOfUnknownSpecialization || 2547 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2548 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2549 IsAddressOfOperand, TemplateArgs); 2550 } else { 2551 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2552 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2553 2554 // If the result might be in a dependent base class, this is a dependent 2555 // id-expression. 2556 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2557 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2558 IsAddressOfOperand, TemplateArgs); 2559 2560 // If this reference is in an Objective-C method, then we need to do 2561 // some special Objective-C lookup, too. 2562 if (IvarLookupFollowUp) { 2563 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2564 if (E.isInvalid()) 2565 return ExprError(); 2566 2567 if (Expr *Ex = E.getAs<Expr>()) 2568 return Ex; 2569 } 2570 } 2571 2572 if (R.isAmbiguous()) 2573 return ExprError(); 2574 2575 // This could be an implicitly declared function reference if the language 2576 // mode allows it as a feature. 2577 if (R.empty() && HasTrailingLParen && II && 2578 getLangOpts().implicitFunctionsAllowed()) { 2579 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2580 if (D) R.addDecl(D); 2581 } 2582 2583 // Determine whether this name might be a candidate for 2584 // argument-dependent lookup. 2585 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2586 2587 if (R.empty() && !ADL) { 2588 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2589 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2590 TemplateKWLoc, TemplateArgs)) 2591 return E; 2592 } 2593 2594 // Don't diagnose an empty lookup for inline assembly. 2595 if (IsInlineAsmIdentifier) 2596 return ExprError(); 2597 2598 // If this name wasn't predeclared and if this is not a function 2599 // call, diagnose the problem. 2600 TypoExpr *TE = nullptr; 2601 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2602 : nullptr); 2603 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2604 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2605 "Typo correction callback misconfigured"); 2606 if (CCC) { 2607 // Make sure the callback knows what the typo being diagnosed is. 2608 CCC->setTypoName(II); 2609 if (SS.isValid()) 2610 CCC->setTypoNNS(SS.getScopeRep()); 2611 } 2612 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2613 // a template name, but we happen to have always already looked up the name 2614 // before we get here if it must be a template name. 2615 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2616 None, &TE)) { 2617 if (TE && KeywordReplacement) { 2618 auto &State = getTypoExprState(TE); 2619 auto BestTC = State.Consumer->getNextCorrection(); 2620 if (BestTC.isKeyword()) { 2621 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2622 if (State.DiagHandler) 2623 State.DiagHandler(BestTC); 2624 KeywordReplacement->startToken(); 2625 KeywordReplacement->setKind(II->getTokenID()); 2626 KeywordReplacement->setIdentifierInfo(II); 2627 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2628 // Clean up the state associated with the TypoExpr, since it has 2629 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2630 clearDelayedTypo(TE); 2631 // Signal that a correction to a keyword was performed by returning a 2632 // valid-but-null ExprResult. 2633 return (Expr*)nullptr; 2634 } 2635 State.Consumer->resetCorrectionStream(); 2636 } 2637 return TE ? TE : ExprError(); 2638 } 2639 2640 assert(!R.empty() && 2641 "DiagnoseEmptyLookup returned false but added no results"); 2642 2643 // If we found an Objective-C instance variable, let 2644 // LookupInObjCMethod build the appropriate expression to 2645 // reference the ivar. 2646 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2647 R.clear(); 2648 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2649 // In a hopelessly buggy code, Objective-C instance variable 2650 // lookup fails and no expression will be built to reference it. 2651 if (!E.isInvalid() && !E.get()) 2652 return ExprError(); 2653 return E; 2654 } 2655 } 2656 2657 // This is guaranteed from this point on. 2658 assert(!R.empty() || ADL); 2659 2660 // Check whether this might be a C++ implicit instance member access. 2661 // C++ [class.mfct.non-static]p3: 2662 // When an id-expression that is not part of a class member access 2663 // syntax and not used to form a pointer to member is used in the 2664 // body of a non-static member function of class X, if name lookup 2665 // resolves the name in the id-expression to a non-static non-type 2666 // member of some class C, the id-expression is transformed into a 2667 // class member access expression using (*this) as the 2668 // postfix-expression to the left of the . operator. 2669 // 2670 // But we don't actually need to do this for '&' operands if R 2671 // resolved to a function or overloaded function set, because the 2672 // expression is ill-formed if it actually works out to be a 2673 // non-static member function: 2674 // 2675 // C++ [expr.ref]p4: 2676 // Otherwise, if E1.E2 refers to a non-static member function. . . 2677 // [t]he expression can be used only as the left-hand operand of a 2678 // member function call. 2679 // 2680 // There are other safeguards against such uses, but it's important 2681 // to get this right here so that we don't end up making a 2682 // spuriously dependent expression if we're inside a dependent 2683 // instance method. 2684 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2685 bool MightBeImplicitMember; 2686 if (!IsAddressOfOperand) 2687 MightBeImplicitMember = true; 2688 else if (!SS.isEmpty()) 2689 MightBeImplicitMember = false; 2690 else if (R.isOverloadedResult()) 2691 MightBeImplicitMember = false; 2692 else if (R.isUnresolvableResult()) 2693 MightBeImplicitMember = true; 2694 else 2695 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2696 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2697 isa<MSPropertyDecl>(R.getFoundDecl()); 2698 2699 if (MightBeImplicitMember) 2700 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2701 R, TemplateArgs, S); 2702 } 2703 2704 if (TemplateArgs || TemplateKWLoc.isValid()) { 2705 2706 // In C++1y, if this is a variable template id, then check it 2707 // in BuildTemplateIdExpr(). 2708 // The single lookup result must be a variable template declaration. 2709 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2710 Id.TemplateId->Kind == TNK_Var_template) { 2711 assert(R.getAsSingle<VarTemplateDecl>() && 2712 "There should only be one declaration found."); 2713 } 2714 2715 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2716 } 2717 2718 return BuildDeclarationNameExpr(SS, R, ADL); 2719 } 2720 2721 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2722 /// declaration name, generally during template instantiation. 2723 /// There's a large number of things which don't need to be done along 2724 /// this path. 2725 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2726 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2727 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2728 DeclContext *DC = computeDeclContext(SS, false); 2729 if (!DC) 2730 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2731 NameInfo, /*TemplateArgs=*/nullptr); 2732 2733 if (RequireCompleteDeclContext(SS, DC)) 2734 return ExprError(); 2735 2736 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2737 LookupQualifiedName(R, DC); 2738 2739 if (R.isAmbiguous()) 2740 return ExprError(); 2741 2742 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2743 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2744 NameInfo, /*TemplateArgs=*/nullptr); 2745 2746 if (R.empty()) { 2747 // Don't diagnose problems with invalid record decl, the secondary no_member 2748 // diagnostic during template instantiation is likely bogus, e.g. if a class 2749 // is invalid because it's derived from an invalid base class, then missing 2750 // members were likely supposed to be inherited. 2751 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2752 if (CD->isInvalidDecl()) 2753 return ExprError(); 2754 Diag(NameInfo.getLoc(), diag::err_no_member) 2755 << NameInfo.getName() << DC << SS.getRange(); 2756 return ExprError(); 2757 } 2758 2759 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2760 // Diagnose a missing typename if this resolved unambiguously to a type in 2761 // a dependent context. If we can recover with a type, downgrade this to 2762 // a warning in Microsoft compatibility mode. 2763 unsigned DiagID = diag::err_typename_missing; 2764 if (RecoveryTSI && getLangOpts().MSVCCompat) 2765 DiagID = diag::ext_typename_missing; 2766 SourceLocation Loc = SS.getBeginLoc(); 2767 auto D = Diag(Loc, DiagID); 2768 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2769 << SourceRange(Loc, NameInfo.getEndLoc()); 2770 2771 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2772 // context. 2773 if (!RecoveryTSI) 2774 return ExprError(); 2775 2776 // Only issue the fixit if we're prepared to recover. 2777 D << FixItHint::CreateInsertion(Loc, "typename "); 2778 2779 // Recover by pretending this was an elaborated type. 2780 QualType Ty = Context.getTypeDeclType(TD); 2781 TypeLocBuilder TLB; 2782 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2783 2784 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2785 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2786 QTL.setElaboratedKeywordLoc(SourceLocation()); 2787 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2788 2789 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2790 2791 return ExprEmpty(); 2792 } 2793 2794 // Defend against this resolving to an implicit member access. We usually 2795 // won't get here if this might be a legitimate a class member (we end up in 2796 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2797 // a pointer-to-member or in an unevaluated context in C++11. 2798 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2799 return BuildPossibleImplicitMemberExpr(SS, 2800 /*TemplateKWLoc=*/SourceLocation(), 2801 R, /*TemplateArgs=*/nullptr, S); 2802 2803 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2804 } 2805 2806 /// The parser has read a name in, and Sema has detected that we're currently 2807 /// inside an ObjC method. Perform some additional checks and determine if we 2808 /// should form a reference to an ivar. 2809 /// 2810 /// Ideally, most of this would be done by lookup, but there's 2811 /// actually quite a lot of extra work involved. 2812 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2813 IdentifierInfo *II) { 2814 SourceLocation Loc = Lookup.getNameLoc(); 2815 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2816 2817 // Check for error condition which is already reported. 2818 if (!CurMethod) 2819 return DeclResult(true); 2820 2821 // There are two cases to handle here. 1) scoped lookup could have failed, 2822 // in which case we should look for an ivar. 2) scoped lookup could have 2823 // found a decl, but that decl is outside the current instance method (i.e. 2824 // a global variable). In these two cases, we do a lookup for an ivar with 2825 // this name, if the lookup sucedes, we replace it our current decl. 2826 2827 // If we're in a class method, we don't normally want to look for 2828 // ivars. But if we don't find anything else, and there's an 2829 // ivar, that's an error. 2830 bool IsClassMethod = CurMethod->isClassMethod(); 2831 2832 bool LookForIvars; 2833 if (Lookup.empty()) 2834 LookForIvars = true; 2835 else if (IsClassMethod) 2836 LookForIvars = false; 2837 else 2838 LookForIvars = (Lookup.isSingleResult() && 2839 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2840 ObjCInterfaceDecl *IFace = nullptr; 2841 if (LookForIvars) { 2842 IFace = CurMethod->getClassInterface(); 2843 ObjCInterfaceDecl *ClassDeclared; 2844 ObjCIvarDecl *IV = nullptr; 2845 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2846 // Diagnose using an ivar in a class method. 2847 if (IsClassMethod) { 2848 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2849 return DeclResult(true); 2850 } 2851 2852 // Diagnose the use of an ivar outside of the declaring class. 2853 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2854 !declaresSameEntity(ClassDeclared, IFace) && 2855 !getLangOpts().DebuggerSupport) 2856 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2857 2858 // Success. 2859 return IV; 2860 } 2861 } else if (CurMethod->isInstanceMethod()) { 2862 // We should warn if a local variable hides an ivar. 2863 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2864 ObjCInterfaceDecl *ClassDeclared; 2865 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2866 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2867 declaresSameEntity(IFace, ClassDeclared)) 2868 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2869 } 2870 } 2871 } else if (Lookup.isSingleResult() && 2872 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2873 // If accessing a stand-alone ivar in a class method, this is an error. 2874 if (const ObjCIvarDecl *IV = 2875 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2876 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2877 return DeclResult(true); 2878 } 2879 } 2880 2881 // Didn't encounter an error, didn't find an ivar. 2882 return DeclResult(false); 2883 } 2884 2885 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2886 ObjCIvarDecl *IV) { 2887 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2888 assert(CurMethod && CurMethod->isInstanceMethod() && 2889 "should not reference ivar from this context"); 2890 2891 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2892 assert(IFace && "should not reference ivar from this context"); 2893 2894 // If we're referencing an invalid decl, just return this as a silent 2895 // error node. The error diagnostic was already emitted on the decl. 2896 if (IV->isInvalidDecl()) 2897 return ExprError(); 2898 2899 // Check if referencing a field with __attribute__((deprecated)). 2900 if (DiagnoseUseOfDecl(IV, Loc)) 2901 return ExprError(); 2902 2903 // FIXME: This should use a new expr for a direct reference, don't 2904 // turn this into Self->ivar, just return a BareIVarExpr or something. 2905 IdentifierInfo &II = Context.Idents.get("self"); 2906 UnqualifiedId SelfName; 2907 SelfName.setImplicitSelfParam(&II); 2908 CXXScopeSpec SelfScopeSpec; 2909 SourceLocation TemplateKWLoc; 2910 ExprResult SelfExpr = 2911 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2912 /*HasTrailingLParen=*/false, 2913 /*IsAddressOfOperand=*/false); 2914 if (SelfExpr.isInvalid()) 2915 return ExprError(); 2916 2917 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2918 if (SelfExpr.isInvalid()) 2919 return ExprError(); 2920 2921 MarkAnyDeclReferenced(Loc, IV, true); 2922 2923 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2924 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2925 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2926 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2927 2928 ObjCIvarRefExpr *Result = new (Context) 2929 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2930 IV->getLocation(), SelfExpr.get(), true, true); 2931 2932 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2933 if (!isUnevaluatedContext() && 2934 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2935 getCurFunction()->recordUseOfWeak(Result); 2936 } 2937 if (getLangOpts().ObjCAutoRefCount) 2938 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2939 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2940 2941 return Result; 2942 } 2943 2944 /// The parser has read a name in, and Sema has detected that we're currently 2945 /// inside an ObjC method. Perform some additional checks and determine if we 2946 /// should form a reference to an ivar. If so, build an expression referencing 2947 /// that ivar. 2948 ExprResult 2949 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2950 IdentifierInfo *II, bool AllowBuiltinCreation) { 2951 // FIXME: Integrate this lookup step into LookupParsedName. 2952 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2953 if (Ivar.isInvalid()) 2954 return ExprError(); 2955 if (Ivar.isUsable()) 2956 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2957 cast<ObjCIvarDecl>(Ivar.get())); 2958 2959 if (Lookup.empty() && II && AllowBuiltinCreation) 2960 LookupBuiltin(Lookup); 2961 2962 // Sentinel value saying that we didn't do anything special. 2963 return ExprResult(false); 2964 } 2965 2966 /// Cast a base object to a member's actual type. 2967 /// 2968 /// There are two relevant checks: 2969 /// 2970 /// C++ [class.access.base]p7: 2971 /// 2972 /// If a class member access operator [...] is used to access a non-static 2973 /// data member or non-static member function, the reference is ill-formed if 2974 /// the left operand [...] cannot be implicitly converted to a pointer to the 2975 /// naming class of the right operand. 2976 /// 2977 /// C++ [expr.ref]p7: 2978 /// 2979 /// If E2 is a non-static data member or a non-static member function, the 2980 /// program is ill-formed if the class of which E2 is directly a member is an 2981 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2982 /// 2983 /// Note that the latter check does not consider access; the access of the 2984 /// "real" base class is checked as appropriate when checking the access of the 2985 /// member name. 2986 ExprResult 2987 Sema::PerformObjectMemberConversion(Expr *From, 2988 NestedNameSpecifier *Qualifier, 2989 NamedDecl *FoundDecl, 2990 NamedDecl *Member) { 2991 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2992 if (!RD) 2993 return From; 2994 2995 QualType DestRecordType; 2996 QualType DestType; 2997 QualType FromRecordType; 2998 QualType FromType = From->getType(); 2999 bool PointerConversions = false; 3000 if (isa<FieldDecl>(Member)) { 3001 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 3002 auto FromPtrType = FromType->getAs<PointerType>(); 3003 DestRecordType = Context.getAddrSpaceQualType( 3004 DestRecordType, FromPtrType 3005 ? FromType->getPointeeType().getAddressSpace() 3006 : FromType.getAddressSpace()); 3007 3008 if (FromPtrType) { 3009 DestType = Context.getPointerType(DestRecordType); 3010 FromRecordType = FromPtrType->getPointeeType(); 3011 PointerConversions = true; 3012 } else { 3013 DestType = DestRecordType; 3014 FromRecordType = FromType; 3015 } 3016 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 3017 if (Method->isStatic()) 3018 return From; 3019 3020 DestType = Method->getThisType(); 3021 DestRecordType = DestType->getPointeeType(); 3022 3023 if (FromType->getAs<PointerType>()) { 3024 FromRecordType = FromType->getPointeeType(); 3025 PointerConversions = true; 3026 } else { 3027 FromRecordType = FromType; 3028 DestType = DestRecordType; 3029 } 3030 3031 LangAS FromAS = FromRecordType.getAddressSpace(); 3032 LangAS DestAS = DestRecordType.getAddressSpace(); 3033 if (FromAS != DestAS) { 3034 QualType FromRecordTypeWithoutAS = 3035 Context.removeAddrSpaceQualType(FromRecordType); 3036 QualType FromTypeWithDestAS = 3037 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 3038 if (PointerConversions) 3039 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 3040 From = ImpCastExprToType(From, FromTypeWithDestAS, 3041 CK_AddressSpaceConversion, From->getValueKind()) 3042 .get(); 3043 } 3044 } else { 3045 // No conversion necessary. 3046 return From; 3047 } 3048 3049 if (DestType->isDependentType() || FromType->isDependentType()) 3050 return From; 3051 3052 // If the unqualified types are the same, no conversion is necessary. 3053 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3054 return From; 3055 3056 SourceRange FromRange = From->getSourceRange(); 3057 SourceLocation FromLoc = FromRange.getBegin(); 3058 3059 ExprValueKind VK = From->getValueKind(); 3060 3061 // C++ [class.member.lookup]p8: 3062 // [...] Ambiguities can often be resolved by qualifying a name with its 3063 // class name. 3064 // 3065 // If the member was a qualified name and the qualified referred to a 3066 // specific base subobject type, we'll cast to that intermediate type 3067 // first and then to the object in which the member is declared. That allows 3068 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3069 // 3070 // class Base { public: int x; }; 3071 // class Derived1 : public Base { }; 3072 // class Derived2 : public Base { }; 3073 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3074 // 3075 // void VeryDerived::f() { 3076 // x = 17; // error: ambiguous base subobjects 3077 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3078 // } 3079 if (Qualifier && Qualifier->getAsType()) { 3080 QualType QType = QualType(Qualifier->getAsType(), 0); 3081 assert(QType->isRecordType() && "lookup done with non-record type"); 3082 3083 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0); 3084 3085 // In C++98, the qualifier type doesn't actually have to be a base 3086 // type of the object type, in which case we just ignore it. 3087 // Otherwise build the appropriate casts. 3088 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3089 CXXCastPath BasePath; 3090 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3091 FromLoc, FromRange, &BasePath)) 3092 return ExprError(); 3093 3094 if (PointerConversions) 3095 QType = Context.getPointerType(QType); 3096 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3097 VK, &BasePath).get(); 3098 3099 FromType = QType; 3100 FromRecordType = QRecordType; 3101 3102 // If the qualifier type was the same as the destination type, 3103 // we're done. 3104 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3105 return From; 3106 } 3107 } 3108 3109 CXXCastPath BasePath; 3110 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3111 FromLoc, FromRange, &BasePath, 3112 /*IgnoreAccess=*/true)) 3113 return ExprError(); 3114 3115 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3116 VK, &BasePath); 3117 } 3118 3119 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3120 const LookupResult &R, 3121 bool HasTrailingLParen) { 3122 // Only when used directly as the postfix-expression of a call. 3123 if (!HasTrailingLParen) 3124 return false; 3125 3126 // Never if a scope specifier was provided. 3127 if (SS.isSet()) 3128 return false; 3129 3130 // Only in C++ or ObjC++. 3131 if (!getLangOpts().CPlusPlus) 3132 return false; 3133 3134 // Turn off ADL when we find certain kinds of declarations during 3135 // normal lookup: 3136 for (NamedDecl *D : R) { 3137 // C++0x [basic.lookup.argdep]p3: 3138 // -- a declaration of a class member 3139 // Since using decls preserve this property, we check this on the 3140 // original decl. 3141 if (D->isCXXClassMember()) 3142 return false; 3143 3144 // C++0x [basic.lookup.argdep]p3: 3145 // -- a block-scope function declaration that is not a 3146 // using-declaration 3147 // NOTE: we also trigger this for function templates (in fact, we 3148 // don't check the decl type at all, since all other decl types 3149 // turn off ADL anyway). 3150 if (isa<UsingShadowDecl>(D)) 3151 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3152 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3153 return false; 3154 3155 // C++0x [basic.lookup.argdep]p3: 3156 // -- a declaration that is neither a function or a function 3157 // template 3158 // And also for builtin functions. 3159 if (isa<FunctionDecl>(D)) { 3160 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3161 3162 // But also builtin functions. 3163 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3164 return false; 3165 } else if (!isa<FunctionTemplateDecl>(D)) 3166 return false; 3167 } 3168 3169 return true; 3170 } 3171 3172 3173 /// Diagnoses obvious problems with the use of the given declaration 3174 /// as an expression. This is only actually called for lookups that 3175 /// were not overloaded, and it doesn't promise that the declaration 3176 /// will in fact be used. 3177 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3178 if (D->isInvalidDecl()) 3179 return true; 3180 3181 if (isa<TypedefNameDecl>(D)) { 3182 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3183 return true; 3184 } 3185 3186 if (isa<ObjCInterfaceDecl>(D)) { 3187 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3188 return true; 3189 } 3190 3191 if (isa<NamespaceDecl>(D)) { 3192 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3193 return true; 3194 } 3195 3196 return false; 3197 } 3198 3199 // Certain multiversion types should be treated as overloaded even when there is 3200 // only one result. 3201 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3202 assert(R.isSingleResult() && "Expected only a single result"); 3203 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3204 return FD && 3205 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3206 } 3207 3208 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3209 LookupResult &R, bool NeedsADL, 3210 bool AcceptInvalidDecl) { 3211 // If this is a single, fully-resolved result and we don't need ADL, 3212 // just build an ordinary singleton decl ref. 3213 if (!NeedsADL && R.isSingleResult() && 3214 !R.getAsSingle<FunctionTemplateDecl>() && 3215 !ShouldLookupResultBeMultiVersionOverload(R)) 3216 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3217 R.getRepresentativeDecl(), nullptr, 3218 AcceptInvalidDecl); 3219 3220 // We only need to check the declaration if there's exactly one 3221 // result, because in the overloaded case the results can only be 3222 // functions and function templates. 3223 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3224 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3225 return ExprError(); 3226 3227 // Otherwise, just build an unresolved lookup expression. Suppress 3228 // any lookup-related diagnostics; we'll hash these out later, when 3229 // we've picked a target. 3230 R.suppressDiagnostics(); 3231 3232 UnresolvedLookupExpr *ULE 3233 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3234 SS.getWithLocInContext(Context), 3235 R.getLookupNameInfo(), 3236 NeedsADL, R.isOverloadedResult(), 3237 R.begin(), R.end()); 3238 3239 return ULE; 3240 } 3241 3242 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3243 ValueDecl *var); 3244 3245 /// Complete semantic analysis for a reference to the given declaration. 3246 ExprResult Sema::BuildDeclarationNameExpr( 3247 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3248 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3249 bool AcceptInvalidDecl) { 3250 assert(D && "Cannot refer to a NULL declaration"); 3251 assert(!isa<FunctionTemplateDecl>(D) && 3252 "Cannot refer unambiguously to a function template"); 3253 3254 SourceLocation Loc = NameInfo.getLoc(); 3255 if (CheckDeclInExpr(*this, Loc, D)) { 3256 // Recovery from invalid cases (e.g. D is an invalid Decl). 3257 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up 3258 // diagnostics, as invalid decls use int as a fallback type. 3259 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {}); 3260 } 3261 3262 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3263 // Specifically diagnose references to class templates that are missing 3264 // a template argument list. 3265 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3266 return ExprError(); 3267 } 3268 3269 // Make sure that we're referring to a value. 3270 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { 3271 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange(); 3272 Diag(D->getLocation(), diag::note_declared_at); 3273 return ExprError(); 3274 } 3275 3276 // Check whether this declaration can be used. Note that we suppress 3277 // this check when we're going to perform argument-dependent lookup 3278 // on this function name, because this might not be the function 3279 // that overload resolution actually selects. 3280 if (DiagnoseUseOfDecl(D, Loc)) 3281 return ExprError(); 3282 3283 auto *VD = cast<ValueDecl>(D); 3284 3285 // Only create DeclRefExpr's for valid Decl's. 3286 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3287 return ExprError(); 3288 3289 // Handle members of anonymous structs and unions. If we got here, 3290 // and the reference is to a class member indirect field, then this 3291 // must be the subject of a pointer-to-member expression. 3292 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3293 if (!indirectField->isCXXClassMember()) 3294 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3295 indirectField); 3296 3297 QualType type = VD->getType(); 3298 if (type.isNull()) 3299 return ExprError(); 3300 ExprValueKind valueKind = VK_PRValue; 3301 3302 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3303 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3304 // is expanded by some outer '...' in the context of the use. 3305 type = type.getNonPackExpansionType(); 3306 3307 switch (D->getKind()) { 3308 // Ignore all the non-ValueDecl kinds. 3309 #define ABSTRACT_DECL(kind) 3310 #define VALUE(type, base) 3311 #define DECL(type, base) case Decl::type: 3312 #include "clang/AST/DeclNodes.inc" 3313 llvm_unreachable("invalid value decl kind"); 3314 3315 // These shouldn't make it here. 3316 case Decl::ObjCAtDefsField: 3317 llvm_unreachable("forming non-member reference to ivar?"); 3318 3319 // Enum constants are always r-values and never references. 3320 // Unresolved using declarations are dependent. 3321 case Decl::EnumConstant: 3322 case Decl::UnresolvedUsingValue: 3323 case Decl::OMPDeclareReduction: 3324 case Decl::OMPDeclareMapper: 3325 valueKind = VK_PRValue; 3326 break; 3327 3328 // Fields and indirect fields that got here must be for 3329 // pointer-to-member expressions; we just call them l-values for 3330 // internal consistency, because this subexpression doesn't really 3331 // exist in the high-level semantics. 3332 case Decl::Field: 3333 case Decl::IndirectField: 3334 case Decl::ObjCIvar: 3335 assert(getLangOpts().CPlusPlus && "building reference to field in C?"); 3336 3337 // These can't have reference type in well-formed programs, but 3338 // for internal consistency we do this anyway. 3339 type = type.getNonReferenceType(); 3340 valueKind = VK_LValue; 3341 break; 3342 3343 // Non-type template parameters are either l-values or r-values 3344 // depending on the type. 3345 case Decl::NonTypeTemplateParm: { 3346 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3347 type = reftype->getPointeeType(); 3348 valueKind = VK_LValue; // even if the parameter is an r-value reference 3349 break; 3350 } 3351 3352 // [expr.prim.id.unqual]p2: 3353 // If the entity is a template parameter object for a template 3354 // parameter of type T, the type of the expression is const T. 3355 // [...] The expression is an lvalue if the entity is a [...] template 3356 // parameter object. 3357 if (type->isRecordType()) { 3358 type = type.getUnqualifiedType().withConst(); 3359 valueKind = VK_LValue; 3360 break; 3361 } 3362 3363 // For non-references, we need to strip qualifiers just in case 3364 // the template parameter was declared as 'const int' or whatever. 3365 valueKind = VK_PRValue; 3366 type = type.getUnqualifiedType(); 3367 break; 3368 } 3369 3370 case Decl::Var: 3371 case Decl::VarTemplateSpecialization: 3372 case Decl::VarTemplatePartialSpecialization: 3373 case Decl::Decomposition: 3374 case Decl::OMPCapturedExpr: 3375 // In C, "extern void blah;" is valid and is an r-value. 3376 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && 3377 type->isVoidType()) { 3378 valueKind = VK_PRValue; 3379 break; 3380 } 3381 LLVM_FALLTHROUGH; 3382 3383 case Decl::ImplicitParam: 3384 case Decl::ParmVar: { 3385 // These are always l-values. 3386 valueKind = VK_LValue; 3387 type = type.getNonReferenceType(); 3388 3389 // FIXME: Does the addition of const really only apply in 3390 // potentially-evaluated contexts? Since the variable isn't actually 3391 // captured in an unevaluated context, it seems that the answer is no. 3392 if (!isUnevaluatedContext()) { 3393 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3394 if (!CapturedType.isNull()) 3395 type = CapturedType; 3396 } 3397 3398 break; 3399 } 3400 3401 case Decl::Binding: { 3402 // These are always lvalues. 3403 valueKind = VK_LValue; 3404 type = type.getNonReferenceType(); 3405 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3406 // decides how that's supposed to work. 3407 auto *BD = cast<BindingDecl>(VD); 3408 if (BD->getDeclContext() != CurContext) { 3409 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3410 if (DD && DD->hasLocalStorage()) 3411 diagnoseUncapturableValueReference(*this, Loc, BD); 3412 } 3413 break; 3414 } 3415 3416 case Decl::Function: { 3417 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3418 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) { 3419 type = Context.BuiltinFnTy; 3420 valueKind = VK_PRValue; 3421 break; 3422 } 3423 } 3424 3425 const FunctionType *fty = type->castAs<FunctionType>(); 3426 3427 // If we're referring to a function with an __unknown_anytype 3428 // result type, make the entire expression __unknown_anytype. 3429 if (fty->getReturnType() == Context.UnknownAnyTy) { 3430 type = Context.UnknownAnyTy; 3431 valueKind = VK_PRValue; 3432 break; 3433 } 3434 3435 // Functions are l-values in C++. 3436 if (getLangOpts().CPlusPlus) { 3437 valueKind = VK_LValue; 3438 break; 3439 } 3440 3441 // C99 DR 316 says that, if a function type comes from a 3442 // function definition (without a prototype), that type is only 3443 // used for checking compatibility. Therefore, when referencing 3444 // the function, we pretend that we don't have the full function 3445 // type. 3446 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty)) 3447 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3448 fty->getExtInfo()); 3449 3450 // Functions are r-values in C. 3451 valueKind = VK_PRValue; 3452 break; 3453 } 3454 3455 case Decl::CXXDeductionGuide: 3456 llvm_unreachable("building reference to deduction guide"); 3457 3458 case Decl::MSProperty: 3459 case Decl::MSGuid: 3460 case Decl::TemplateParamObject: 3461 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3462 // capture in OpenMP, or duplicated between host and device? 3463 valueKind = VK_LValue; 3464 break; 3465 3466 case Decl::UnnamedGlobalConstant: 3467 valueKind = VK_LValue; 3468 break; 3469 3470 case Decl::CXXMethod: 3471 // If we're referring to a method with an __unknown_anytype 3472 // result type, make the entire expression __unknown_anytype. 3473 // This should only be possible with a type written directly. 3474 if (const FunctionProtoType *proto = 3475 dyn_cast<FunctionProtoType>(VD->getType())) 3476 if (proto->getReturnType() == Context.UnknownAnyTy) { 3477 type = Context.UnknownAnyTy; 3478 valueKind = VK_PRValue; 3479 break; 3480 } 3481 3482 // C++ methods are l-values if static, r-values if non-static. 3483 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3484 valueKind = VK_LValue; 3485 break; 3486 } 3487 LLVM_FALLTHROUGH; 3488 3489 case Decl::CXXConversion: 3490 case Decl::CXXDestructor: 3491 case Decl::CXXConstructor: 3492 valueKind = VK_PRValue; 3493 break; 3494 } 3495 3496 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3497 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3498 TemplateArgs); 3499 } 3500 3501 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3502 SmallString<32> &Target) { 3503 Target.resize(CharByteWidth * (Source.size() + 1)); 3504 char *ResultPtr = &Target[0]; 3505 const llvm::UTF8 *ErrorPtr; 3506 bool success = 3507 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3508 (void)success; 3509 assert(success); 3510 Target.resize(ResultPtr - &Target[0]); 3511 } 3512 3513 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3514 PredefinedExpr::IdentKind IK) { 3515 // Pick the current block, lambda, captured statement or function. 3516 Decl *currentDecl = nullptr; 3517 if (const BlockScopeInfo *BSI = getCurBlock()) 3518 currentDecl = BSI->TheDecl; 3519 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3520 currentDecl = LSI->CallOperator; 3521 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3522 currentDecl = CSI->TheCapturedDecl; 3523 else 3524 currentDecl = getCurFunctionOrMethodDecl(); 3525 3526 if (!currentDecl) { 3527 Diag(Loc, diag::ext_predef_outside_function); 3528 currentDecl = Context.getTranslationUnitDecl(); 3529 } 3530 3531 QualType ResTy; 3532 StringLiteral *SL = nullptr; 3533 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3534 ResTy = Context.DependentTy; 3535 else { 3536 // Pre-defined identifiers are of type char[x], where x is the length of 3537 // the string. 3538 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3539 unsigned Length = Str.length(); 3540 3541 llvm::APInt LengthI(32, Length + 1); 3542 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3543 ResTy = 3544 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3545 SmallString<32> RawChars; 3546 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3547 Str, RawChars); 3548 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3549 ArrayType::Normal, 3550 /*IndexTypeQuals*/ 0); 3551 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3552 /*Pascal*/ false, ResTy, Loc); 3553 } else { 3554 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3555 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3556 ArrayType::Normal, 3557 /*IndexTypeQuals*/ 0); 3558 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3559 /*Pascal*/ false, ResTy, Loc); 3560 } 3561 } 3562 3563 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3564 } 3565 3566 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3567 SourceLocation LParen, 3568 SourceLocation RParen, 3569 TypeSourceInfo *TSI) { 3570 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); 3571 } 3572 3573 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3574 SourceLocation LParen, 3575 SourceLocation RParen, 3576 ParsedType ParsedTy) { 3577 TypeSourceInfo *TSI = nullptr; 3578 QualType Ty = GetTypeFromParser(ParsedTy, &TSI); 3579 3580 if (Ty.isNull()) 3581 return ExprError(); 3582 if (!TSI) 3583 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); 3584 3585 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); 3586 } 3587 3588 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3589 PredefinedExpr::IdentKind IK; 3590 3591 switch (Kind) { 3592 default: llvm_unreachable("Unknown simple primary expr!"); 3593 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3594 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3595 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3596 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3597 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3598 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3599 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3600 } 3601 3602 return BuildPredefinedExpr(Loc, IK); 3603 } 3604 3605 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3606 SmallString<16> CharBuffer; 3607 bool Invalid = false; 3608 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3609 if (Invalid) 3610 return ExprError(); 3611 3612 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3613 PP, Tok.getKind()); 3614 if (Literal.hadError()) 3615 return ExprError(); 3616 3617 QualType Ty; 3618 if (Literal.isWide()) 3619 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3620 else if (Literal.isUTF8() && getLangOpts().C2x) 3621 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C2x 3622 else if (Literal.isUTF8() && getLangOpts().Char8) 3623 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3624 else if (Literal.isUTF16()) 3625 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3626 else if (Literal.isUTF32()) 3627 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3628 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3629 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3630 else 3631 Ty = Context.CharTy; // 'x' -> char in C++; 3632 // u8'x' -> char in C11-C17 and in C++ without char8_t. 3633 3634 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3635 if (Literal.isWide()) 3636 Kind = CharacterLiteral::Wide; 3637 else if (Literal.isUTF16()) 3638 Kind = CharacterLiteral::UTF16; 3639 else if (Literal.isUTF32()) 3640 Kind = CharacterLiteral::UTF32; 3641 else if (Literal.isUTF8()) 3642 Kind = CharacterLiteral::UTF8; 3643 3644 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3645 Tok.getLocation()); 3646 3647 if (Literal.getUDSuffix().empty()) 3648 return Lit; 3649 3650 // We're building a user-defined literal. 3651 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3652 SourceLocation UDSuffixLoc = 3653 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3654 3655 // Make sure we're allowed user-defined literals here. 3656 if (!UDLScope) 3657 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3658 3659 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3660 // operator "" X (ch) 3661 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3662 Lit, Tok.getLocation()); 3663 } 3664 3665 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3666 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3667 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3668 Context.IntTy, Loc); 3669 } 3670 3671 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3672 QualType Ty, SourceLocation Loc) { 3673 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3674 3675 using llvm::APFloat; 3676 APFloat Val(Format); 3677 3678 APFloat::opStatus result = Literal.GetFloatValue(Val); 3679 3680 // Overflow is always an error, but underflow is only an error if 3681 // we underflowed to zero (APFloat reports denormals as underflow). 3682 if ((result & APFloat::opOverflow) || 3683 ((result & APFloat::opUnderflow) && Val.isZero())) { 3684 unsigned diagnostic; 3685 SmallString<20> buffer; 3686 if (result & APFloat::opOverflow) { 3687 diagnostic = diag::warn_float_overflow; 3688 APFloat::getLargest(Format).toString(buffer); 3689 } else { 3690 diagnostic = diag::warn_float_underflow; 3691 APFloat::getSmallest(Format).toString(buffer); 3692 } 3693 3694 S.Diag(Loc, diagnostic) 3695 << Ty 3696 << StringRef(buffer.data(), buffer.size()); 3697 } 3698 3699 bool isExact = (result == APFloat::opOK); 3700 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3701 } 3702 3703 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3704 assert(E && "Invalid expression"); 3705 3706 if (E->isValueDependent()) 3707 return false; 3708 3709 QualType QT = E->getType(); 3710 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3711 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3712 return true; 3713 } 3714 3715 llvm::APSInt ValueAPS; 3716 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3717 3718 if (R.isInvalid()) 3719 return true; 3720 3721 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3722 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3723 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3724 << toString(ValueAPS, 10) << ValueIsPositive; 3725 return true; 3726 } 3727 3728 return false; 3729 } 3730 3731 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3732 // Fast path for a single digit (which is quite common). A single digit 3733 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3734 if (Tok.getLength() == 1) { 3735 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3736 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3737 } 3738 3739 SmallString<128> SpellingBuffer; 3740 // NumericLiteralParser wants to overread by one character. Add padding to 3741 // the buffer in case the token is copied to the buffer. If getSpelling() 3742 // returns a StringRef to the memory buffer, it should have a null char at 3743 // the EOF, so it is also safe. 3744 SpellingBuffer.resize(Tok.getLength() + 1); 3745 3746 // Get the spelling of the token, which eliminates trigraphs, etc. 3747 bool Invalid = false; 3748 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3749 if (Invalid) 3750 return ExprError(); 3751 3752 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3753 PP.getSourceManager(), PP.getLangOpts(), 3754 PP.getTargetInfo(), PP.getDiagnostics()); 3755 if (Literal.hadError) 3756 return ExprError(); 3757 3758 if (Literal.hasUDSuffix()) { 3759 // We're building a user-defined literal. 3760 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3761 SourceLocation UDSuffixLoc = 3762 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3763 3764 // Make sure we're allowed user-defined literals here. 3765 if (!UDLScope) 3766 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3767 3768 QualType CookedTy; 3769 if (Literal.isFloatingLiteral()) { 3770 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3771 // long double, the literal is treated as a call of the form 3772 // operator "" X (f L) 3773 CookedTy = Context.LongDoubleTy; 3774 } else { 3775 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3776 // unsigned long long, the literal is treated as a call of the form 3777 // operator "" X (n ULL) 3778 CookedTy = Context.UnsignedLongLongTy; 3779 } 3780 3781 DeclarationName OpName = 3782 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3783 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3784 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3785 3786 SourceLocation TokLoc = Tok.getLocation(); 3787 3788 // Perform literal operator lookup to determine if we're building a raw 3789 // literal or a cooked one. 3790 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3791 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3792 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3793 /*AllowStringTemplatePack*/ false, 3794 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3795 case LOLR_ErrorNoDiagnostic: 3796 // Lookup failure for imaginary constants isn't fatal, there's still the 3797 // GNU extension producing _Complex types. 3798 break; 3799 case LOLR_Error: 3800 return ExprError(); 3801 case LOLR_Cooked: { 3802 Expr *Lit; 3803 if (Literal.isFloatingLiteral()) { 3804 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3805 } else { 3806 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3807 if (Literal.GetIntegerValue(ResultVal)) 3808 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3809 << /* Unsigned */ 1; 3810 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3811 Tok.getLocation()); 3812 } 3813 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3814 } 3815 3816 case LOLR_Raw: { 3817 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3818 // literal is treated as a call of the form 3819 // operator "" X ("n") 3820 unsigned Length = Literal.getUDSuffixOffset(); 3821 QualType StrTy = Context.getConstantArrayType( 3822 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3823 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3824 Expr *Lit = StringLiteral::Create( 3825 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3826 /*Pascal*/false, StrTy, &TokLoc, 1); 3827 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3828 } 3829 3830 case LOLR_Template: { 3831 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3832 // template), L is treated as a call fo the form 3833 // operator "" X <'c1', 'c2', ... 'ck'>() 3834 // where n is the source character sequence c1 c2 ... ck. 3835 TemplateArgumentListInfo ExplicitArgs; 3836 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3837 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3838 llvm::APSInt Value(CharBits, CharIsUnsigned); 3839 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3840 Value = TokSpelling[I]; 3841 TemplateArgument Arg(Context, Value, Context.CharTy); 3842 TemplateArgumentLocInfo ArgInfo; 3843 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3844 } 3845 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3846 &ExplicitArgs); 3847 } 3848 case LOLR_StringTemplatePack: 3849 llvm_unreachable("unexpected literal operator lookup result"); 3850 } 3851 } 3852 3853 Expr *Res; 3854 3855 if (Literal.isFixedPointLiteral()) { 3856 QualType Ty; 3857 3858 if (Literal.isAccum) { 3859 if (Literal.isHalf) { 3860 Ty = Context.ShortAccumTy; 3861 } else if (Literal.isLong) { 3862 Ty = Context.LongAccumTy; 3863 } else { 3864 Ty = Context.AccumTy; 3865 } 3866 } else if (Literal.isFract) { 3867 if (Literal.isHalf) { 3868 Ty = Context.ShortFractTy; 3869 } else if (Literal.isLong) { 3870 Ty = Context.LongFractTy; 3871 } else { 3872 Ty = Context.FractTy; 3873 } 3874 } 3875 3876 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3877 3878 bool isSigned = !Literal.isUnsigned; 3879 unsigned scale = Context.getFixedPointScale(Ty); 3880 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3881 3882 llvm::APInt Val(bit_width, 0, isSigned); 3883 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3884 bool ValIsZero = Val.isZero() && !Overflowed; 3885 3886 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3887 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3888 // Clause 6.4.4 - The value of a constant shall be in the range of 3889 // representable values for its type, with exception for constants of a 3890 // fract type with a value of exactly 1; such a constant shall denote 3891 // the maximal value for the type. 3892 --Val; 3893 else if (Val.ugt(MaxVal) || Overflowed) 3894 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3895 3896 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3897 Tok.getLocation(), scale); 3898 } else if (Literal.isFloatingLiteral()) { 3899 QualType Ty; 3900 if (Literal.isHalf){ 3901 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3902 Ty = Context.HalfTy; 3903 else { 3904 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3905 return ExprError(); 3906 } 3907 } else if (Literal.isFloat) 3908 Ty = Context.FloatTy; 3909 else if (Literal.isLong) 3910 Ty = Context.LongDoubleTy; 3911 else if (Literal.isFloat16) 3912 Ty = Context.Float16Ty; 3913 else if (Literal.isFloat128) 3914 Ty = Context.Float128Ty; 3915 else 3916 Ty = Context.DoubleTy; 3917 3918 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3919 3920 if (Ty == Context.DoubleTy) { 3921 if (getLangOpts().SinglePrecisionConstants) { 3922 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3923 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3924 } 3925 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3926 "cl_khr_fp64", getLangOpts())) { 3927 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3928 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) 3929 << (getLangOpts().getOpenCLCompatibleVersion() >= 300); 3930 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3931 } 3932 } 3933 } else if (!Literal.isIntegerLiteral()) { 3934 return ExprError(); 3935 } else { 3936 QualType Ty; 3937 3938 // 'long long' is a C99 or C++11 feature. 3939 if (!getLangOpts().C99 && Literal.isLongLong) { 3940 if (getLangOpts().CPlusPlus) 3941 Diag(Tok.getLocation(), 3942 getLangOpts().CPlusPlus11 ? 3943 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3944 else 3945 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3946 } 3947 3948 // 'z/uz' literals are a C++2b feature. 3949 if (Literal.isSizeT) 3950 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3951 ? getLangOpts().CPlusPlus2b 3952 ? diag::warn_cxx20_compat_size_t_suffix 3953 : diag::ext_cxx2b_size_t_suffix 3954 : diag::err_cxx2b_size_t_suffix); 3955 3956 // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++, 3957 // but we do not currently support the suffix in C++ mode because it's not 3958 // entirely clear whether WG21 will prefer this suffix to return a library 3959 // type such as std::bit_int instead of returning a _BitInt. 3960 if (Literal.isBitInt && !getLangOpts().CPlusPlus) 3961 PP.Diag(Tok.getLocation(), getLangOpts().C2x 3962 ? diag::warn_c2x_compat_bitint_suffix 3963 : diag::ext_c2x_bitint_suffix); 3964 3965 // Get the value in the widest-possible width. What is "widest" depends on 3966 // whether the literal is a bit-precise integer or not. For a bit-precise 3967 // integer type, try to scan the source to determine how many bits are 3968 // needed to represent the value. This may seem a bit expensive, but trying 3969 // to get the integer value from an overly-wide APInt is *extremely* 3970 // expensive, so the naive approach of assuming 3971 // llvm::IntegerType::MAX_INT_BITS is a big performance hit. 3972 unsigned BitsNeeded = 3973 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded( 3974 Literal.getLiteralDigits(), Literal.getRadix()) 3975 : Context.getTargetInfo().getIntMaxTWidth(); 3976 llvm::APInt ResultVal(BitsNeeded, 0); 3977 3978 if (Literal.GetIntegerValue(ResultVal)) { 3979 // If this value didn't fit into uintmax_t, error and force to ull. 3980 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3981 << /* Unsigned */ 1; 3982 Ty = Context.UnsignedLongLongTy; 3983 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3984 "long long is not intmax_t?"); 3985 } else { 3986 // If this value fits into a ULL, try to figure out what else it fits into 3987 // according to the rules of C99 6.4.4.1p5. 3988 3989 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3990 // be an unsigned int. 3991 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3992 3993 // Check from smallest to largest, picking the smallest type we can. 3994 unsigned Width = 0; 3995 3996 // Microsoft specific integer suffixes are explicitly sized. 3997 if (Literal.MicrosoftInteger) { 3998 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3999 Width = 8; 4000 Ty = Context.CharTy; 4001 } else { 4002 Width = Literal.MicrosoftInteger; 4003 Ty = Context.getIntTypeForBitwidth(Width, 4004 /*Signed=*/!Literal.isUnsigned); 4005 } 4006 } 4007 4008 // Bit-precise integer literals are automagically-sized based on the 4009 // width required by the literal. 4010 if (Literal.isBitInt) { 4011 // The signed version has one more bit for the sign value. There are no 4012 // zero-width bit-precise integers, even if the literal value is 0. 4013 Width = std::max(ResultVal.getActiveBits(), 1u) + 4014 (Literal.isUnsigned ? 0u : 1u); 4015 4016 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH, 4017 // and reset the type to the largest supported width. 4018 unsigned int MaxBitIntWidth = 4019 Context.getTargetInfo().getMaxBitIntWidth(); 4020 if (Width > MaxBitIntWidth) { 4021 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 4022 << Literal.isUnsigned; 4023 Width = MaxBitIntWidth; 4024 } 4025 4026 // Reset the result value to the smaller APInt and select the correct 4027 // type to be used. Note, we zext even for signed values because the 4028 // literal itself is always an unsigned value (a preceeding - is a 4029 // unary operator, not part of the literal). 4030 ResultVal = ResultVal.zextOrTrunc(Width); 4031 Ty = Context.getBitIntType(Literal.isUnsigned, Width); 4032 } 4033 4034 // Check C++2b size_t literals. 4035 if (Literal.isSizeT) { 4036 assert(!Literal.MicrosoftInteger && 4037 "size_t literals can't be Microsoft literals"); 4038 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 4039 Context.getTargetInfo().getSizeType()); 4040 4041 // Does it fit in size_t? 4042 if (ResultVal.isIntN(SizeTSize)) { 4043 // Does it fit in ssize_t? 4044 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 4045 Ty = Context.getSignedSizeType(); 4046 else if (AllowUnsigned) 4047 Ty = Context.getSizeType(); 4048 Width = SizeTSize; 4049 } 4050 } 4051 4052 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 4053 !Literal.isSizeT) { 4054 // Are int/unsigned possibilities? 4055 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 4056 4057 // Does it fit in a unsigned int? 4058 if (ResultVal.isIntN(IntSize)) { 4059 // Does it fit in a signed int? 4060 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 4061 Ty = Context.IntTy; 4062 else if (AllowUnsigned) 4063 Ty = Context.UnsignedIntTy; 4064 Width = IntSize; 4065 } 4066 } 4067 4068 // Are long/unsigned long possibilities? 4069 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 4070 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 4071 4072 // Does it fit in a unsigned long? 4073 if (ResultVal.isIntN(LongSize)) { 4074 // Does it fit in a signed long? 4075 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 4076 Ty = Context.LongTy; 4077 else if (AllowUnsigned) 4078 Ty = Context.UnsignedLongTy; 4079 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 4080 // is compatible. 4081 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 4082 const unsigned LongLongSize = 4083 Context.getTargetInfo().getLongLongWidth(); 4084 Diag(Tok.getLocation(), 4085 getLangOpts().CPlusPlus 4086 ? Literal.isLong 4087 ? diag::warn_old_implicitly_unsigned_long_cxx 4088 : /*C++98 UB*/ diag:: 4089 ext_old_implicitly_unsigned_long_cxx 4090 : diag::warn_old_implicitly_unsigned_long) 4091 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 4092 : /*will be ill-formed*/ 1); 4093 Ty = Context.UnsignedLongTy; 4094 } 4095 Width = LongSize; 4096 } 4097 } 4098 4099 // Check long long if needed. 4100 if (Ty.isNull() && !Literal.isSizeT) { 4101 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 4102 4103 // Does it fit in a unsigned long long? 4104 if (ResultVal.isIntN(LongLongSize)) { 4105 // Does it fit in a signed long long? 4106 // To be compatible with MSVC, hex integer literals ending with the 4107 // LL or i64 suffix are always signed in Microsoft mode. 4108 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 4109 (getLangOpts().MSVCCompat && Literal.isLongLong))) 4110 Ty = Context.LongLongTy; 4111 else if (AllowUnsigned) 4112 Ty = Context.UnsignedLongLongTy; 4113 Width = LongLongSize; 4114 } 4115 } 4116 4117 // If we still couldn't decide a type, we either have 'size_t' literal 4118 // that is out of range, or a decimal literal that does not fit in a 4119 // signed long long and has no U suffix. 4120 if (Ty.isNull()) { 4121 if (Literal.isSizeT) 4122 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 4123 << Literal.isUnsigned; 4124 else 4125 Diag(Tok.getLocation(), 4126 diag::ext_integer_literal_too_large_for_signed); 4127 Ty = Context.UnsignedLongLongTy; 4128 Width = Context.getTargetInfo().getLongLongWidth(); 4129 } 4130 4131 if (ResultVal.getBitWidth() != Width) 4132 ResultVal = ResultVal.trunc(Width); 4133 } 4134 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 4135 } 4136 4137 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 4138 if (Literal.isImaginary) { 4139 Res = new (Context) ImaginaryLiteral(Res, 4140 Context.getComplexType(Res->getType())); 4141 4142 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4143 } 4144 return Res; 4145 } 4146 4147 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4148 assert(E && "ActOnParenExpr() missing expr"); 4149 QualType ExprTy = E->getType(); 4150 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && 4151 !E->isLValue() && ExprTy->hasFloatingRepresentation()) 4152 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); 4153 return new (Context) ParenExpr(L, R, E); 4154 } 4155 4156 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4157 SourceLocation Loc, 4158 SourceRange ArgRange) { 4159 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4160 // scalar or vector data type argument..." 4161 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4162 // type (C99 6.2.5p18) or void. 4163 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4164 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4165 << T << ArgRange; 4166 return true; 4167 } 4168 4169 assert((T->isVoidType() || !T->isIncompleteType()) && 4170 "Scalar types should always be complete"); 4171 return false; 4172 } 4173 4174 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4175 SourceLocation Loc, 4176 SourceRange ArgRange, 4177 UnaryExprOrTypeTrait TraitKind) { 4178 // Invalid types must be hard errors for SFINAE in C++. 4179 if (S.LangOpts.CPlusPlus) 4180 return true; 4181 4182 // C99 6.5.3.4p1: 4183 if (T->isFunctionType() && 4184 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4185 TraitKind == UETT_PreferredAlignOf)) { 4186 // sizeof(function)/alignof(function) is allowed as an extension. 4187 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4188 << getTraitSpelling(TraitKind) << ArgRange; 4189 return false; 4190 } 4191 4192 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4193 // this is an error (OpenCL v1.1 s6.3.k) 4194 if (T->isVoidType()) { 4195 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4196 : diag::ext_sizeof_alignof_void_type; 4197 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4198 return false; 4199 } 4200 4201 return true; 4202 } 4203 4204 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4205 SourceLocation Loc, 4206 SourceRange ArgRange, 4207 UnaryExprOrTypeTrait TraitKind) { 4208 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4209 // runtime doesn't allow it. 4210 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4211 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4212 << T << (TraitKind == UETT_SizeOf) 4213 << ArgRange; 4214 return true; 4215 } 4216 4217 return false; 4218 } 4219 4220 /// Check whether E is a pointer from a decayed array type (the decayed 4221 /// pointer type is equal to T) and emit a warning if it is. 4222 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4223 Expr *E) { 4224 // Don't warn if the operation changed the type. 4225 if (T != E->getType()) 4226 return; 4227 4228 // Now look for array decays. 4229 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4230 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4231 return; 4232 4233 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4234 << ICE->getType() 4235 << ICE->getSubExpr()->getType(); 4236 } 4237 4238 /// Check the constraints on expression operands to unary type expression 4239 /// and type traits. 4240 /// 4241 /// Completes any types necessary and validates the constraints on the operand 4242 /// expression. The logic mostly mirrors the type-based overload, but may modify 4243 /// the expression as it completes the type for that expression through template 4244 /// instantiation, etc. 4245 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4246 UnaryExprOrTypeTrait ExprKind) { 4247 QualType ExprTy = E->getType(); 4248 assert(!ExprTy->isReferenceType()); 4249 4250 bool IsUnevaluatedOperand = 4251 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4252 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4253 if (IsUnevaluatedOperand) { 4254 ExprResult Result = CheckUnevaluatedOperand(E); 4255 if (Result.isInvalid()) 4256 return true; 4257 E = Result.get(); 4258 } 4259 4260 // The operand for sizeof and alignof is in an unevaluated expression context, 4261 // so side effects could result in unintended consequences. 4262 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4263 // used to build SFINAE gadgets. 4264 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4265 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4266 !E->isInstantiationDependent() && 4267 !E->getType()->isVariableArrayType() && 4268 E->HasSideEffects(Context, false)) 4269 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4270 4271 if (ExprKind == UETT_VecStep) 4272 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4273 E->getSourceRange()); 4274 4275 // Explicitly list some types as extensions. 4276 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4277 E->getSourceRange(), ExprKind)) 4278 return false; 4279 4280 // 'alignof' applied to an expression only requires the base element type of 4281 // the expression to be complete. 'sizeof' requires the expression's type to 4282 // be complete (and will attempt to complete it if it's an array of unknown 4283 // bound). 4284 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4285 if (RequireCompleteSizedType( 4286 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4287 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4288 getTraitSpelling(ExprKind), E->getSourceRange())) 4289 return true; 4290 } else { 4291 if (RequireCompleteSizedExprType( 4292 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4293 getTraitSpelling(ExprKind), E->getSourceRange())) 4294 return true; 4295 } 4296 4297 // Completing the expression's type may have changed it. 4298 ExprTy = E->getType(); 4299 assert(!ExprTy->isReferenceType()); 4300 4301 if (ExprTy->isFunctionType()) { 4302 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4303 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4304 return true; 4305 } 4306 4307 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4308 E->getSourceRange(), ExprKind)) 4309 return true; 4310 4311 if (ExprKind == UETT_SizeOf) { 4312 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4313 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4314 QualType OType = PVD->getOriginalType(); 4315 QualType Type = PVD->getType(); 4316 if (Type->isPointerType() && OType->isArrayType()) { 4317 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4318 << Type << OType; 4319 Diag(PVD->getLocation(), diag::note_declared_at); 4320 } 4321 } 4322 } 4323 4324 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4325 // decays into a pointer and returns an unintended result. This is most 4326 // likely a typo for "sizeof(array) op x". 4327 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4328 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4329 BO->getLHS()); 4330 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4331 BO->getRHS()); 4332 } 4333 } 4334 4335 return false; 4336 } 4337 4338 /// Check the constraints on operands to unary expression and type 4339 /// traits. 4340 /// 4341 /// This will complete any types necessary, and validate the various constraints 4342 /// on those operands. 4343 /// 4344 /// The UsualUnaryConversions() function is *not* called by this routine. 4345 /// C99 6.3.2.1p[2-4] all state: 4346 /// Except when it is the operand of the sizeof operator ... 4347 /// 4348 /// C++ [expr.sizeof]p4 4349 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4350 /// standard conversions are not applied to the operand of sizeof. 4351 /// 4352 /// This policy is followed for all of the unary trait expressions. 4353 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4354 SourceLocation OpLoc, 4355 SourceRange ExprRange, 4356 UnaryExprOrTypeTrait ExprKind) { 4357 if (ExprType->isDependentType()) 4358 return false; 4359 4360 // C++ [expr.sizeof]p2: 4361 // When applied to a reference or a reference type, the result 4362 // is the size of the referenced type. 4363 // C++11 [expr.alignof]p3: 4364 // When alignof is applied to a reference type, the result 4365 // shall be the alignment of the referenced type. 4366 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4367 ExprType = Ref->getPointeeType(); 4368 4369 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4370 // When alignof or _Alignof is applied to an array type, the result 4371 // is the alignment of the element type. 4372 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4373 ExprKind == UETT_OpenMPRequiredSimdAlign) 4374 ExprType = Context.getBaseElementType(ExprType); 4375 4376 if (ExprKind == UETT_VecStep) 4377 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4378 4379 // Explicitly list some types as extensions. 4380 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4381 ExprKind)) 4382 return false; 4383 4384 if (RequireCompleteSizedType( 4385 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4386 getTraitSpelling(ExprKind), ExprRange)) 4387 return true; 4388 4389 if (ExprType->isFunctionType()) { 4390 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4391 << getTraitSpelling(ExprKind) << ExprRange; 4392 return true; 4393 } 4394 4395 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4396 ExprKind)) 4397 return true; 4398 4399 return false; 4400 } 4401 4402 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4403 // Cannot know anything else if the expression is dependent. 4404 if (E->isTypeDependent()) 4405 return false; 4406 4407 if (E->getObjectKind() == OK_BitField) { 4408 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4409 << 1 << E->getSourceRange(); 4410 return true; 4411 } 4412 4413 ValueDecl *D = nullptr; 4414 Expr *Inner = E->IgnoreParens(); 4415 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4416 D = DRE->getDecl(); 4417 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4418 D = ME->getMemberDecl(); 4419 } 4420 4421 // If it's a field, require the containing struct to have a 4422 // complete definition so that we can compute the layout. 4423 // 4424 // This can happen in C++11 onwards, either by naming the member 4425 // in a way that is not transformed into a member access expression 4426 // (in an unevaluated operand, for instance), or by naming the member 4427 // in a trailing-return-type. 4428 // 4429 // For the record, since __alignof__ on expressions is a GCC 4430 // extension, GCC seems to permit this but always gives the 4431 // nonsensical answer 0. 4432 // 4433 // We don't really need the layout here --- we could instead just 4434 // directly check for all the appropriate alignment-lowing 4435 // attributes --- but that would require duplicating a lot of 4436 // logic that just isn't worth duplicating for such a marginal 4437 // use-case. 4438 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4439 // Fast path this check, since we at least know the record has a 4440 // definition if we can find a member of it. 4441 if (!FD->getParent()->isCompleteDefinition()) { 4442 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4443 << E->getSourceRange(); 4444 return true; 4445 } 4446 4447 // Otherwise, if it's a field, and the field doesn't have 4448 // reference type, then it must have a complete type (or be a 4449 // flexible array member, which we explicitly want to 4450 // white-list anyway), which makes the following checks trivial. 4451 if (!FD->getType()->isReferenceType()) 4452 return false; 4453 } 4454 4455 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4456 } 4457 4458 bool Sema::CheckVecStepExpr(Expr *E) { 4459 E = E->IgnoreParens(); 4460 4461 // Cannot know anything else if the expression is dependent. 4462 if (E->isTypeDependent()) 4463 return false; 4464 4465 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4466 } 4467 4468 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4469 CapturingScopeInfo *CSI) { 4470 assert(T->isVariablyModifiedType()); 4471 assert(CSI != nullptr); 4472 4473 // We're going to walk down into the type and look for VLA expressions. 4474 do { 4475 const Type *Ty = T.getTypePtr(); 4476 switch (Ty->getTypeClass()) { 4477 #define TYPE(Class, Base) 4478 #define ABSTRACT_TYPE(Class, Base) 4479 #define NON_CANONICAL_TYPE(Class, Base) 4480 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4481 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4482 #include "clang/AST/TypeNodes.inc" 4483 T = QualType(); 4484 break; 4485 // These types are never variably-modified. 4486 case Type::Builtin: 4487 case Type::Complex: 4488 case Type::Vector: 4489 case Type::ExtVector: 4490 case Type::ConstantMatrix: 4491 case Type::Record: 4492 case Type::Enum: 4493 case Type::Elaborated: 4494 case Type::TemplateSpecialization: 4495 case Type::ObjCObject: 4496 case Type::ObjCInterface: 4497 case Type::ObjCObjectPointer: 4498 case Type::ObjCTypeParam: 4499 case Type::Pipe: 4500 case Type::BitInt: 4501 llvm_unreachable("type class is never variably-modified!"); 4502 case Type::Adjusted: 4503 T = cast<AdjustedType>(Ty)->getOriginalType(); 4504 break; 4505 case Type::Decayed: 4506 T = cast<DecayedType>(Ty)->getPointeeType(); 4507 break; 4508 case Type::Pointer: 4509 T = cast<PointerType>(Ty)->getPointeeType(); 4510 break; 4511 case Type::BlockPointer: 4512 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4513 break; 4514 case Type::LValueReference: 4515 case Type::RValueReference: 4516 T = cast<ReferenceType>(Ty)->getPointeeType(); 4517 break; 4518 case Type::MemberPointer: 4519 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4520 break; 4521 case Type::ConstantArray: 4522 case Type::IncompleteArray: 4523 // Losing element qualification here is fine. 4524 T = cast<ArrayType>(Ty)->getElementType(); 4525 break; 4526 case Type::VariableArray: { 4527 // Losing element qualification here is fine. 4528 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4529 4530 // Unknown size indication requires no size computation. 4531 // Otherwise, evaluate and record it. 4532 auto Size = VAT->getSizeExpr(); 4533 if (Size && !CSI->isVLATypeCaptured(VAT) && 4534 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4535 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4536 4537 T = VAT->getElementType(); 4538 break; 4539 } 4540 case Type::FunctionProto: 4541 case Type::FunctionNoProto: 4542 T = cast<FunctionType>(Ty)->getReturnType(); 4543 break; 4544 case Type::Paren: 4545 case Type::TypeOf: 4546 case Type::UnaryTransform: 4547 case Type::Attributed: 4548 case Type::BTFTagAttributed: 4549 case Type::SubstTemplateTypeParm: 4550 case Type::MacroQualified: 4551 // Keep walking after single level desugaring. 4552 T = T.getSingleStepDesugaredType(Context); 4553 break; 4554 case Type::Typedef: 4555 T = cast<TypedefType>(Ty)->desugar(); 4556 break; 4557 case Type::Decltype: 4558 T = cast<DecltypeType>(Ty)->desugar(); 4559 break; 4560 case Type::Using: 4561 T = cast<UsingType>(Ty)->desugar(); 4562 break; 4563 case Type::Auto: 4564 case Type::DeducedTemplateSpecialization: 4565 T = cast<DeducedType>(Ty)->getDeducedType(); 4566 break; 4567 case Type::TypeOfExpr: 4568 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4569 break; 4570 case Type::Atomic: 4571 T = cast<AtomicType>(Ty)->getValueType(); 4572 break; 4573 } 4574 } while (!T.isNull() && T->isVariablyModifiedType()); 4575 } 4576 4577 /// Build a sizeof or alignof expression given a type operand. 4578 ExprResult 4579 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4580 SourceLocation OpLoc, 4581 UnaryExprOrTypeTrait ExprKind, 4582 SourceRange R) { 4583 if (!TInfo) 4584 return ExprError(); 4585 4586 QualType T = TInfo->getType(); 4587 4588 if (!T->isDependentType() && 4589 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4590 return ExprError(); 4591 4592 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4593 if (auto *TT = T->getAs<TypedefType>()) { 4594 for (auto I = FunctionScopes.rbegin(), 4595 E = std::prev(FunctionScopes.rend()); 4596 I != E; ++I) { 4597 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4598 if (CSI == nullptr) 4599 break; 4600 DeclContext *DC = nullptr; 4601 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4602 DC = LSI->CallOperator; 4603 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4604 DC = CRSI->TheCapturedDecl; 4605 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4606 DC = BSI->TheDecl; 4607 if (DC) { 4608 if (DC->containsDecl(TT->getDecl())) 4609 break; 4610 captureVariablyModifiedType(Context, T, CSI); 4611 } 4612 } 4613 } 4614 } 4615 4616 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4617 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf && 4618 TInfo->getType()->isVariablyModifiedType()) 4619 TInfo = TransformToPotentiallyEvaluated(TInfo); 4620 4621 return new (Context) UnaryExprOrTypeTraitExpr( 4622 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4623 } 4624 4625 /// Build a sizeof or alignof expression given an expression 4626 /// operand. 4627 ExprResult 4628 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4629 UnaryExprOrTypeTrait ExprKind) { 4630 ExprResult PE = CheckPlaceholderExpr(E); 4631 if (PE.isInvalid()) 4632 return ExprError(); 4633 4634 E = PE.get(); 4635 4636 // Verify that the operand is valid. 4637 bool isInvalid = false; 4638 if (E->isTypeDependent()) { 4639 // Delay type-checking for type-dependent expressions. 4640 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4641 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4642 } else if (ExprKind == UETT_VecStep) { 4643 isInvalid = CheckVecStepExpr(E); 4644 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4645 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4646 isInvalid = true; 4647 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4648 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4649 isInvalid = true; 4650 } else { 4651 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4652 } 4653 4654 if (isInvalid) 4655 return ExprError(); 4656 4657 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4658 PE = TransformToPotentiallyEvaluated(E); 4659 if (PE.isInvalid()) return ExprError(); 4660 E = PE.get(); 4661 } 4662 4663 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4664 return new (Context) UnaryExprOrTypeTraitExpr( 4665 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4666 } 4667 4668 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4669 /// expr and the same for @c alignof and @c __alignof 4670 /// Note that the ArgRange is invalid if isType is false. 4671 ExprResult 4672 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4673 UnaryExprOrTypeTrait ExprKind, bool IsType, 4674 void *TyOrEx, SourceRange ArgRange) { 4675 // If error parsing type, ignore. 4676 if (!TyOrEx) return ExprError(); 4677 4678 if (IsType) { 4679 TypeSourceInfo *TInfo; 4680 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4681 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4682 } 4683 4684 Expr *ArgEx = (Expr *)TyOrEx; 4685 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4686 return Result; 4687 } 4688 4689 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4690 bool IsReal) { 4691 if (V.get()->isTypeDependent()) 4692 return S.Context.DependentTy; 4693 4694 // _Real and _Imag are only l-values for normal l-values. 4695 if (V.get()->getObjectKind() != OK_Ordinary) { 4696 V = S.DefaultLvalueConversion(V.get()); 4697 if (V.isInvalid()) 4698 return QualType(); 4699 } 4700 4701 // These operators return the element type of a complex type. 4702 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4703 return CT->getElementType(); 4704 4705 // Otherwise they pass through real integer and floating point types here. 4706 if (V.get()->getType()->isArithmeticType()) 4707 return V.get()->getType(); 4708 4709 // Test for placeholders. 4710 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4711 if (PR.isInvalid()) return QualType(); 4712 if (PR.get() != V.get()) { 4713 V = PR; 4714 return CheckRealImagOperand(S, V, Loc, IsReal); 4715 } 4716 4717 // Reject anything else. 4718 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4719 << (IsReal ? "__real" : "__imag"); 4720 return QualType(); 4721 } 4722 4723 4724 4725 ExprResult 4726 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4727 tok::TokenKind Kind, Expr *Input) { 4728 UnaryOperatorKind Opc; 4729 switch (Kind) { 4730 default: llvm_unreachable("Unknown unary op!"); 4731 case tok::plusplus: Opc = UO_PostInc; break; 4732 case tok::minusminus: Opc = UO_PostDec; break; 4733 } 4734 4735 // Since this might is a postfix expression, get rid of ParenListExprs. 4736 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4737 if (Result.isInvalid()) return ExprError(); 4738 Input = Result.get(); 4739 4740 return BuildUnaryOp(S, OpLoc, Opc, Input); 4741 } 4742 4743 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4744 /// 4745 /// \return true on error 4746 static bool checkArithmeticOnObjCPointer(Sema &S, 4747 SourceLocation opLoc, 4748 Expr *op) { 4749 assert(op->getType()->isObjCObjectPointerType()); 4750 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4751 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4752 return false; 4753 4754 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4755 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4756 << op->getSourceRange(); 4757 return true; 4758 } 4759 4760 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4761 auto *BaseNoParens = Base->IgnoreParens(); 4762 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4763 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4764 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4765 } 4766 4767 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent. 4768 // Typically this is DependentTy, but can sometimes be more precise. 4769 // 4770 // There are cases when we could determine a non-dependent type: 4771 // - LHS and RHS may have non-dependent types despite being type-dependent 4772 // (e.g. unbounded array static members of the current instantiation) 4773 // - one may be a dependent-sized array with known element type 4774 // - one may be a dependent-typed valid index (enum in current instantiation) 4775 // 4776 // We *always* return a dependent type, in such cases it is DependentTy. 4777 // This avoids creating type-dependent expressions with non-dependent types. 4778 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275 4779 static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, 4780 const ASTContext &Ctx) { 4781 assert(LHS->isTypeDependent() || RHS->isTypeDependent()); 4782 QualType LTy = LHS->getType(), RTy = RHS->getType(); 4783 QualType Result = Ctx.DependentTy; 4784 if (RTy->isIntegralOrUnscopedEnumerationType()) { 4785 if (const PointerType *PT = LTy->getAs<PointerType>()) 4786 Result = PT->getPointeeType(); 4787 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe()) 4788 Result = AT->getElementType(); 4789 } else if (LTy->isIntegralOrUnscopedEnumerationType()) { 4790 if (const PointerType *PT = RTy->getAs<PointerType>()) 4791 Result = PT->getPointeeType(); 4792 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe()) 4793 Result = AT->getElementType(); 4794 } 4795 // Ensure we return a dependent type. 4796 return Result->isDependentType() ? Result : Ctx.DependentTy; 4797 } 4798 4799 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args); 4800 4801 ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, 4802 SourceLocation lbLoc, 4803 MultiExprArg ArgExprs, 4804 SourceLocation rbLoc) { 4805 4806 if (base && !base->getType().isNull() && 4807 base->hasPlaceholderType(BuiltinType::OMPArraySection)) 4808 return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(), 4809 SourceLocation(), /*Length*/ nullptr, 4810 /*Stride=*/nullptr, rbLoc); 4811 4812 // Since this might be a postfix expression, get rid of ParenListExprs. 4813 if (isa<ParenListExpr>(base)) { 4814 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4815 if (result.isInvalid()) 4816 return ExprError(); 4817 base = result.get(); 4818 } 4819 4820 // Check if base and idx form a MatrixSubscriptExpr. 4821 // 4822 // Helper to check for comma expressions, which are not allowed as indices for 4823 // matrix subscript expressions. 4824 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4825 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4826 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4827 << SourceRange(base->getBeginLoc(), rbLoc); 4828 return true; 4829 } 4830 return false; 4831 }; 4832 // The matrix subscript operator ([][])is considered a single operator. 4833 // Separating the index expressions by parenthesis is not allowed. 4834 if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) && 4835 !isa<MatrixSubscriptExpr>(base)) { 4836 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4837 << SourceRange(base->getBeginLoc(), rbLoc); 4838 return ExprError(); 4839 } 4840 // If the base is a MatrixSubscriptExpr, try to create a new 4841 // MatrixSubscriptExpr. 4842 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4843 if (matSubscriptE) { 4844 assert(ArgExprs.size() == 1); 4845 if (CheckAndReportCommaError(ArgExprs.front())) 4846 return ExprError(); 4847 4848 assert(matSubscriptE->isIncomplete() && 4849 "base has to be an incomplete matrix subscript"); 4850 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(), 4851 matSubscriptE->getRowIdx(), 4852 ArgExprs.front(), rbLoc); 4853 } 4854 4855 // Handle any non-overload placeholder types in the base and index 4856 // expressions. We can't handle overloads here because the other 4857 // operand might be an overloadable type, in which case the overload 4858 // resolution for the operator overload should get the first crack 4859 // at the overload. 4860 bool IsMSPropertySubscript = false; 4861 if (base->getType()->isNonOverloadPlaceholderType()) { 4862 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4863 if (!IsMSPropertySubscript) { 4864 ExprResult result = CheckPlaceholderExpr(base); 4865 if (result.isInvalid()) 4866 return ExprError(); 4867 base = result.get(); 4868 } 4869 } 4870 4871 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4872 if (base->getType()->isMatrixType()) { 4873 assert(ArgExprs.size() == 1); 4874 if (CheckAndReportCommaError(ArgExprs.front())) 4875 return ExprError(); 4876 4877 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr, 4878 rbLoc); 4879 } 4880 4881 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) { 4882 Expr *idx = ArgExprs[0]; 4883 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4884 (isa<CXXOperatorCallExpr>(idx) && 4885 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) { 4886 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4887 << SourceRange(base->getBeginLoc(), rbLoc); 4888 } 4889 } 4890 4891 if (ArgExprs.size() == 1 && 4892 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) { 4893 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]); 4894 if (result.isInvalid()) 4895 return ExprError(); 4896 ArgExprs[0] = result.get(); 4897 } else { 4898 if (checkArgsForPlaceholders(*this, ArgExprs)) 4899 return ExprError(); 4900 } 4901 4902 // Build an unanalyzed expression if either operand is type-dependent. 4903 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 && 4904 (base->isTypeDependent() || 4905 Expr::hasAnyTypeDependentArguments(ArgExprs))) { 4906 return new (Context) ArraySubscriptExpr( 4907 base, ArgExprs.front(), 4908 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()), 4909 VK_LValue, OK_Ordinary, rbLoc); 4910 } 4911 4912 // MSDN, property (C++) 4913 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4914 // This attribute can also be used in the declaration of an empty array in a 4915 // class or structure definition. For example: 4916 // __declspec(property(get=GetX, put=PutX)) int x[]; 4917 // The above statement indicates that x[] can be used with one or more array 4918 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4919 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4920 if (IsMSPropertySubscript) { 4921 assert(ArgExprs.size() == 1); 4922 // Build MS property subscript expression if base is MS property reference 4923 // or MS property subscript. 4924 return new (Context) 4925 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy, 4926 VK_LValue, OK_Ordinary, rbLoc); 4927 } 4928 4929 // Use C++ overloaded-operator rules if either operand has record 4930 // type. The spec says to do this if either type is *overloadable*, 4931 // but enum types can't declare subscript operators or conversion 4932 // operators, so there's nothing interesting for overload resolution 4933 // to do if there aren't any record types involved. 4934 // 4935 // ObjC pointers have their own subscripting logic that is not tied 4936 // to overload resolution and so should not take this path. 4937 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() && 4938 ((base->getType()->isRecordType() || 4939 (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) { 4940 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs); 4941 } 4942 4943 ExprResult Res = 4944 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc); 4945 4946 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4947 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4948 4949 return Res; 4950 } 4951 4952 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4953 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4954 InitializationKind Kind = 4955 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4956 InitializationSequence InitSeq(*this, Entity, Kind, E); 4957 return InitSeq.Perform(*this, Entity, Kind, E); 4958 } 4959 4960 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4961 Expr *ColumnIdx, 4962 SourceLocation RBLoc) { 4963 ExprResult BaseR = CheckPlaceholderExpr(Base); 4964 if (BaseR.isInvalid()) 4965 return BaseR; 4966 Base = BaseR.get(); 4967 4968 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4969 if (RowR.isInvalid()) 4970 return RowR; 4971 RowIdx = RowR.get(); 4972 4973 if (!ColumnIdx) 4974 return new (Context) MatrixSubscriptExpr( 4975 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4976 4977 // Build an unanalyzed expression if any of the operands is type-dependent. 4978 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4979 ColumnIdx->isTypeDependent()) 4980 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4981 Context.DependentTy, RBLoc); 4982 4983 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4984 if (ColumnR.isInvalid()) 4985 return ColumnR; 4986 ColumnIdx = ColumnR.get(); 4987 4988 // Check that IndexExpr is an integer expression. If it is a constant 4989 // expression, check that it is less than Dim (= the number of elements in the 4990 // corresponding dimension). 4991 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4992 bool IsColumnIdx) -> Expr * { 4993 if (!IndexExpr->getType()->isIntegerType() && 4994 !IndexExpr->isTypeDependent()) { 4995 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4996 << IsColumnIdx; 4997 return nullptr; 4998 } 4999 5000 if (Optional<llvm::APSInt> Idx = 5001 IndexExpr->getIntegerConstantExpr(Context)) { 5002 if ((*Idx < 0 || *Idx >= Dim)) { 5003 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 5004 << IsColumnIdx << Dim; 5005 return nullptr; 5006 } 5007 } 5008 5009 ExprResult ConvExpr = 5010 tryConvertExprToType(IndexExpr, Context.getSizeType()); 5011 assert(!ConvExpr.isInvalid() && 5012 "should be able to convert any integer type to size type"); 5013 return ConvExpr.get(); 5014 }; 5015 5016 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 5017 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 5018 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 5019 if (!RowIdx || !ColumnIdx) 5020 return ExprError(); 5021 5022 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 5023 MTy->getElementType(), RBLoc); 5024 } 5025 5026 void Sema::CheckAddressOfNoDeref(const Expr *E) { 5027 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 5028 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 5029 5030 // For expressions like `&(*s).b`, the base is recorded and what should be 5031 // checked. 5032 const MemberExpr *Member = nullptr; 5033 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 5034 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 5035 5036 LastRecord.PossibleDerefs.erase(StrippedExpr); 5037 } 5038 5039 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 5040 if (isUnevaluatedContext()) 5041 return; 5042 5043 QualType ResultTy = E->getType(); 5044 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 5045 5046 // Bail if the element is an array since it is not memory access. 5047 if (isa<ArrayType>(ResultTy)) 5048 return; 5049 5050 if (ResultTy->hasAttr(attr::NoDeref)) { 5051 LastRecord.PossibleDerefs.insert(E); 5052 return; 5053 } 5054 5055 // Check if the base type is a pointer to a member access of a struct 5056 // marked with noderef. 5057 const Expr *Base = E->getBase(); 5058 QualType BaseTy = Base->getType(); 5059 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 5060 // Not a pointer access 5061 return; 5062 5063 const MemberExpr *Member = nullptr; 5064 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 5065 Member->isArrow()) 5066 Base = Member->getBase(); 5067 5068 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 5069 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 5070 LastRecord.PossibleDerefs.insert(E); 5071 } 5072 } 5073 5074 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 5075 Expr *LowerBound, 5076 SourceLocation ColonLocFirst, 5077 SourceLocation ColonLocSecond, 5078 Expr *Length, Expr *Stride, 5079 SourceLocation RBLoc) { 5080 if (Base->hasPlaceholderType() && 5081 !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) { 5082 ExprResult Result = CheckPlaceholderExpr(Base); 5083 if (Result.isInvalid()) 5084 return ExprError(); 5085 Base = Result.get(); 5086 } 5087 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 5088 ExprResult Result = CheckPlaceholderExpr(LowerBound); 5089 if (Result.isInvalid()) 5090 return ExprError(); 5091 Result = DefaultLvalueConversion(Result.get()); 5092 if (Result.isInvalid()) 5093 return ExprError(); 5094 LowerBound = Result.get(); 5095 } 5096 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 5097 ExprResult Result = CheckPlaceholderExpr(Length); 5098 if (Result.isInvalid()) 5099 return ExprError(); 5100 Result = DefaultLvalueConversion(Result.get()); 5101 if (Result.isInvalid()) 5102 return ExprError(); 5103 Length = Result.get(); 5104 } 5105 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 5106 ExprResult Result = CheckPlaceholderExpr(Stride); 5107 if (Result.isInvalid()) 5108 return ExprError(); 5109 Result = DefaultLvalueConversion(Result.get()); 5110 if (Result.isInvalid()) 5111 return ExprError(); 5112 Stride = Result.get(); 5113 } 5114 5115 // Build an unanalyzed expression if either operand is type-dependent. 5116 if (Base->isTypeDependent() || 5117 (LowerBound && 5118 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 5119 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 5120 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 5121 return new (Context) OMPArraySectionExpr( 5122 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 5123 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5124 } 5125 5126 // Perform default conversions. 5127 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 5128 QualType ResultTy; 5129 if (OriginalTy->isAnyPointerType()) { 5130 ResultTy = OriginalTy->getPointeeType(); 5131 } else if (OriginalTy->isArrayType()) { 5132 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 5133 } else { 5134 return ExprError( 5135 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 5136 << Base->getSourceRange()); 5137 } 5138 // C99 6.5.2.1p1 5139 if (LowerBound) { 5140 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 5141 LowerBound); 5142 if (Res.isInvalid()) 5143 return ExprError(Diag(LowerBound->getExprLoc(), 5144 diag::err_omp_typecheck_section_not_integer) 5145 << 0 << LowerBound->getSourceRange()); 5146 LowerBound = Res.get(); 5147 5148 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5149 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5150 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 5151 << 0 << LowerBound->getSourceRange(); 5152 } 5153 if (Length) { 5154 auto Res = 5155 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 5156 if (Res.isInvalid()) 5157 return ExprError(Diag(Length->getExprLoc(), 5158 diag::err_omp_typecheck_section_not_integer) 5159 << 1 << Length->getSourceRange()); 5160 Length = Res.get(); 5161 5162 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5163 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5164 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 5165 << 1 << Length->getSourceRange(); 5166 } 5167 if (Stride) { 5168 ExprResult Res = 5169 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 5170 if (Res.isInvalid()) 5171 return ExprError(Diag(Stride->getExprLoc(), 5172 diag::err_omp_typecheck_section_not_integer) 5173 << 1 << Stride->getSourceRange()); 5174 Stride = Res.get(); 5175 5176 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5177 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5178 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5179 << 1 << Stride->getSourceRange(); 5180 } 5181 5182 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5183 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5184 // type. Note that functions are not objects, and that (in C99 parlance) 5185 // incomplete types are not object types. 5186 if (ResultTy->isFunctionType()) { 5187 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5188 << ResultTy << Base->getSourceRange(); 5189 return ExprError(); 5190 } 5191 5192 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5193 diag::err_omp_section_incomplete_type, Base)) 5194 return ExprError(); 5195 5196 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5197 Expr::EvalResult Result; 5198 if (LowerBound->EvaluateAsInt(Result, Context)) { 5199 // OpenMP 5.0, [2.1.5 Array Sections] 5200 // The array section must be a subset of the original array. 5201 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5202 if (LowerBoundValue.isNegative()) { 5203 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5204 << LowerBound->getSourceRange(); 5205 return ExprError(); 5206 } 5207 } 5208 } 5209 5210 if (Length) { 5211 Expr::EvalResult Result; 5212 if (Length->EvaluateAsInt(Result, Context)) { 5213 // OpenMP 5.0, [2.1.5 Array Sections] 5214 // The length must evaluate to non-negative integers. 5215 llvm::APSInt LengthValue = Result.Val.getInt(); 5216 if (LengthValue.isNegative()) { 5217 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5218 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5219 << Length->getSourceRange(); 5220 return ExprError(); 5221 } 5222 } 5223 } else if (ColonLocFirst.isValid() && 5224 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5225 !OriginalTy->isVariableArrayType()))) { 5226 // OpenMP 5.0, [2.1.5 Array Sections] 5227 // When the size of the array dimension is not known, the length must be 5228 // specified explicitly. 5229 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5230 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5231 return ExprError(); 5232 } 5233 5234 if (Stride) { 5235 Expr::EvalResult Result; 5236 if (Stride->EvaluateAsInt(Result, Context)) { 5237 // OpenMP 5.0, [2.1.5 Array Sections] 5238 // The stride must evaluate to a positive integer. 5239 llvm::APSInt StrideValue = Result.Val.getInt(); 5240 if (!StrideValue.isStrictlyPositive()) { 5241 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5242 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5243 << Stride->getSourceRange(); 5244 return ExprError(); 5245 } 5246 } 5247 } 5248 5249 if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) { 5250 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5251 if (Result.isInvalid()) 5252 return ExprError(); 5253 Base = Result.get(); 5254 } 5255 return new (Context) OMPArraySectionExpr( 5256 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5257 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5258 } 5259 5260 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5261 SourceLocation RParenLoc, 5262 ArrayRef<Expr *> Dims, 5263 ArrayRef<SourceRange> Brackets) { 5264 if (Base->hasPlaceholderType()) { 5265 ExprResult Result = CheckPlaceholderExpr(Base); 5266 if (Result.isInvalid()) 5267 return ExprError(); 5268 Result = DefaultLvalueConversion(Result.get()); 5269 if (Result.isInvalid()) 5270 return ExprError(); 5271 Base = Result.get(); 5272 } 5273 QualType BaseTy = Base->getType(); 5274 // Delay analysis of the types/expressions if instantiation/specialization is 5275 // required. 5276 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5277 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5278 LParenLoc, RParenLoc, Dims, Brackets); 5279 if (!BaseTy->isPointerType() || 5280 (!Base->isTypeDependent() && 5281 BaseTy->getPointeeType()->isIncompleteType())) 5282 return ExprError(Diag(Base->getExprLoc(), 5283 diag::err_omp_non_pointer_type_array_shaping_base) 5284 << Base->getSourceRange()); 5285 5286 SmallVector<Expr *, 4> NewDims; 5287 bool ErrorFound = false; 5288 for (Expr *Dim : Dims) { 5289 if (Dim->hasPlaceholderType()) { 5290 ExprResult Result = CheckPlaceholderExpr(Dim); 5291 if (Result.isInvalid()) { 5292 ErrorFound = true; 5293 continue; 5294 } 5295 Result = DefaultLvalueConversion(Result.get()); 5296 if (Result.isInvalid()) { 5297 ErrorFound = true; 5298 continue; 5299 } 5300 Dim = Result.get(); 5301 } 5302 if (!Dim->isTypeDependent()) { 5303 ExprResult Result = 5304 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5305 if (Result.isInvalid()) { 5306 ErrorFound = true; 5307 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5308 << Dim->getSourceRange(); 5309 continue; 5310 } 5311 Dim = Result.get(); 5312 Expr::EvalResult EvResult; 5313 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5314 // OpenMP 5.0, [2.1.4 Array Shaping] 5315 // Each si is an integral type expression that must evaluate to a 5316 // positive integer. 5317 llvm::APSInt Value = EvResult.Val.getInt(); 5318 if (!Value.isStrictlyPositive()) { 5319 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5320 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5321 << Dim->getSourceRange(); 5322 ErrorFound = true; 5323 continue; 5324 } 5325 } 5326 } 5327 NewDims.push_back(Dim); 5328 } 5329 if (ErrorFound) 5330 return ExprError(); 5331 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5332 LParenLoc, RParenLoc, NewDims, Brackets); 5333 } 5334 5335 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5336 SourceLocation LLoc, SourceLocation RLoc, 5337 ArrayRef<OMPIteratorData> Data) { 5338 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5339 bool IsCorrect = true; 5340 for (const OMPIteratorData &D : Data) { 5341 TypeSourceInfo *TInfo = nullptr; 5342 SourceLocation StartLoc; 5343 QualType DeclTy; 5344 if (!D.Type.getAsOpaquePtr()) { 5345 // OpenMP 5.0, 2.1.6 Iterators 5346 // In an iterator-specifier, if the iterator-type is not specified then 5347 // the type of that iterator is of int type. 5348 DeclTy = Context.IntTy; 5349 StartLoc = D.DeclIdentLoc; 5350 } else { 5351 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5352 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5353 } 5354 5355 bool IsDeclTyDependent = DeclTy->isDependentType() || 5356 DeclTy->containsUnexpandedParameterPack() || 5357 DeclTy->isInstantiationDependentType(); 5358 if (!IsDeclTyDependent) { 5359 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5360 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5361 // The iterator-type must be an integral or pointer type. 5362 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5363 << DeclTy; 5364 IsCorrect = false; 5365 continue; 5366 } 5367 if (DeclTy.isConstant(Context)) { 5368 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5369 // The iterator-type must not be const qualified. 5370 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5371 << DeclTy; 5372 IsCorrect = false; 5373 continue; 5374 } 5375 } 5376 5377 // Iterator declaration. 5378 assert(D.DeclIdent && "Identifier expected."); 5379 // Always try to create iterator declarator to avoid extra error messages 5380 // about unknown declarations use. 5381 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5382 D.DeclIdent, DeclTy, TInfo, SC_None); 5383 VD->setImplicit(); 5384 if (S) { 5385 // Check for conflicting previous declaration. 5386 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5387 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5388 ForVisibleRedeclaration); 5389 Previous.suppressDiagnostics(); 5390 LookupName(Previous, S); 5391 5392 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5393 /*AllowInlineNamespace=*/false); 5394 if (!Previous.empty()) { 5395 NamedDecl *Old = Previous.getRepresentativeDecl(); 5396 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5397 Diag(Old->getLocation(), diag::note_previous_definition); 5398 } else { 5399 PushOnScopeChains(VD, S); 5400 } 5401 } else { 5402 CurContext->addDecl(VD); 5403 } 5404 Expr *Begin = D.Range.Begin; 5405 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5406 ExprResult BeginRes = 5407 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5408 Begin = BeginRes.get(); 5409 } 5410 Expr *End = D.Range.End; 5411 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5412 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5413 End = EndRes.get(); 5414 } 5415 Expr *Step = D.Range.Step; 5416 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5417 if (!Step->getType()->isIntegralType(Context)) { 5418 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5419 << Step << Step->getSourceRange(); 5420 IsCorrect = false; 5421 continue; 5422 } 5423 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5424 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5425 // If the step expression of a range-specification equals zero, the 5426 // behavior is unspecified. 5427 if (Result && Result->isZero()) { 5428 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5429 << Step << Step->getSourceRange(); 5430 IsCorrect = false; 5431 continue; 5432 } 5433 } 5434 if (!Begin || !End || !IsCorrect) { 5435 IsCorrect = false; 5436 continue; 5437 } 5438 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5439 IDElem.IteratorDecl = VD; 5440 IDElem.AssignmentLoc = D.AssignLoc; 5441 IDElem.Range.Begin = Begin; 5442 IDElem.Range.End = End; 5443 IDElem.Range.Step = Step; 5444 IDElem.ColonLoc = D.ColonLoc; 5445 IDElem.SecondColonLoc = D.SecColonLoc; 5446 } 5447 if (!IsCorrect) { 5448 // Invalidate all created iterator declarations if error is found. 5449 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5450 if (Decl *ID = D.IteratorDecl) 5451 ID->setInvalidDecl(); 5452 } 5453 return ExprError(); 5454 } 5455 SmallVector<OMPIteratorHelperData, 4> Helpers; 5456 if (!CurContext->isDependentContext()) { 5457 // Build number of ityeration for each iteration range. 5458 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5459 // ((Begini-Stepi-1-Endi) / -Stepi); 5460 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5461 // (Endi - Begini) 5462 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5463 D.Range.Begin); 5464 if(!Res.isUsable()) { 5465 IsCorrect = false; 5466 continue; 5467 } 5468 ExprResult St, St1; 5469 if (D.Range.Step) { 5470 St = D.Range.Step; 5471 // (Endi - Begini) + Stepi 5472 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5473 if (!Res.isUsable()) { 5474 IsCorrect = false; 5475 continue; 5476 } 5477 // (Endi - Begini) + Stepi - 1 5478 Res = 5479 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5480 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5481 if (!Res.isUsable()) { 5482 IsCorrect = false; 5483 continue; 5484 } 5485 // ((Endi - Begini) + Stepi - 1) / Stepi 5486 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5487 if (!Res.isUsable()) { 5488 IsCorrect = false; 5489 continue; 5490 } 5491 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5492 // (Begini - Endi) 5493 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5494 D.Range.Begin, D.Range.End); 5495 if (!Res1.isUsable()) { 5496 IsCorrect = false; 5497 continue; 5498 } 5499 // (Begini - Endi) - Stepi 5500 Res1 = 5501 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5502 if (!Res1.isUsable()) { 5503 IsCorrect = false; 5504 continue; 5505 } 5506 // (Begini - Endi) - Stepi - 1 5507 Res1 = 5508 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5509 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5510 if (!Res1.isUsable()) { 5511 IsCorrect = false; 5512 continue; 5513 } 5514 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5515 Res1 = 5516 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5517 if (!Res1.isUsable()) { 5518 IsCorrect = false; 5519 continue; 5520 } 5521 // Stepi > 0. 5522 ExprResult CmpRes = 5523 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5524 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5525 if (!CmpRes.isUsable()) { 5526 IsCorrect = false; 5527 continue; 5528 } 5529 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5530 Res.get(), Res1.get()); 5531 if (!Res.isUsable()) { 5532 IsCorrect = false; 5533 continue; 5534 } 5535 } 5536 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5537 if (!Res.isUsable()) { 5538 IsCorrect = false; 5539 continue; 5540 } 5541 5542 // Build counter update. 5543 // Build counter. 5544 auto *CounterVD = 5545 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5546 D.IteratorDecl->getBeginLoc(), nullptr, 5547 Res.get()->getType(), nullptr, SC_None); 5548 CounterVD->setImplicit(); 5549 ExprResult RefRes = 5550 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5551 D.IteratorDecl->getBeginLoc()); 5552 // Build counter update. 5553 // I = Begini + counter * Stepi; 5554 ExprResult UpdateRes; 5555 if (D.Range.Step) { 5556 UpdateRes = CreateBuiltinBinOp( 5557 D.AssignmentLoc, BO_Mul, 5558 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5559 } else { 5560 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5561 } 5562 if (!UpdateRes.isUsable()) { 5563 IsCorrect = false; 5564 continue; 5565 } 5566 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5567 UpdateRes.get()); 5568 if (!UpdateRes.isUsable()) { 5569 IsCorrect = false; 5570 continue; 5571 } 5572 ExprResult VDRes = 5573 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5574 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5575 D.IteratorDecl->getBeginLoc()); 5576 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5577 UpdateRes.get()); 5578 if (!UpdateRes.isUsable()) { 5579 IsCorrect = false; 5580 continue; 5581 } 5582 UpdateRes = 5583 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5584 if (!UpdateRes.isUsable()) { 5585 IsCorrect = false; 5586 continue; 5587 } 5588 ExprResult CounterUpdateRes = 5589 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5590 if (!CounterUpdateRes.isUsable()) { 5591 IsCorrect = false; 5592 continue; 5593 } 5594 CounterUpdateRes = 5595 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5596 if (!CounterUpdateRes.isUsable()) { 5597 IsCorrect = false; 5598 continue; 5599 } 5600 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5601 HD.CounterVD = CounterVD; 5602 HD.Upper = Res.get(); 5603 HD.Update = UpdateRes.get(); 5604 HD.CounterUpdate = CounterUpdateRes.get(); 5605 } 5606 } else { 5607 Helpers.assign(ID.size(), {}); 5608 } 5609 if (!IsCorrect) { 5610 // Invalidate all created iterator declarations if error is found. 5611 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5612 if (Decl *ID = D.IteratorDecl) 5613 ID->setInvalidDecl(); 5614 } 5615 return ExprError(); 5616 } 5617 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5618 LLoc, RLoc, ID, Helpers); 5619 } 5620 5621 ExprResult 5622 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5623 Expr *Idx, SourceLocation RLoc) { 5624 Expr *LHSExp = Base; 5625 Expr *RHSExp = Idx; 5626 5627 ExprValueKind VK = VK_LValue; 5628 ExprObjectKind OK = OK_Ordinary; 5629 5630 // Per C++ core issue 1213, the result is an xvalue if either operand is 5631 // a non-lvalue array, and an lvalue otherwise. 5632 if (getLangOpts().CPlusPlus11) { 5633 for (auto *Op : {LHSExp, RHSExp}) { 5634 Op = Op->IgnoreImplicit(); 5635 if (Op->getType()->isArrayType() && !Op->isLValue()) 5636 VK = VK_XValue; 5637 } 5638 } 5639 5640 // Perform default conversions. 5641 if (!LHSExp->getType()->getAs<VectorType>()) { 5642 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5643 if (Result.isInvalid()) 5644 return ExprError(); 5645 LHSExp = Result.get(); 5646 } 5647 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5648 if (Result.isInvalid()) 5649 return ExprError(); 5650 RHSExp = Result.get(); 5651 5652 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5653 5654 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5655 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5656 // in the subscript position. As a result, we need to derive the array base 5657 // and index from the expression types. 5658 Expr *BaseExpr, *IndexExpr; 5659 QualType ResultType; 5660 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5661 BaseExpr = LHSExp; 5662 IndexExpr = RHSExp; 5663 ResultType = 5664 getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext()); 5665 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5666 BaseExpr = LHSExp; 5667 IndexExpr = RHSExp; 5668 ResultType = PTy->getPointeeType(); 5669 } else if (const ObjCObjectPointerType *PTy = 5670 LHSTy->getAs<ObjCObjectPointerType>()) { 5671 BaseExpr = LHSExp; 5672 IndexExpr = RHSExp; 5673 5674 // Use custom logic if this should be the pseudo-object subscript 5675 // expression. 5676 if (!LangOpts.isSubscriptPointerArithmetic()) 5677 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5678 nullptr); 5679 5680 ResultType = PTy->getPointeeType(); 5681 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5682 // Handle the uncommon case of "123[Ptr]". 5683 BaseExpr = RHSExp; 5684 IndexExpr = LHSExp; 5685 ResultType = PTy->getPointeeType(); 5686 } else if (const ObjCObjectPointerType *PTy = 5687 RHSTy->getAs<ObjCObjectPointerType>()) { 5688 // Handle the uncommon case of "123[Ptr]". 5689 BaseExpr = RHSExp; 5690 IndexExpr = LHSExp; 5691 ResultType = PTy->getPointeeType(); 5692 if (!LangOpts.isSubscriptPointerArithmetic()) { 5693 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5694 << ResultType << BaseExpr->getSourceRange(); 5695 return ExprError(); 5696 } 5697 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5698 BaseExpr = LHSExp; // vectors: V[123] 5699 IndexExpr = RHSExp; 5700 // We apply C++ DR1213 to vector subscripting too. 5701 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5702 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5703 if (Materialized.isInvalid()) 5704 return ExprError(); 5705 LHSExp = Materialized.get(); 5706 } 5707 VK = LHSExp->getValueKind(); 5708 if (VK != VK_PRValue) 5709 OK = OK_VectorComponent; 5710 5711 ResultType = VTy->getElementType(); 5712 QualType BaseType = BaseExpr->getType(); 5713 Qualifiers BaseQuals = BaseType.getQualifiers(); 5714 Qualifiers MemberQuals = ResultType.getQualifiers(); 5715 Qualifiers Combined = BaseQuals + MemberQuals; 5716 if (Combined != MemberQuals) 5717 ResultType = Context.getQualifiedType(ResultType, Combined); 5718 } else if (LHSTy->isBuiltinType() && 5719 LHSTy->getAs<BuiltinType>()->isVLSTBuiltinType()) { 5720 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>(); 5721 if (BTy->isSVEBool()) 5722 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t) 5723 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5724 5725 BaseExpr = LHSExp; 5726 IndexExpr = RHSExp; 5727 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5728 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5729 if (Materialized.isInvalid()) 5730 return ExprError(); 5731 LHSExp = Materialized.get(); 5732 } 5733 VK = LHSExp->getValueKind(); 5734 if (VK != VK_PRValue) 5735 OK = OK_VectorComponent; 5736 5737 ResultType = BTy->getSveEltType(Context); 5738 5739 QualType BaseType = BaseExpr->getType(); 5740 Qualifiers BaseQuals = BaseType.getQualifiers(); 5741 Qualifiers MemberQuals = ResultType.getQualifiers(); 5742 Qualifiers Combined = BaseQuals + MemberQuals; 5743 if (Combined != MemberQuals) 5744 ResultType = Context.getQualifiedType(ResultType, Combined); 5745 } else if (LHSTy->isArrayType()) { 5746 // If we see an array that wasn't promoted by 5747 // DefaultFunctionArrayLvalueConversion, it must be an array that 5748 // wasn't promoted because of the C90 rule that doesn't 5749 // allow promoting non-lvalue arrays. Warn, then 5750 // force the promotion here. 5751 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5752 << LHSExp->getSourceRange(); 5753 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5754 CK_ArrayToPointerDecay).get(); 5755 LHSTy = LHSExp->getType(); 5756 5757 BaseExpr = LHSExp; 5758 IndexExpr = RHSExp; 5759 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5760 } else if (RHSTy->isArrayType()) { 5761 // Same as previous, except for 123[f().a] case 5762 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5763 << RHSExp->getSourceRange(); 5764 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5765 CK_ArrayToPointerDecay).get(); 5766 RHSTy = RHSExp->getType(); 5767 5768 BaseExpr = RHSExp; 5769 IndexExpr = LHSExp; 5770 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5771 } else { 5772 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5773 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5774 } 5775 // C99 6.5.2.1p1 5776 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5777 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5778 << IndexExpr->getSourceRange()); 5779 5780 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5781 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5782 && !IndexExpr->isTypeDependent()) 5783 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5784 5785 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5786 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5787 // type. Note that Functions are not objects, and that (in C99 parlance) 5788 // incomplete types are not object types. 5789 if (ResultType->isFunctionType()) { 5790 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5791 << ResultType << BaseExpr->getSourceRange(); 5792 return ExprError(); 5793 } 5794 5795 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5796 // GNU extension: subscripting on pointer to void 5797 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5798 << BaseExpr->getSourceRange(); 5799 5800 // C forbids expressions of unqualified void type from being l-values. 5801 // See IsCForbiddenLValueType. 5802 if (!ResultType.hasQualifiers()) 5803 VK = VK_PRValue; 5804 } else if (!ResultType->isDependentType() && 5805 RequireCompleteSizedType( 5806 LLoc, ResultType, 5807 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5808 return ExprError(); 5809 5810 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 5811 !ResultType.isCForbiddenLValueType()); 5812 5813 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5814 FunctionScopes.size() > 1) { 5815 if (auto *TT = 5816 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5817 for (auto I = FunctionScopes.rbegin(), 5818 E = std::prev(FunctionScopes.rend()); 5819 I != E; ++I) { 5820 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5821 if (CSI == nullptr) 5822 break; 5823 DeclContext *DC = nullptr; 5824 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5825 DC = LSI->CallOperator; 5826 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5827 DC = CRSI->TheCapturedDecl; 5828 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5829 DC = BSI->TheDecl; 5830 if (DC) { 5831 if (DC->containsDecl(TT->getDecl())) 5832 break; 5833 captureVariablyModifiedType( 5834 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5835 } 5836 } 5837 } 5838 } 5839 5840 return new (Context) 5841 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5842 } 5843 5844 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5845 ParmVarDecl *Param) { 5846 if (Param->hasUnparsedDefaultArg()) { 5847 // If we've already cleared out the location for the default argument, 5848 // that means we're parsing it right now. 5849 if (!UnparsedDefaultArgLocs.count(Param)) { 5850 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5851 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5852 Param->setInvalidDecl(); 5853 return true; 5854 } 5855 5856 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5857 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5858 Diag(UnparsedDefaultArgLocs[Param], 5859 diag::note_default_argument_declared_here); 5860 return true; 5861 } 5862 5863 if (Param->hasUninstantiatedDefaultArg() && 5864 InstantiateDefaultArgument(CallLoc, FD, Param)) 5865 return true; 5866 5867 assert(Param->hasInit() && "default argument but no initializer?"); 5868 5869 // If the default expression creates temporaries, we need to 5870 // push them to the current stack of expression temporaries so they'll 5871 // be properly destroyed. 5872 // FIXME: We should really be rebuilding the default argument with new 5873 // bound temporaries; see the comment in PR5810. 5874 // We don't need to do that with block decls, though, because 5875 // blocks in default argument expression can never capture anything. 5876 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5877 // Set the "needs cleanups" bit regardless of whether there are 5878 // any explicit objects. 5879 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5880 5881 // Append all the objects to the cleanup list. Right now, this 5882 // should always be a no-op, because blocks in default argument 5883 // expressions should never be able to capture anything. 5884 assert(!Init->getNumObjects() && 5885 "default argument expression has capturing blocks?"); 5886 } 5887 5888 // We already type-checked the argument, so we know it works. 5889 // Just mark all of the declarations in this potentially-evaluated expression 5890 // as being "referenced". 5891 EnterExpressionEvaluationContext EvalContext( 5892 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5893 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5894 /*SkipLocalVariables=*/true); 5895 return false; 5896 } 5897 5898 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5899 FunctionDecl *FD, ParmVarDecl *Param) { 5900 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5901 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5902 return ExprError(); 5903 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5904 } 5905 5906 Sema::VariadicCallType 5907 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5908 Expr *Fn) { 5909 if (Proto && Proto->isVariadic()) { 5910 if (isa_and_nonnull<CXXConstructorDecl>(FDecl)) 5911 return VariadicConstructor; 5912 else if (Fn && Fn->getType()->isBlockPointerType()) 5913 return VariadicBlock; 5914 else if (FDecl) { 5915 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5916 if (Method->isInstance()) 5917 return VariadicMethod; 5918 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5919 return VariadicMethod; 5920 return VariadicFunction; 5921 } 5922 return VariadicDoesNotApply; 5923 } 5924 5925 namespace { 5926 class FunctionCallCCC final : public FunctionCallFilterCCC { 5927 public: 5928 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5929 unsigned NumArgs, MemberExpr *ME) 5930 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5931 FunctionName(FuncName) {} 5932 5933 bool ValidateCandidate(const TypoCorrection &candidate) override { 5934 if (!candidate.getCorrectionSpecifier() || 5935 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5936 return false; 5937 } 5938 5939 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5940 } 5941 5942 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5943 return std::make_unique<FunctionCallCCC>(*this); 5944 } 5945 5946 private: 5947 const IdentifierInfo *const FunctionName; 5948 }; 5949 } 5950 5951 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5952 FunctionDecl *FDecl, 5953 ArrayRef<Expr *> Args) { 5954 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5955 DeclarationName FuncName = FDecl->getDeclName(); 5956 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5957 5958 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5959 if (TypoCorrection Corrected = S.CorrectTypo( 5960 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5961 S.getScopeForContext(S.CurContext), nullptr, CCC, 5962 Sema::CTK_ErrorRecovery)) { 5963 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5964 if (Corrected.isOverloaded()) { 5965 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5966 OverloadCandidateSet::iterator Best; 5967 for (NamedDecl *CD : Corrected) { 5968 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5969 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5970 OCS); 5971 } 5972 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5973 case OR_Success: 5974 ND = Best->FoundDecl; 5975 Corrected.setCorrectionDecl(ND); 5976 break; 5977 default: 5978 break; 5979 } 5980 } 5981 ND = ND->getUnderlyingDecl(); 5982 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5983 return Corrected; 5984 } 5985 } 5986 return TypoCorrection(); 5987 } 5988 5989 /// ConvertArgumentsForCall - Converts the arguments specified in 5990 /// Args/NumArgs to the parameter types of the function FDecl with 5991 /// function prototype Proto. Call is the call expression itself, and 5992 /// Fn is the function expression. For a C++ member function, this 5993 /// routine does not attempt to convert the object argument. Returns 5994 /// true if the call is ill-formed. 5995 bool 5996 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5997 FunctionDecl *FDecl, 5998 const FunctionProtoType *Proto, 5999 ArrayRef<Expr *> Args, 6000 SourceLocation RParenLoc, 6001 bool IsExecConfig) { 6002 // Bail out early if calling a builtin with custom typechecking. 6003 if (FDecl) 6004 if (unsigned ID = FDecl->getBuiltinID()) 6005 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 6006 return false; 6007 6008 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 6009 // assignment, to the types of the corresponding parameter, ... 6010 unsigned NumParams = Proto->getNumParams(); 6011 bool Invalid = false; 6012 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 6013 unsigned FnKind = Fn->getType()->isBlockPointerType() 6014 ? 1 /* block */ 6015 : (IsExecConfig ? 3 /* kernel function (exec config) */ 6016 : 0 /* function */); 6017 6018 // If too few arguments are available (and we don't have default 6019 // arguments for the remaining parameters), don't make the call. 6020 if (Args.size() < NumParams) { 6021 if (Args.size() < MinArgs) { 6022 TypoCorrection TC; 6023 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 6024 unsigned diag_id = 6025 MinArgs == NumParams && !Proto->isVariadic() 6026 ? diag::err_typecheck_call_too_few_args_suggest 6027 : diag::err_typecheck_call_too_few_args_at_least_suggest; 6028 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 6029 << static_cast<unsigned>(Args.size()) 6030 << TC.getCorrectionRange()); 6031 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 6032 Diag(RParenLoc, 6033 MinArgs == NumParams && !Proto->isVariadic() 6034 ? diag::err_typecheck_call_too_few_args_one 6035 : diag::err_typecheck_call_too_few_args_at_least_one) 6036 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 6037 else 6038 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 6039 ? diag::err_typecheck_call_too_few_args 6040 : diag::err_typecheck_call_too_few_args_at_least) 6041 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 6042 << Fn->getSourceRange(); 6043 6044 // Emit the location of the prototype. 6045 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 6046 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6047 6048 return true; 6049 } 6050 // We reserve space for the default arguments when we create 6051 // the call expression, before calling ConvertArgumentsForCall. 6052 assert((Call->getNumArgs() == NumParams) && 6053 "We should have reserved space for the default arguments before!"); 6054 } 6055 6056 // If too many are passed and not variadic, error on the extras and drop 6057 // them. 6058 if (Args.size() > NumParams) { 6059 if (!Proto->isVariadic()) { 6060 TypoCorrection TC; 6061 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 6062 unsigned diag_id = 6063 MinArgs == NumParams && !Proto->isVariadic() 6064 ? diag::err_typecheck_call_too_many_args_suggest 6065 : diag::err_typecheck_call_too_many_args_at_most_suggest; 6066 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 6067 << static_cast<unsigned>(Args.size()) 6068 << TC.getCorrectionRange()); 6069 } else if (NumParams == 1 && FDecl && 6070 FDecl->getParamDecl(0)->getDeclName()) 6071 Diag(Args[NumParams]->getBeginLoc(), 6072 MinArgs == NumParams 6073 ? diag::err_typecheck_call_too_many_args_one 6074 : diag::err_typecheck_call_too_many_args_at_most_one) 6075 << FnKind << FDecl->getParamDecl(0) 6076 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 6077 << SourceRange(Args[NumParams]->getBeginLoc(), 6078 Args.back()->getEndLoc()); 6079 else 6080 Diag(Args[NumParams]->getBeginLoc(), 6081 MinArgs == NumParams 6082 ? diag::err_typecheck_call_too_many_args 6083 : diag::err_typecheck_call_too_many_args_at_most) 6084 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 6085 << Fn->getSourceRange() 6086 << SourceRange(Args[NumParams]->getBeginLoc(), 6087 Args.back()->getEndLoc()); 6088 6089 // Emit the location of the prototype. 6090 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 6091 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6092 6093 // This deletes the extra arguments. 6094 Call->shrinkNumArgs(NumParams); 6095 return true; 6096 } 6097 } 6098 SmallVector<Expr *, 8> AllArgs; 6099 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 6100 6101 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 6102 AllArgs, CallType); 6103 if (Invalid) 6104 return true; 6105 unsigned TotalNumArgs = AllArgs.size(); 6106 for (unsigned i = 0; i < TotalNumArgs; ++i) 6107 Call->setArg(i, AllArgs[i]); 6108 6109 Call->computeDependence(); 6110 return false; 6111 } 6112 6113 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 6114 const FunctionProtoType *Proto, 6115 unsigned FirstParam, ArrayRef<Expr *> Args, 6116 SmallVectorImpl<Expr *> &AllArgs, 6117 VariadicCallType CallType, bool AllowExplicit, 6118 bool IsListInitialization) { 6119 unsigned NumParams = Proto->getNumParams(); 6120 bool Invalid = false; 6121 size_t ArgIx = 0; 6122 // Continue to check argument types (even if we have too few/many args). 6123 for (unsigned i = FirstParam; i < NumParams; i++) { 6124 QualType ProtoArgType = Proto->getParamType(i); 6125 6126 Expr *Arg; 6127 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 6128 if (ArgIx < Args.size()) { 6129 Arg = Args[ArgIx++]; 6130 6131 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 6132 diag::err_call_incomplete_argument, Arg)) 6133 return true; 6134 6135 // Strip the unbridged-cast placeholder expression off, if applicable. 6136 bool CFAudited = false; 6137 if (Arg->getType() == Context.ARCUnbridgedCastTy && 6138 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 6139 (!Param || !Param->hasAttr<CFConsumedAttr>())) 6140 Arg = stripARCUnbridgedCast(Arg); 6141 else if (getLangOpts().ObjCAutoRefCount && 6142 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 6143 (!Param || !Param->hasAttr<CFConsumedAttr>())) 6144 CFAudited = true; 6145 6146 if (Proto->getExtParameterInfo(i).isNoEscape() && 6147 ProtoArgType->isBlockPointerType()) 6148 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 6149 BE->getBlockDecl()->setDoesNotEscape(); 6150 6151 InitializedEntity Entity = 6152 Param ? InitializedEntity::InitializeParameter(Context, Param, 6153 ProtoArgType) 6154 : InitializedEntity::InitializeParameter( 6155 Context, ProtoArgType, Proto->isParamConsumed(i)); 6156 6157 // Remember that parameter belongs to a CF audited API. 6158 if (CFAudited) 6159 Entity.setParameterCFAudited(); 6160 6161 ExprResult ArgE = PerformCopyInitialization( 6162 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 6163 if (ArgE.isInvalid()) 6164 return true; 6165 6166 Arg = ArgE.getAs<Expr>(); 6167 } else { 6168 assert(Param && "can't use default arguments without a known callee"); 6169 6170 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 6171 if (ArgExpr.isInvalid()) 6172 return true; 6173 6174 Arg = ArgExpr.getAs<Expr>(); 6175 } 6176 6177 // Check for array bounds violations for each argument to the call. This 6178 // check only triggers warnings when the argument isn't a more complex Expr 6179 // with its own checking, such as a BinaryOperator. 6180 CheckArrayAccess(Arg); 6181 6182 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 6183 CheckStaticArrayArgument(CallLoc, Param, Arg); 6184 6185 AllArgs.push_back(Arg); 6186 } 6187 6188 // If this is a variadic call, handle args passed through "...". 6189 if (CallType != VariadicDoesNotApply) { 6190 // Assume that extern "C" functions with variadic arguments that 6191 // return __unknown_anytype aren't *really* variadic. 6192 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 6193 FDecl->isExternC()) { 6194 for (Expr *A : Args.slice(ArgIx)) { 6195 QualType paramType; // ignored 6196 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 6197 Invalid |= arg.isInvalid(); 6198 AllArgs.push_back(arg.get()); 6199 } 6200 6201 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6202 } else { 6203 for (Expr *A : Args.slice(ArgIx)) { 6204 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6205 Invalid |= Arg.isInvalid(); 6206 AllArgs.push_back(Arg.get()); 6207 } 6208 } 6209 6210 // Check for array bounds violations. 6211 for (Expr *A : Args.slice(ArgIx)) 6212 CheckArrayAccess(A); 6213 } 6214 return Invalid; 6215 } 6216 6217 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6218 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6219 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6220 TL = DTL.getOriginalLoc(); 6221 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6222 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6223 << ATL.getLocalSourceRange(); 6224 } 6225 6226 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6227 /// array parameter, check that it is non-null, and that if it is formed by 6228 /// array-to-pointer decay, the underlying array is sufficiently large. 6229 /// 6230 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6231 /// array type derivation, then for each call to the function, the value of the 6232 /// corresponding actual argument shall provide access to the first element of 6233 /// an array with at least as many elements as specified by the size expression. 6234 void 6235 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6236 ParmVarDecl *Param, 6237 const Expr *ArgExpr) { 6238 // Static array parameters are not supported in C++. 6239 if (!Param || getLangOpts().CPlusPlus) 6240 return; 6241 6242 QualType OrigTy = Param->getOriginalType(); 6243 6244 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6245 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6246 return; 6247 6248 if (ArgExpr->isNullPointerConstant(Context, 6249 Expr::NPC_NeverValueDependent)) { 6250 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6251 DiagnoseCalleeStaticArrayParam(*this, Param); 6252 return; 6253 } 6254 6255 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6256 if (!CAT) 6257 return; 6258 6259 const ConstantArrayType *ArgCAT = 6260 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6261 if (!ArgCAT) 6262 return; 6263 6264 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6265 ArgCAT->getElementType())) { 6266 if (ArgCAT->getSize().ult(CAT->getSize())) { 6267 Diag(CallLoc, diag::warn_static_array_too_small) 6268 << ArgExpr->getSourceRange() 6269 << (unsigned)ArgCAT->getSize().getZExtValue() 6270 << (unsigned)CAT->getSize().getZExtValue() << 0; 6271 DiagnoseCalleeStaticArrayParam(*this, Param); 6272 } 6273 return; 6274 } 6275 6276 Optional<CharUnits> ArgSize = 6277 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6278 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6279 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6280 Diag(CallLoc, diag::warn_static_array_too_small) 6281 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6282 << (unsigned)ParmSize->getQuantity() << 1; 6283 DiagnoseCalleeStaticArrayParam(*this, Param); 6284 } 6285 } 6286 6287 /// Given a function expression of unknown-any type, try to rebuild it 6288 /// to have a function type. 6289 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6290 6291 /// Is the given type a placeholder that we need to lower out 6292 /// immediately during argument processing? 6293 static bool isPlaceholderToRemoveAsArg(QualType type) { 6294 // Placeholders are never sugared. 6295 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6296 if (!placeholder) return false; 6297 6298 switch (placeholder->getKind()) { 6299 // Ignore all the non-placeholder types. 6300 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6301 case BuiltinType::Id: 6302 #include "clang/Basic/OpenCLImageTypes.def" 6303 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6304 case BuiltinType::Id: 6305 #include "clang/Basic/OpenCLExtensionTypes.def" 6306 // In practice we'll never use this, since all SVE types are sugared 6307 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6308 #define SVE_TYPE(Name, Id, SingletonId) \ 6309 case BuiltinType::Id: 6310 #include "clang/Basic/AArch64SVEACLETypes.def" 6311 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6312 case BuiltinType::Id: 6313 #include "clang/Basic/PPCTypes.def" 6314 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6315 #include "clang/Basic/RISCVVTypes.def" 6316 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6317 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6318 #include "clang/AST/BuiltinTypes.def" 6319 return false; 6320 6321 // We cannot lower out overload sets; they might validly be resolved 6322 // by the call machinery. 6323 case BuiltinType::Overload: 6324 return false; 6325 6326 // Unbridged casts in ARC can be handled in some call positions and 6327 // should be left in place. 6328 case BuiltinType::ARCUnbridgedCast: 6329 return false; 6330 6331 // Pseudo-objects should be converted as soon as possible. 6332 case BuiltinType::PseudoObject: 6333 return true; 6334 6335 // The debugger mode could theoretically but currently does not try 6336 // to resolve unknown-typed arguments based on known parameter types. 6337 case BuiltinType::UnknownAny: 6338 return true; 6339 6340 // These are always invalid as call arguments and should be reported. 6341 case BuiltinType::BoundMember: 6342 case BuiltinType::BuiltinFn: 6343 case BuiltinType::IncompleteMatrixIdx: 6344 case BuiltinType::OMPArraySection: 6345 case BuiltinType::OMPArrayShaping: 6346 case BuiltinType::OMPIterator: 6347 return true; 6348 6349 } 6350 llvm_unreachable("bad builtin type kind"); 6351 } 6352 6353 /// Check an argument list for placeholders that we won't try to 6354 /// handle later. 6355 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6356 // Apply this processing to all the arguments at once instead of 6357 // dying at the first failure. 6358 bool hasInvalid = false; 6359 for (size_t i = 0, e = args.size(); i != e; i++) { 6360 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6361 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6362 if (result.isInvalid()) hasInvalid = true; 6363 else args[i] = result.get(); 6364 } 6365 } 6366 return hasInvalid; 6367 } 6368 6369 /// If a builtin function has a pointer argument with no explicit address 6370 /// space, then it should be able to accept a pointer to any address 6371 /// space as input. In order to do this, we need to replace the 6372 /// standard builtin declaration with one that uses the same address space 6373 /// as the call. 6374 /// 6375 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6376 /// it does not contain any pointer arguments without 6377 /// an address space qualifer. Otherwise the rewritten 6378 /// FunctionDecl is returned. 6379 /// TODO: Handle pointer return types. 6380 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6381 FunctionDecl *FDecl, 6382 MultiExprArg ArgExprs) { 6383 6384 QualType DeclType = FDecl->getType(); 6385 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6386 6387 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6388 ArgExprs.size() < FT->getNumParams()) 6389 return nullptr; 6390 6391 bool NeedsNewDecl = false; 6392 unsigned i = 0; 6393 SmallVector<QualType, 8> OverloadParams; 6394 6395 for (QualType ParamType : FT->param_types()) { 6396 6397 // Convert array arguments to pointer to simplify type lookup. 6398 ExprResult ArgRes = 6399 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6400 if (ArgRes.isInvalid()) 6401 return nullptr; 6402 Expr *Arg = ArgRes.get(); 6403 QualType ArgType = Arg->getType(); 6404 if (!ParamType->isPointerType() || 6405 ParamType.hasAddressSpace() || 6406 !ArgType->isPointerType() || 6407 !ArgType->getPointeeType().hasAddressSpace()) { 6408 OverloadParams.push_back(ParamType); 6409 continue; 6410 } 6411 6412 QualType PointeeType = ParamType->getPointeeType(); 6413 if (PointeeType.hasAddressSpace()) 6414 continue; 6415 6416 NeedsNewDecl = true; 6417 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6418 6419 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6420 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6421 } 6422 6423 if (!NeedsNewDecl) 6424 return nullptr; 6425 6426 FunctionProtoType::ExtProtoInfo EPI; 6427 EPI.Variadic = FT->isVariadic(); 6428 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6429 OverloadParams, EPI); 6430 DeclContext *Parent = FDecl->getParent(); 6431 FunctionDecl *OverloadDecl = FunctionDecl::Create( 6432 Context, Parent, FDecl->getLocation(), FDecl->getLocation(), 6433 FDecl->getIdentifier(), OverloadTy, 6434 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), 6435 false, 6436 /*hasPrototype=*/true); 6437 SmallVector<ParmVarDecl*, 16> Params; 6438 FT = cast<FunctionProtoType>(OverloadTy); 6439 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6440 QualType ParamType = FT->getParamType(i); 6441 ParmVarDecl *Parm = 6442 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6443 SourceLocation(), nullptr, ParamType, 6444 /*TInfo=*/nullptr, SC_None, nullptr); 6445 Parm->setScopeInfo(0, i); 6446 Params.push_back(Parm); 6447 } 6448 OverloadDecl->setParams(Params); 6449 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6450 return OverloadDecl; 6451 } 6452 6453 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6454 FunctionDecl *Callee, 6455 MultiExprArg ArgExprs) { 6456 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6457 // similar attributes) really don't like it when functions are called with an 6458 // invalid number of args. 6459 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6460 /*PartialOverloading=*/false) && 6461 !Callee->isVariadic()) 6462 return; 6463 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6464 return; 6465 6466 if (const EnableIfAttr *Attr = 6467 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6468 S.Diag(Fn->getBeginLoc(), 6469 isa<CXXMethodDecl>(Callee) 6470 ? diag::err_ovl_no_viable_member_function_in_call 6471 : diag::err_ovl_no_viable_function_in_call) 6472 << Callee << Callee->getSourceRange(); 6473 S.Diag(Callee->getLocation(), 6474 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6475 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6476 return; 6477 } 6478 } 6479 6480 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6481 const UnresolvedMemberExpr *const UME, Sema &S) { 6482 6483 const auto GetFunctionLevelDCIfCXXClass = 6484 [](Sema &S) -> const CXXRecordDecl * { 6485 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6486 if (!DC || !DC->getParent()) 6487 return nullptr; 6488 6489 // If the call to some member function was made from within a member 6490 // function body 'M' return return 'M's parent. 6491 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6492 return MD->getParent()->getCanonicalDecl(); 6493 // else the call was made from within a default member initializer of a 6494 // class, so return the class. 6495 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6496 return RD->getCanonicalDecl(); 6497 return nullptr; 6498 }; 6499 // If our DeclContext is neither a member function nor a class (in the 6500 // case of a lambda in a default member initializer), we can't have an 6501 // enclosing 'this'. 6502 6503 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6504 if (!CurParentClass) 6505 return false; 6506 6507 // The naming class for implicit member functions call is the class in which 6508 // name lookup starts. 6509 const CXXRecordDecl *const NamingClass = 6510 UME->getNamingClass()->getCanonicalDecl(); 6511 assert(NamingClass && "Must have naming class even for implicit access"); 6512 6513 // If the unresolved member functions were found in a 'naming class' that is 6514 // related (either the same or derived from) to the class that contains the 6515 // member function that itself contained the implicit member access. 6516 6517 return CurParentClass == NamingClass || 6518 CurParentClass->isDerivedFrom(NamingClass); 6519 } 6520 6521 static void 6522 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6523 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6524 6525 if (!UME) 6526 return; 6527 6528 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6529 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6530 // already been captured, or if this is an implicit member function call (if 6531 // it isn't, an attempt to capture 'this' should already have been made). 6532 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6533 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6534 return; 6535 6536 // Check if the naming class in which the unresolved members were found is 6537 // related (same as or is a base of) to the enclosing class. 6538 6539 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6540 return; 6541 6542 6543 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6544 // If the enclosing function is not dependent, then this lambda is 6545 // capture ready, so if we can capture this, do so. 6546 if (!EnclosingFunctionCtx->isDependentContext()) { 6547 // If the current lambda and all enclosing lambdas can capture 'this' - 6548 // then go ahead and capture 'this' (since our unresolved overload set 6549 // contains at least one non-static member function). 6550 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6551 S.CheckCXXThisCapture(CallLoc); 6552 } else if (S.CurContext->isDependentContext()) { 6553 // ... since this is an implicit member reference, that might potentially 6554 // involve a 'this' capture, mark 'this' for potential capture in 6555 // enclosing lambdas. 6556 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6557 CurLSI->addPotentialThisCapture(CallLoc); 6558 } 6559 } 6560 6561 // Once a call is fully resolved, warn for unqualified calls to specific 6562 // C++ standard functions, like move and forward. 6563 static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) { 6564 // We are only checking unary move and forward so exit early here. 6565 if (Call->getNumArgs() != 1) 6566 return; 6567 6568 Expr *E = Call->getCallee()->IgnoreParenImpCasts(); 6569 if (!E || isa<UnresolvedLookupExpr>(E)) 6570 return; 6571 DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E); 6572 if (!DRE || !DRE->getLocation().isValid()) 6573 return; 6574 6575 if (DRE->getQualifier()) 6576 return; 6577 6578 const FunctionDecl *FD = Call->getDirectCallee(); 6579 if (!FD) 6580 return; 6581 6582 // Only warn for some functions deemed more frequent or problematic. 6583 unsigned BuiltinID = FD->getBuiltinID(); 6584 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward) 6585 return; 6586 6587 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function) 6588 << FD->getQualifiedNameAsString() 6589 << FixItHint::CreateInsertion(DRE->getLocation(), "std::"); 6590 } 6591 6592 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6593 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6594 Expr *ExecConfig) { 6595 ExprResult Call = 6596 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6597 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6598 if (Call.isInvalid()) 6599 return Call; 6600 6601 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6602 // language modes. 6603 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6604 if (ULE->hasExplicitTemplateArgs() && 6605 ULE->decls_begin() == ULE->decls_end()) { 6606 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6607 ? diag::warn_cxx17_compat_adl_only_template_id 6608 : diag::ext_adl_only_template_id) 6609 << ULE->getName(); 6610 } 6611 } 6612 6613 if (LangOpts.OpenMP) 6614 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6615 ExecConfig); 6616 if (LangOpts.CPlusPlus) { 6617 CallExpr *CE = dyn_cast<CallExpr>(Call.get()); 6618 if (CE) 6619 DiagnosedUnqualifiedCallsToStdFunctions(*this, CE); 6620 } 6621 return Call; 6622 } 6623 6624 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6625 /// This provides the location of the left/right parens and a list of comma 6626 /// locations. 6627 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6628 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6629 Expr *ExecConfig, bool IsExecConfig, 6630 bool AllowRecovery) { 6631 // Since this might be a postfix expression, get rid of ParenListExprs. 6632 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6633 if (Result.isInvalid()) return ExprError(); 6634 Fn = Result.get(); 6635 6636 if (checkArgsForPlaceholders(*this, ArgExprs)) 6637 return ExprError(); 6638 6639 if (getLangOpts().CPlusPlus) { 6640 // If this is a pseudo-destructor expression, build the call immediately. 6641 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6642 if (!ArgExprs.empty()) { 6643 // Pseudo-destructor calls should not have any arguments. 6644 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6645 << FixItHint::CreateRemoval( 6646 SourceRange(ArgExprs.front()->getBeginLoc(), 6647 ArgExprs.back()->getEndLoc())); 6648 } 6649 6650 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6651 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6652 } 6653 if (Fn->getType() == Context.PseudoObjectTy) { 6654 ExprResult result = CheckPlaceholderExpr(Fn); 6655 if (result.isInvalid()) return ExprError(); 6656 Fn = result.get(); 6657 } 6658 6659 // Determine whether this is a dependent call inside a C++ template, 6660 // in which case we won't do any semantic analysis now. 6661 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6662 if (ExecConfig) { 6663 return CUDAKernelCallExpr::Create(Context, Fn, 6664 cast<CallExpr>(ExecConfig), ArgExprs, 6665 Context.DependentTy, VK_PRValue, 6666 RParenLoc, CurFPFeatureOverrides()); 6667 } else { 6668 6669 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6670 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6671 Fn->getBeginLoc()); 6672 6673 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6674 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6675 } 6676 } 6677 6678 // Determine whether this is a call to an object (C++ [over.call.object]). 6679 if (Fn->getType()->isRecordType()) 6680 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6681 RParenLoc); 6682 6683 if (Fn->getType() == Context.UnknownAnyTy) { 6684 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6685 if (result.isInvalid()) return ExprError(); 6686 Fn = result.get(); 6687 } 6688 6689 if (Fn->getType() == Context.BoundMemberTy) { 6690 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6691 RParenLoc, ExecConfig, IsExecConfig, 6692 AllowRecovery); 6693 } 6694 } 6695 6696 // Check for overloaded calls. This can happen even in C due to extensions. 6697 if (Fn->getType() == Context.OverloadTy) { 6698 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6699 6700 // We aren't supposed to apply this logic if there's an '&' involved. 6701 if (!find.HasFormOfMemberPointer) { 6702 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6703 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6704 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6705 OverloadExpr *ovl = find.Expression; 6706 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6707 return BuildOverloadedCallExpr( 6708 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6709 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6710 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6711 RParenLoc, ExecConfig, IsExecConfig, 6712 AllowRecovery); 6713 } 6714 } 6715 6716 // If we're directly calling a function, get the appropriate declaration. 6717 if (Fn->getType() == Context.UnknownAnyTy) { 6718 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6719 if (result.isInvalid()) return ExprError(); 6720 Fn = result.get(); 6721 } 6722 6723 Expr *NakedFn = Fn->IgnoreParens(); 6724 6725 bool CallingNDeclIndirectly = false; 6726 NamedDecl *NDecl = nullptr; 6727 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6728 if (UnOp->getOpcode() == UO_AddrOf) { 6729 CallingNDeclIndirectly = true; 6730 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6731 } 6732 } 6733 6734 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6735 NDecl = DRE->getDecl(); 6736 6737 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6738 if (FDecl && FDecl->getBuiltinID()) { 6739 // Rewrite the function decl for this builtin by replacing parameters 6740 // with no explicit address space with the address space of the arguments 6741 // in ArgExprs. 6742 if ((FDecl = 6743 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6744 NDecl = FDecl; 6745 Fn = DeclRefExpr::Create( 6746 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6747 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6748 nullptr, DRE->isNonOdrUse()); 6749 } 6750 } 6751 } else if (isa<MemberExpr>(NakedFn)) 6752 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6753 6754 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6755 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6756 FD, /*Complain=*/true, Fn->getBeginLoc())) 6757 return ExprError(); 6758 6759 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6760 6761 // If this expression is a call to a builtin function in HIP device 6762 // compilation, allow a pointer-type argument to default address space to be 6763 // passed as a pointer-type parameter to a non-default address space. 6764 // If Arg is declared in the default address space and Param is declared 6765 // in a non-default address space, perform an implicit address space cast to 6766 // the parameter type. 6767 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && 6768 FD->getBuiltinID()) { 6769 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) { 6770 ParmVarDecl *Param = FD->getParamDecl(Idx); 6771 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || 6772 !ArgExprs[Idx]->getType()->isPointerType()) 6773 continue; 6774 6775 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); 6776 auto ArgTy = ArgExprs[Idx]->getType(); 6777 auto ArgPtTy = ArgTy->getPointeeType(); 6778 auto ArgAS = ArgPtTy.getAddressSpace(); 6779 6780 // Add address space cast if target address spaces are different 6781 bool NeedImplicitASC = 6782 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling. 6783 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS 6784 // or from specific AS which has target AS matching that of Param. 6785 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS)); 6786 if (!NeedImplicitASC) 6787 continue; 6788 6789 // First, ensure that the Arg is an RValue. 6790 if (ArgExprs[Idx]->isGLValue()) { 6791 ArgExprs[Idx] = ImplicitCastExpr::Create( 6792 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx], 6793 nullptr, VK_PRValue, FPOptionsOverride()); 6794 } 6795 6796 // Construct a new arg type with address space of Param 6797 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); 6798 ArgPtQuals.setAddressSpace(ParamAS); 6799 auto NewArgPtTy = 6800 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); 6801 auto NewArgTy = 6802 Context.getQualifiedType(Context.getPointerType(NewArgPtTy), 6803 ArgTy.getQualifiers()); 6804 6805 // Finally perform an implicit address space cast 6806 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, 6807 CK_AddressSpaceConversion) 6808 .get(); 6809 } 6810 } 6811 } 6812 6813 if (Context.isDependenceAllowed() && 6814 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6815 assert(!getLangOpts().CPlusPlus); 6816 assert((Fn->containsErrors() || 6817 llvm::any_of(ArgExprs, 6818 [](clang::Expr *E) { return E->containsErrors(); })) && 6819 "should only occur in error-recovery path."); 6820 QualType ReturnType = 6821 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6822 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6823 : Context.DependentTy; 6824 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6825 Expr::getValueKindForType(ReturnType), RParenLoc, 6826 CurFPFeatureOverrides()); 6827 } 6828 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6829 ExecConfig, IsExecConfig); 6830 } 6831 6832 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id 6833 // with the specified CallArgs 6834 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 6835 MultiExprArg CallArgs) { 6836 StringRef Name = Context.BuiltinInfo.getName(Id); 6837 LookupResult R(*this, &Context.Idents.get(Name), Loc, 6838 Sema::LookupOrdinaryName); 6839 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); 6840 6841 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); 6842 assert(BuiltInDecl && "failed to find builtin declaration"); 6843 6844 ExprResult DeclRef = 6845 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); 6846 assert(DeclRef.isUsable() && "Builtin reference cannot fail"); 6847 6848 ExprResult Call = 6849 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); 6850 6851 assert(!Call.isInvalid() && "Call to builtin cannot fail!"); 6852 return Call.get(); 6853 } 6854 6855 /// Parse a __builtin_astype expression. 6856 /// 6857 /// __builtin_astype( value, dst type ) 6858 /// 6859 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6860 SourceLocation BuiltinLoc, 6861 SourceLocation RParenLoc) { 6862 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6863 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6864 } 6865 6866 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6867 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6868 SourceLocation BuiltinLoc, 6869 SourceLocation RParenLoc) { 6870 ExprValueKind VK = VK_PRValue; 6871 ExprObjectKind OK = OK_Ordinary; 6872 QualType SrcTy = E->getType(); 6873 if (!SrcTy->isDependentType() && 6874 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6875 return ExprError( 6876 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6877 << DestTy << SrcTy << E->getSourceRange()); 6878 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6879 } 6880 6881 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6882 /// provided arguments. 6883 /// 6884 /// __builtin_convertvector( value, dst type ) 6885 /// 6886 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6887 SourceLocation BuiltinLoc, 6888 SourceLocation RParenLoc) { 6889 TypeSourceInfo *TInfo; 6890 GetTypeFromParser(ParsedDestTy, &TInfo); 6891 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6892 } 6893 6894 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6895 /// i.e. an expression not of \p OverloadTy. The expression should 6896 /// unary-convert to an expression of function-pointer or 6897 /// block-pointer type. 6898 /// 6899 /// \param NDecl the declaration being called, if available 6900 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6901 SourceLocation LParenLoc, 6902 ArrayRef<Expr *> Args, 6903 SourceLocation RParenLoc, Expr *Config, 6904 bool IsExecConfig, ADLCallKind UsesADL) { 6905 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6906 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6907 6908 // Functions with 'interrupt' attribute cannot be called directly. 6909 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6910 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6911 return ExprError(); 6912 } 6913 6914 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6915 // so there's some risk when calling out to non-interrupt handler functions 6916 // that the callee might not preserve them. This is easy to diagnose here, 6917 // but can be very challenging to debug. 6918 // Likewise, X86 interrupt handlers may only call routines with attribute 6919 // no_caller_saved_registers since there is no efficient way to 6920 // save and restore the non-GPR state. 6921 if (auto *Caller = getCurFunctionDecl()) { 6922 if (Caller->hasAttr<ARMInterruptAttr>()) { 6923 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6924 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6925 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6926 if (FDecl) 6927 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6928 } 6929 } 6930 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6931 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6932 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6933 if (FDecl) 6934 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6935 } 6936 } 6937 6938 // Promote the function operand. 6939 // We special-case function promotion here because we only allow promoting 6940 // builtin functions to function pointers in the callee of a call. 6941 ExprResult Result; 6942 QualType ResultTy; 6943 if (BuiltinID && 6944 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6945 // Extract the return type from the (builtin) function pointer type. 6946 // FIXME Several builtins still have setType in 6947 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6948 // Builtins.def to ensure they are correct before removing setType calls. 6949 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6950 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6951 ResultTy = FDecl->getCallResultType(); 6952 } else { 6953 Result = CallExprUnaryConversions(Fn); 6954 ResultTy = Context.BoolTy; 6955 } 6956 if (Result.isInvalid()) 6957 return ExprError(); 6958 Fn = Result.get(); 6959 6960 // Check for a valid function type, but only if it is not a builtin which 6961 // requires custom type checking. These will be handled by 6962 // CheckBuiltinFunctionCall below just after creation of the call expression. 6963 const FunctionType *FuncT = nullptr; 6964 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6965 retry: 6966 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6967 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6968 // have type pointer to function". 6969 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6970 if (!FuncT) 6971 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6972 << Fn->getType() << Fn->getSourceRange()); 6973 } else if (const BlockPointerType *BPT = 6974 Fn->getType()->getAs<BlockPointerType>()) { 6975 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6976 } else { 6977 // Handle calls to expressions of unknown-any type. 6978 if (Fn->getType() == Context.UnknownAnyTy) { 6979 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6980 if (rewrite.isInvalid()) 6981 return ExprError(); 6982 Fn = rewrite.get(); 6983 goto retry; 6984 } 6985 6986 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6987 << Fn->getType() << Fn->getSourceRange()); 6988 } 6989 } 6990 6991 // Get the number of parameters in the function prototype, if any. 6992 // We will allocate space for max(Args.size(), NumParams) arguments 6993 // in the call expression. 6994 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6995 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6996 6997 CallExpr *TheCall; 6998 if (Config) { 6999 assert(UsesADL == ADLCallKind::NotADL && 7000 "CUDAKernelCallExpr should not use ADL"); 7001 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 7002 Args, ResultTy, VK_PRValue, RParenLoc, 7003 CurFPFeatureOverrides(), NumParams); 7004 } else { 7005 TheCall = 7006 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 7007 CurFPFeatureOverrides(), NumParams, UsesADL); 7008 } 7009 7010 if (!Context.isDependenceAllowed()) { 7011 // Forget about the nulled arguments since typo correction 7012 // do not handle them well. 7013 TheCall->shrinkNumArgs(Args.size()); 7014 // C cannot always handle TypoExpr nodes in builtin calls and direct 7015 // function calls as their argument checking don't necessarily handle 7016 // dependent types properly, so make sure any TypoExprs have been 7017 // dealt with. 7018 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 7019 if (!Result.isUsable()) return ExprError(); 7020 CallExpr *TheOldCall = TheCall; 7021 TheCall = dyn_cast<CallExpr>(Result.get()); 7022 bool CorrectedTypos = TheCall != TheOldCall; 7023 if (!TheCall) return Result; 7024 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 7025 7026 // A new call expression node was created if some typos were corrected. 7027 // However it may not have been constructed with enough storage. In this 7028 // case, rebuild the node with enough storage. The waste of space is 7029 // immaterial since this only happens when some typos were corrected. 7030 if (CorrectedTypos && Args.size() < NumParams) { 7031 if (Config) 7032 TheCall = CUDAKernelCallExpr::Create( 7033 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 7034 RParenLoc, CurFPFeatureOverrides(), NumParams); 7035 else 7036 TheCall = 7037 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 7038 CurFPFeatureOverrides(), NumParams, UsesADL); 7039 } 7040 // We can now handle the nulled arguments for the default arguments. 7041 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 7042 } 7043 7044 // Bail out early if calling a builtin with custom type checking. 7045 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 7046 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 7047 7048 if (getLangOpts().CUDA) { 7049 if (Config) { 7050 // CUDA: Kernel calls must be to global functions 7051 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 7052 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 7053 << FDecl << Fn->getSourceRange()); 7054 7055 // CUDA: Kernel function must have 'void' return type 7056 if (!FuncT->getReturnType()->isVoidType() && 7057 !FuncT->getReturnType()->getAs<AutoType>() && 7058 !FuncT->getReturnType()->isInstantiationDependentType()) 7059 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 7060 << Fn->getType() << Fn->getSourceRange()); 7061 } else { 7062 // CUDA: Calls to global functions must be configured 7063 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 7064 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 7065 << FDecl << Fn->getSourceRange()); 7066 } 7067 } 7068 7069 // Check for a valid return type 7070 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 7071 FDecl)) 7072 return ExprError(); 7073 7074 // We know the result type of the call, set it. 7075 TheCall->setType(FuncT->getCallResultType(Context)); 7076 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 7077 7078 if (Proto) { 7079 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 7080 IsExecConfig)) 7081 return ExprError(); 7082 } else { 7083 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 7084 7085 if (FDecl) { 7086 // Check if we have too few/too many template arguments, based 7087 // on our knowledge of the function definition. 7088 const FunctionDecl *Def = nullptr; 7089 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 7090 Proto = Def->getType()->getAs<FunctionProtoType>(); 7091 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 7092 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 7093 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 7094 } 7095 7096 // If the function we're calling isn't a function prototype, but we have 7097 // a function prototype from a prior declaratiom, use that prototype. 7098 if (!FDecl->hasPrototype()) 7099 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 7100 } 7101 7102 // If we still haven't found a prototype to use but there are arguments to 7103 // the call, diagnose this as calling a function without a prototype. 7104 // However, if we found a function declaration, check to see if 7105 // -Wdeprecated-non-prototype was disabled where the function was declared. 7106 // If so, we will silence the diagnostic here on the assumption that this 7107 // interface is intentional and the user knows what they're doing. We will 7108 // also silence the diagnostic if there is a function declaration but it 7109 // was implicitly defined (the user already gets diagnostics about the 7110 // creation of the implicit function declaration, so the additional warning 7111 // is not helpful). 7112 if (!Proto && !Args.empty() && 7113 (!FDecl || (!FDecl->isImplicit() && 7114 !Diags.isIgnored(diag::warn_strict_uses_without_prototype, 7115 FDecl->getLocation())))) 7116 Diag(LParenLoc, diag::warn_strict_uses_without_prototype) 7117 << (FDecl != nullptr) << FDecl; 7118 7119 // Promote the arguments (C99 6.5.2.2p6). 7120 for (unsigned i = 0, e = Args.size(); i != e; i++) { 7121 Expr *Arg = Args[i]; 7122 7123 if (Proto && i < Proto->getNumParams()) { 7124 InitializedEntity Entity = InitializedEntity::InitializeParameter( 7125 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 7126 ExprResult ArgE = 7127 PerformCopyInitialization(Entity, SourceLocation(), Arg); 7128 if (ArgE.isInvalid()) 7129 return true; 7130 7131 Arg = ArgE.getAs<Expr>(); 7132 7133 } else { 7134 ExprResult ArgE = DefaultArgumentPromotion(Arg); 7135 7136 if (ArgE.isInvalid()) 7137 return true; 7138 7139 Arg = ArgE.getAs<Expr>(); 7140 } 7141 7142 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 7143 diag::err_call_incomplete_argument, Arg)) 7144 return ExprError(); 7145 7146 TheCall->setArg(i, Arg); 7147 } 7148 TheCall->computeDependence(); 7149 } 7150 7151 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 7152 if (!Method->isStatic()) 7153 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 7154 << Fn->getSourceRange()); 7155 7156 // Check for sentinels 7157 if (NDecl) 7158 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 7159 7160 // Warn for unions passing across security boundary (CMSE). 7161 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 7162 for (unsigned i = 0, e = Args.size(); i != e; i++) { 7163 if (const auto *RT = 7164 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 7165 if (RT->getDecl()->isOrContainsUnion()) 7166 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 7167 << 0 << i; 7168 } 7169 } 7170 } 7171 7172 // Do special checking on direct calls to functions. 7173 if (FDecl) { 7174 if (CheckFunctionCall(FDecl, TheCall, Proto)) 7175 return ExprError(); 7176 7177 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 7178 7179 if (BuiltinID) 7180 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 7181 } else if (NDecl) { 7182 if (CheckPointerCall(NDecl, TheCall, Proto)) 7183 return ExprError(); 7184 } else { 7185 if (CheckOtherCall(TheCall, Proto)) 7186 return ExprError(); 7187 } 7188 7189 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 7190 } 7191 7192 ExprResult 7193 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 7194 SourceLocation RParenLoc, Expr *InitExpr) { 7195 assert(Ty && "ActOnCompoundLiteral(): missing type"); 7196 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 7197 7198 TypeSourceInfo *TInfo; 7199 QualType literalType = GetTypeFromParser(Ty, &TInfo); 7200 if (!TInfo) 7201 TInfo = Context.getTrivialTypeSourceInfo(literalType); 7202 7203 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 7204 } 7205 7206 ExprResult 7207 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 7208 SourceLocation RParenLoc, Expr *LiteralExpr) { 7209 QualType literalType = TInfo->getType(); 7210 7211 if (literalType->isArrayType()) { 7212 if (RequireCompleteSizedType( 7213 LParenLoc, Context.getBaseElementType(literalType), 7214 diag::err_array_incomplete_or_sizeless_type, 7215 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 7216 return ExprError(); 7217 if (literalType->isVariableArrayType()) { 7218 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 7219 diag::err_variable_object_no_init)) { 7220 return ExprError(); 7221 } 7222 } 7223 } else if (!literalType->isDependentType() && 7224 RequireCompleteType(LParenLoc, literalType, 7225 diag::err_typecheck_decl_incomplete_type, 7226 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 7227 return ExprError(); 7228 7229 InitializedEntity Entity 7230 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 7231 InitializationKind Kind 7232 = InitializationKind::CreateCStyleCast(LParenLoc, 7233 SourceRange(LParenLoc, RParenLoc), 7234 /*InitList=*/true); 7235 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 7236 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 7237 &literalType); 7238 if (Result.isInvalid()) 7239 return ExprError(); 7240 LiteralExpr = Result.get(); 7241 7242 bool isFileScope = !CurContext->isFunctionOrMethod(); 7243 7244 // In C, compound literals are l-values for some reason. 7245 // For GCC compatibility, in C++, file-scope array compound literals with 7246 // constant initializers are also l-values, and compound literals are 7247 // otherwise prvalues. 7248 // 7249 // (GCC also treats C++ list-initialized file-scope array prvalues with 7250 // constant initializers as l-values, but that's non-conforming, so we don't 7251 // follow it there.) 7252 // 7253 // FIXME: It would be better to handle the lvalue cases as materializing and 7254 // lifetime-extending a temporary object, but our materialized temporaries 7255 // representation only supports lifetime extension from a variable, not "out 7256 // of thin air". 7257 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 7258 // is bound to the result of applying array-to-pointer decay to the compound 7259 // literal. 7260 // FIXME: GCC supports compound literals of reference type, which should 7261 // obviously have a value kind derived from the kind of reference involved. 7262 ExprValueKind VK = 7263 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 7264 ? VK_PRValue 7265 : VK_LValue; 7266 7267 if (isFileScope) 7268 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 7269 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 7270 Expr *Init = ILE->getInit(i); 7271 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 7272 } 7273 7274 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 7275 VK, LiteralExpr, isFileScope); 7276 if (isFileScope) { 7277 if (!LiteralExpr->isTypeDependent() && 7278 !LiteralExpr->isValueDependent() && 7279 !literalType->isDependentType()) // C99 6.5.2.5p3 7280 if (CheckForConstantInitializer(LiteralExpr, literalType)) 7281 return ExprError(); 7282 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 7283 literalType.getAddressSpace() != LangAS::Default) { 7284 // Embedded-C extensions to C99 6.5.2.5: 7285 // "If the compound literal occurs inside the body of a function, the 7286 // type name shall not be qualified by an address-space qualifier." 7287 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 7288 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 7289 return ExprError(); 7290 } 7291 7292 if (!isFileScope && !getLangOpts().CPlusPlus) { 7293 // Compound literals that have automatic storage duration are destroyed at 7294 // the end of the scope in C; in C++, they're just temporaries. 7295 7296 // Emit diagnostics if it is or contains a C union type that is non-trivial 7297 // to destruct. 7298 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 7299 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 7300 NTCUC_CompoundLiteral, NTCUK_Destruct); 7301 7302 // Diagnose jumps that enter or exit the lifetime of the compound literal. 7303 if (literalType.isDestructedType()) { 7304 Cleanup.setExprNeedsCleanups(true); 7305 ExprCleanupObjects.push_back(E); 7306 getCurFunction()->setHasBranchProtectedScope(); 7307 } 7308 } 7309 7310 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7311 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7312 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7313 E->getInitializer()->getExprLoc()); 7314 7315 return MaybeBindToTemporary(E); 7316 } 7317 7318 ExprResult 7319 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7320 SourceLocation RBraceLoc) { 7321 // Only produce each kind of designated initialization diagnostic once. 7322 SourceLocation FirstDesignator; 7323 bool DiagnosedArrayDesignator = false; 7324 bool DiagnosedNestedDesignator = false; 7325 bool DiagnosedMixedDesignator = false; 7326 7327 // Check that any designated initializers are syntactically valid in the 7328 // current language mode. 7329 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7330 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7331 if (FirstDesignator.isInvalid()) 7332 FirstDesignator = DIE->getBeginLoc(); 7333 7334 if (!getLangOpts().CPlusPlus) 7335 break; 7336 7337 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7338 DiagnosedNestedDesignator = true; 7339 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7340 << DIE->getDesignatorsSourceRange(); 7341 } 7342 7343 for (auto &Desig : DIE->designators()) { 7344 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7345 DiagnosedArrayDesignator = true; 7346 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7347 << Desig.getSourceRange(); 7348 } 7349 } 7350 7351 if (!DiagnosedMixedDesignator && 7352 !isa<DesignatedInitExpr>(InitArgList[0])) { 7353 DiagnosedMixedDesignator = true; 7354 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7355 << DIE->getSourceRange(); 7356 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7357 << InitArgList[0]->getSourceRange(); 7358 } 7359 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7360 isa<DesignatedInitExpr>(InitArgList[0])) { 7361 DiagnosedMixedDesignator = true; 7362 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7363 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7364 << DIE->getSourceRange(); 7365 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7366 << InitArgList[I]->getSourceRange(); 7367 } 7368 } 7369 7370 if (FirstDesignator.isValid()) { 7371 // Only diagnose designated initiaization as a C++20 extension if we didn't 7372 // already diagnose use of (non-C++20) C99 designator syntax. 7373 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7374 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7375 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7376 ? diag::warn_cxx17_compat_designated_init 7377 : diag::ext_cxx_designated_init); 7378 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7379 Diag(FirstDesignator, diag::ext_designated_init); 7380 } 7381 } 7382 7383 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7384 } 7385 7386 ExprResult 7387 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7388 SourceLocation RBraceLoc) { 7389 // Semantic analysis for initializers is done by ActOnDeclarator() and 7390 // CheckInitializer() - it requires knowledge of the object being initialized. 7391 7392 // Immediately handle non-overload placeholders. Overloads can be 7393 // resolved contextually, but everything else here can't. 7394 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7395 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7396 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7397 7398 // Ignore failures; dropping the entire initializer list because 7399 // of one failure would be terrible for indexing/etc. 7400 if (result.isInvalid()) continue; 7401 7402 InitArgList[I] = result.get(); 7403 } 7404 } 7405 7406 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7407 RBraceLoc); 7408 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7409 return E; 7410 } 7411 7412 /// Do an explicit extend of the given block pointer if we're in ARC. 7413 void Sema::maybeExtendBlockObject(ExprResult &E) { 7414 assert(E.get()->getType()->isBlockPointerType()); 7415 assert(E.get()->isPRValue()); 7416 7417 // Only do this in an r-value context. 7418 if (!getLangOpts().ObjCAutoRefCount) return; 7419 7420 E = ImplicitCastExpr::Create( 7421 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7422 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 7423 Cleanup.setExprNeedsCleanups(true); 7424 } 7425 7426 /// Prepare a conversion of the given expression to an ObjC object 7427 /// pointer type. 7428 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7429 QualType type = E.get()->getType(); 7430 if (type->isObjCObjectPointerType()) { 7431 return CK_BitCast; 7432 } else if (type->isBlockPointerType()) { 7433 maybeExtendBlockObject(E); 7434 return CK_BlockPointerToObjCPointerCast; 7435 } else { 7436 assert(type->isPointerType()); 7437 return CK_CPointerToObjCPointerCast; 7438 } 7439 } 7440 7441 /// Prepares for a scalar cast, performing all the necessary stages 7442 /// except the final cast and returning the kind required. 7443 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7444 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7445 // Also, callers should have filtered out the invalid cases with 7446 // pointers. Everything else should be possible. 7447 7448 QualType SrcTy = Src.get()->getType(); 7449 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7450 return CK_NoOp; 7451 7452 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7453 case Type::STK_MemberPointer: 7454 llvm_unreachable("member pointer type in C"); 7455 7456 case Type::STK_CPointer: 7457 case Type::STK_BlockPointer: 7458 case Type::STK_ObjCObjectPointer: 7459 switch (DestTy->getScalarTypeKind()) { 7460 case Type::STK_CPointer: { 7461 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7462 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7463 if (SrcAS != DestAS) 7464 return CK_AddressSpaceConversion; 7465 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7466 return CK_NoOp; 7467 return CK_BitCast; 7468 } 7469 case Type::STK_BlockPointer: 7470 return (SrcKind == Type::STK_BlockPointer 7471 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7472 case Type::STK_ObjCObjectPointer: 7473 if (SrcKind == Type::STK_ObjCObjectPointer) 7474 return CK_BitCast; 7475 if (SrcKind == Type::STK_CPointer) 7476 return CK_CPointerToObjCPointerCast; 7477 maybeExtendBlockObject(Src); 7478 return CK_BlockPointerToObjCPointerCast; 7479 case Type::STK_Bool: 7480 return CK_PointerToBoolean; 7481 case Type::STK_Integral: 7482 return CK_PointerToIntegral; 7483 case Type::STK_Floating: 7484 case Type::STK_FloatingComplex: 7485 case Type::STK_IntegralComplex: 7486 case Type::STK_MemberPointer: 7487 case Type::STK_FixedPoint: 7488 llvm_unreachable("illegal cast from pointer"); 7489 } 7490 llvm_unreachable("Should have returned before this"); 7491 7492 case Type::STK_FixedPoint: 7493 switch (DestTy->getScalarTypeKind()) { 7494 case Type::STK_FixedPoint: 7495 return CK_FixedPointCast; 7496 case Type::STK_Bool: 7497 return CK_FixedPointToBoolean; 7498 case Type::STK_Integral: 7499 return CK_FixedPointToIntegral; 7500 case Type::STK_Floating: 7501 return CK_FixedPointToFloating; 7502 case Type::STK_IntegralComplex: 7503 case Type::STK_FloatingComplex: 7504 Diag(Src.get()->getExprLoc(), 7505 diag::err_unimplemented_conversion_with_fixed_point_type) 7506 << DestTy; 7507 return CK_IntegralCast; 7508 case Type::STK_CPointer: 7509 case Type::STK_ObjCObjectPointer: 7510 case Type::STK_BlockPointer: 7511 case Type::STK_MemberPointer: 7512 llvm_unreachable("illegal cast to pointer type"); 7513 } 7514 llvm_unreachable("Should have returned before this"); 7515 7516 case Type::STK_Bool: // casting from bool is like casting from an integer 7517 case Type::STK_Integral: 7518 switch (DestTy->getScalarTypeKind()) { 7519 case Type::STK_CPointer: 7520 case Type::STK_ObjCObjectPointer: 7521 case Type::STK_BlockPointer: 7522 if (Src.get()->isNullPointerConstant(Context, 7523 Expr::NPC_ValueDependentIsNull)) 7524 return CK_NullToPointer; 7525 return CK_IntegralToPointer; 7526 case Type::STK_Bool: 7527 return CK_IntegralToBoolean; 7528 case Type::STK_Integral: 7529 return CK_IntegralCast; 7530 case Type::STK_Floating: 7531 return CK_IntegralToFloating; 7532 case Type::STK_IntegralComplex: 7533 Src = ImpCastExprToType(Src.get(), 7534 DestTy->castAs<ComplexType>()->getElementType(), 7535 CK_IntegralCast); 7536 return CK_IntegralRealToComplex; 7537 case Type::STK_FloatingComplex: 7538 Src = ImpCastExprToType(Src.get(), 7539 DestTy->castAs<ComplexType>()->getElementType(), 7540 CK_IntegralToFloating); 7541 return CK_FloatingRealToComplex; 7542 case Type::STK_MemberPointer: 7543 llvm_unreachable("member pointer type in C"); 7544 case Type::STK_FixedPoint: 7545 return CK_IntegralToFixedPoint; 7546 } 7547 llvm_unreachable("Should have returned before this"); 7548 7549 case Type::STK_Floating: 7550 switch (DestTy->getScalarTypeKind()) { 7551 case Type::STK_Floating: 7552 return CK_FloatingCast; 7553 case Type::STK_Bool: 7554 return CK_FloatingToBoolean; 7555 case Type::STK_Integral: 7556 return CK_FloatingToIntegral; 7557 case Type::STK_FloatingComplex: 7558 Src = ImpCastExprToType(Src.get(), 7559 DestTy->castAs<ComplexType>()->getElementType(), 7560 CK_FloatingCast); 7561 return CK_FloatingRealToComplex; 7562 case Type::STK_IntegralComplex: 7563 Src = ImpCastExprToType(Src.get(), 7564 DestTy->castAs<ComplexType>()->getElementType(), 7565 CK_FloatingToIntegral); 7566 return CK_IntegralRealToComplex; 7567 case Type::STK_CPointer: 7568 case Type::STK_ObjCObjectPointer: 7569 case Type::STK_BlockPointer: 7570 llvm_unreachable("valid float->pointer cast?"); 7571 case Type::STK_MemberPointer: 7572 llvm_unreachable("member pointer type in C"); 7573 case Type::STK_FixedPoint: 7574 return CK_FloatingToFixedPoint; 7575 } 7576 llvm_unreachable("Should have returned before this"); 7577 7578 case Type::STK_FloatingComplex: 7579 switch (DestTy->getScalarTypeKind()) { 7580 case Type::STK_FloatingComplex: 7581 return CK_FloatingComplexCast; 7582 case Type::STK_IntegralComplex: 7583 return CK_FloatingComplexToIntegralComplex; 7584 case Type::STK_Floating: { 7585 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7586 if (Context.hasSameType(ET, DestTy)) 7587 return CK_FloatingComplexToReal; 7588 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7589 return CK_FloatingCast; 7590 } 7591 case Type::STK_Bool: 7592 return CK_FloatingComplexToBoolean; 7593 case Type::STK_Integral: 7594 Src = ImpCastExprToType(Src.get(), 7595 SrcTy->castAs<ComplexType>()->getElementType(), 7596 CK_FloatingComplexToReal); 7597 return CK_FloatingToIntegral; 7598 case Type::STK_CPointer: 7599 case Type::STK_ObjCObjectPointer: 7600 case Type::STK_BlockPointer: 7601 llvm_unreachable("valid complex float->pointer cast?"); 7602 case Type::STK_MemberPointer: 7603 llvm_unreachable("member pointer type in C"); 7604 case Type::STK_FixedPoint: 7605 Diag(Src.get()->getExprLoc(), 7606 diag::err_unimplemented_conversion_with_fixed_point_type) 7607 << SrcTy; 7608 return CK_IntegralCast; 7609 } 7610 llvm_unreachable("Should have returned before this"); 7611 7612 case Type::STK_IntegralComplex: 7613 switch (DestTy->getScalarTypeKind()) { 7614 case Type::STK_FloatingComplex: 7615 return CK_IntegralComplexToFloatingComplex; 7616 case Type::STK_IntegralComplex: 7617 return CK_IntegralComplexCast; 7618 case Type::STK_Integral: { 7619 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7620 if (Context.hasSameType(ET, DestTy)) 7621 return CK_IntegralComplexToReal; 7622 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7623 return CK_IntegralCast; 7624 } 7625 case Type::STK_Bool: 7626 return CK_IntegralComplexToBoolean; 7627 case Type::STK_Floating: 7628 Src = ImpCastExprToType(Src.get(), 7629 SrcTy->castAs<ComplexType>()->getElementType(), 7630 CK_IntegralComplexToReal); 7631 return CK_IntegralToFloating; 7632 case Type::STK_CPointer: 7633 case Type::STK_ObjCObjectPointer: 7634 case Type::STK_BlockPointer: 7635 llvm_unreachable("valid complex int->pointer cast?"); 7636 case Type::STK_MemberPointer: 7637 llvm_unreachable("member pointer type in C"); 7638 case Type::STK_FixedPoint: 7639 Diag(Src.get()->getExprLoc(), 7640 diag::err_unimplemented_conversion_with_fixed_point_type) 7641 << SrcTy; 7642 return CK_IntegralCast; 7643 } 7644 llvm_unreachable("Should have returned before this"); 7645 } 7646 7647 llvm_unreachable("Unhandled scalar cast"); 7648 } 7649 7650 static bool breakDownVectorType(QualType type, uint64_t &len, 7651 QualType &eltType) { 7652 // Vectors are simple. 7653 if (const VectorType *vecType = type->getAs<VectorType>()) { 7654 len = vecType->getNumElements(); 7655 eltType = vecType->getElementType(); 7656 assert(eltType->isScalarType()); 7657 return true; 7658 } 7659 7660 // We allow lax conversion to and from non-vector types, but only if 7661 // they're real types (i.e. non-complex, non-pointer scalar types). 7662 if (!type->isRealType()) return false; 7663 7664 len = 1; 7665 eltType = type; 7666 return true; 7667 } 7668 7669 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7670 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7671 /// allowed? 7672 /// 7673 /// This will also return false if the two given types do not make sense from 7674 /// the perspective of SVE bitcasts. 7675 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7676 assert(srcTy->isVectorType() || destTy->isVectorType()); 7677 7678 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7679 if (!FirstType->isSizelessBuiltinType()) 7680 return false; 7681 7682 const auto *VecTy = SecondType->getAs<VectorType>(); 7683 return VecTy && 7684 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7685 }; 7686 7687 return ValidScalableConversion(srcTy, destTy) || 7688 ValidScalableConversion(destTy, srcTy); 7689 } 7690 7691 /// Are the two types matrix types and do they have the same dimensions i.e. 7692 /// do they have the same number of rows and the same number of columns? 7693 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7694 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7695 return false; 7696 7697 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7698 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7699 7700 return matSrcType->getNumRows() == matDestType->getNumRows() && 7701 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7702 } 7703 7704 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7705 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7706 7707 uint64_t SrcLen, DestLen; 7708 QualType SrcEltTy, DestEltTy; 7709 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7710 return false; 7711 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7712 return false; 7713 7714 // ASTContext::getTypeSize will return the size rounded up to a 7715 // power of 2, so instead of using that, we need to use the raw 7716 // element size multiplied by the element count. 7717 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7718 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7719 7720 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7721 } 7722 7723 /// Are the two types lax-compatible vector types? That is, given 7724 /// that one of them is a vector, do they have equal storage sizes, 7725 /// where the storage size is the number of elements times the element 7726 /// size? 7727 /// 7728 /// This will also return false if either of the types is neither a 7729 /// vector nor a real type. 7730 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7731 assert(destTy->isVectorType() || srcTy->isVectorType()); 7732 7733 // Disallow lax conversions between scalars and ExtVectors (these 7734 // conversions are allowed for other vector types because common headers 7735 // depend on them). Most scalar OP ExtVector cases are handled by the 7736 // splat path anyway, which does what we want (convert, not bitcast). 7737 // What this rules out for ExtVectors is crazy things like char4*float. 7738 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7739 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7740 7741 return areVectorTypesSameSize(srcTy, destTy); 7742 } 7743 7744 /// Is this a legal conversion between two types, one of which is 7745 /// known to be a vector type? 7746 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7747 assert(destTy->isVectorType() || srcTy->isVectorType()); 7748 7749 switch (Context.getLangOpts().getLaxVectorConversions()) { 7750 case LangOptions::LaxVectorConversionKind::None: 7751 return false; 7752 7753 case LangOptions::LaxVectorConversionKind::Integer: 7754 if (!srcTy->isIntegralOrEnumerationType()) { 7755 auto *Vec = srcTy->getAs<VectorType>(); 7756 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7757 return false; 7758 } 7759 if (!destTy->isIntegralOrEnumerationType()) { 7760 auto *Vec = destTy->getAs<VectorType>(); 7761 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7762 return false; 7763 } 7764 // OK, integer (vector) -> integer (vector) bitcast. 7765 break; 7766 7767 case LangOptions::LaxVectorConversionKind::All: 7768 break; 7769 } 7770 7771 return areLaxCompatibleVectorTypes(srcTy, destTy); 7772 } 7773 7774 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7775 CastKind &Kind) { 7776 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7777 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7778 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7779 << DestTy << SrcTy << R; 7780 } 7781 } else if (SrcTy->isMatrixType()) { 7782 return Diag(R.getBegin(), 7783 diag::err_invalid_conversion_between_matrix_and_type) 7784 << SrcTy << DestTy << R; 7785 } else if (DestTy->isMatrixType()) { 7786 return Diag(R.getBegin(), 7787 diag::err_invalid_conversion_between_matrix_and_type) 7788 << DestTy << SrcTy << R; 7789 } 7790 7791 Kind = CK_MatrixCast; 7792 return false; 7793 } 7794 7795 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7796 CastKind &Kind) { 7797 assert(VectorTy->isVectorType() && "Not a vector type!"); 7798 7799 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7800 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7801 return Diag(R.getBegin(), 7802 Ty->isVectorType() ? 7803 diag::err_invalid_conversion_between_vectors : 7804 diag::err_invalid_conversion_between_vector_and_integer) 7805 << VectorTy << Ty << R; 7806 } else 7807 return Diag(R.getBegin(), 7808 diag::err_invalid_conversion_between_vector_and_scalar) 7809 << VectorTy << Ty << R; 7810 7811 Kind = CK_BitCast; 7812 return false; 7813 } 7814 7815 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7816 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7817 7818 if (DestElemTy == SplattedExpr->getType()) 7819 return SplattedExpr; 7820 7821 assert(DestElemTy->isFloatingType() || 7822 DestElemTy->isIntegralOrEnumerationType()); 7823 7824 CastKind CK; 7825 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7826 // OpenCL requires that we convert `true` boolean expressions to -1, but 7827 // only when splatting vectors. 7828 if (DestElemTy->isFloatingType()) { 7829 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7830 // in two steps: boolean to signed integral, then to floating. 7831 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7832 CK_BooleanToSignedIntegral); 7833 SplattedExpr = CastExprRes.get(); 7834 CK = CK_IntegralToFloating; 7835 } else { 7836 CK = CK_BooleanToSignedIntegral; 7837 } 7838 } else { 7839 ExprResult CastExprRes = SplattedExpr; 7840 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7841 if (CastExprRes.isInvalid()) 7842 return ExprError(); 7843 SplattedExpr = CastExprRes.get(); 7844 } 7845 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7846 } 7847 7848 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7849 Expr *CastExpr, CastKind &Kind) { 7850 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7851 7852 QualType SrcTy = CastExpr->getType(); 7853 7854 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7855 // an ExtVectorType. 7856 // In OpenCL, casts between vectors of different types are not allowed. 7857 // (See OpenCL 6.2). 7858 if (SrcTy->isVectorType()) { 7859 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7860 (getLangOpts().OpenCL && 7861 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7862 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7863 << DestTy << SrcTy << R; 7864 return ExprError(); 7865 } 7866 Kind = CK_BitCast; 7867 return CastExpr; 7868 } 7869 7870 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7871 // conversion will take place first from scalar to elt type, and then 7872 // splat from elt type to vector. 7873 if (SrcTy->isPointerType()) 7874 return Diag(R.getBegin(), 7875 diag::err_invalid_conversion_between_vector_and_scalar) 7876 << DestTy << SrcTy << R; 7877 7878 Kind = CK_VectorSplat; 7879 return prepareVectorSplat(DestTy, CastExpr); 7880 } 7881 7882 ExprResult 7883 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7884 Declarator &D, ParsedType &Ty, 7885 SourceLocation RParenLoc, Expr *CastExpr) { 7886 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7887 "ActOnCastExpr(): missing type or expr"); 7888 7889 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7890 if (D.isInvalidType()) 7891 return ExprError(); 7892 7893 if (getLangOpts().CPlusPlus) { 7894 // Check that there are no default arguments (C++ only). 7895 CheckExtraCXXDefaultArguments(D); 7896 } else { 7897 // Make sure any TypoExprs have been dealt with. 7898 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7899 if (!Res.isUsable()) 7900 return ExprError(); 7901 CastExpr = Res.get(); 7902 } 7903 7904 checkUnusedDeclAttributes(D); 7905 7906 QualType castType = castTInfo->getType(); 7907 Ty = CreateParsedType(castType, castTInfo); 7908 7909 bool isVectorLiteral = false; 7910 7911 // Check for an altivec or OpenCL literal, 7912 // i.e. all the elements are integer constants. 7913 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7914 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7915 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7916 && castType->isVectorType() && (PE || PLE)) { 7917 if (PLE && PLE->getNumExprs() == 0) { 7918 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7919 return ExprError(); 7920 } 7921 if (PE || PLE->getNumExprs() == 1) { 7922 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7923 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7924 isVectorLiteral = true; 7925 } 7926 else 7927 isVectorLiteral = true; 7928 } 7929 7930 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7931 // then handle it as such. 7932 if (isVectorLiteral) 7933 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7934 7935 // If the Expr being casted is a ParenListExpr, handle it specially. 7936 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7937 // sequence of BinOp comma operators. 7938 if (isa<ParenListExpr>(CastExpr)) { 7939 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7940 if (Result.isInvalid()) return ExprError(); 7941 CastExpr = Result.get(); 7942 } 7943 7944 if (getLangOpts().CPlusPlus && !castType->isVoidType()) 7945 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7946 7947 CheckTollFreeBridgeCast(castType, CastExpr); 7948 7949 CheckObjCBridgeRelatedCast(castType, CastExpr); 7950 7951 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7952 7953 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7954 } 7955 7956 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7957 SourceLocation RParenLoc, Expr *E, 7958 TypeSourceInfo *TInfo) { 7959 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7960 "Expected paren or paren list expression"); 7961 7962 Expr **exprs; 7963 unsigned numExprs; 7964 Expr *subExpr; 7965 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7966 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7967 LiteralLParenLoc = PE->getLParenLoc(); 7968 LiteralRParenLoc = PE->getRParenLoc(); 7969 exprs = PE->getExprs(); 7970 numExprs = PE->getNumExprs(); 7971 } else { // isa<ParenExpr> by assertion at function entrance 7972 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7973 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7974 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7975 exprs = &subExpr; 7976 numExprs = 1; 7977 } 7978 7979 QualType Ty = TInfo->getType(); 7980 assert(Ty->isVectorType() && "Expected vector type"); 7981 7982 SmallVector<Expr *, 8> initExprs; 7983 const VectorType *VTy = Ty->castAs<VectorType>(); 7984 unsigned numElems = VTy->getNumElements(); 7985 7986 // '(...)' form of vector initialization in AltiVec: the number of 7987 // initializers must be one or must match the size of the vector. 7988 // If a single value is specified in the initializer then it will be 7989 // replicated to all the components of the vector 7990 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, 7991 VTy->getElementType())) 7992 return ExprError(); 7993 if (ShouldSplatAltivecScalarInCast(VTy)) { 7994 // The number of initializers must be one or must match the size of the 7995 // vector. If a single value is specified in the initializer then it will 7996 // be replicated to all the components of the vector 7997 if (numExprs == 1) { 7998 QualType ElemTy = VTy->getElementType(); 7999 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 8000 if (Literal.isInvalid()) 8001 return ExprError(); 8002 Literal = ImpCastExprToType(Literal.get(), ElemTy, 8003 PrepareScalarCast(Literal, ElemTy)); 8004 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 8005 } 8006 else if (numExprs < numElems) { 8007 Diag(E->getExprLoc(), 8008 diag::err_incorrect_number_of_vector_initializers); 8009 return ExprError(); 8010 } 8011 else 8012 initExprs.append(exprs, exprs + numExprs); 8013 } 8014 else { 8015 // For OpenCL, when the number of initializers is a single value, 8016 // it will be replicated to all components of the vector. 8017 if (getLangOpts().OpenCL && 8018 VTy->getVectorKind() == VectorType::GenericVector && 8019 numExprs == 1) { 8020 QualType ElemTy = VTy->getElementType(); 8021 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 8022 if (Literal.isInvalid()) 8023 return ExprError(); 8024 Literal = ImpCastExprToType(Literal.get(), ElemTy, 8025 PrepareScalarCast(Literal, ElemTy)); 8026 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 8027 } 8028 8029 initExprs.append(exprs, exprs + numExprs); 8030 } 8031 // FIXME: This means that pretty-printing the final AST will produce curly 8032 // braces instead of the original commas. 8033 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 8034 initExprs, LiteralRParenLoc); 8035 initE->setType(Ty); 8036 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 8037 } 8038 8039 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 8040 /// the ParenListExpr into a sequence of comma binary operators. 8041 ExprResult 8042 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 8043 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 8044 if (!E) 8045 return OrigExpr; 8046 8047 ExprResult Result(E->getExpr(0)); 8048 8049 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 8050 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 8051 E->getExpr(i)); 8052 8053 if (Result.isInvalid()) return ExprError(); 8054 8055 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 8056 } 8057 8058 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 8059 SourceLocation R, 8060 MultiExprArg Val) { 8061 return ParenListExpr::Create(Context, L, Val, R); 8062 } 8063 8064 /// Emit a specialized diagnostic when one expression is a null pointer 8065 /// constant and the other is not a pointer. Returns true if a diagnostic is 8066 /// emitted. 8067 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 8068 SourceLocation QuestionLoc) { 8069 Expr *NullExpr = LHSExpr; 8070 Expr *NonPointerExpr = RHSExpr; 8071 Expr::NullPointerConstantKind NullKind = 8072 NullExpr->isNullPointerConstant(Context, 8073 Expr::NPC_ValueDependentIsNotNull); 8074 8075 if (NullKind == Expr::NPCK_NotNull) { 8076 NullExpr = RHSExpr; 8077 NonPointerExpr = LHSExpr; 8078 NullKind = 8079 NullExpr->isNullPointerConstant(Context, 8080 Expr::NPC_ValueDependentIsNotNull); 8081 } 8082 8083 if (NullKind == Expr::NPCK_NotNull) 8084 return false; 8085 8086 if (NullKind == Expr::NPCK_ZeroExpression) 8087 return false; 8088 8089 if (NullKind == Expr::NPCK_ZeroLiteral) { 8090 // In this case, check to make sure that we got here from a "NULL" 8091 // string in the source code. 8092 NullExpr = NullExpr->IgnoreParenImpCasts(); 8093 SourceLocation loc = NullExpr->getExprLoc(); 8094 if (!findMacroSpelling(loc, "NULL")) 8095 return false; 8096 } 8097 8098 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 8099 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 8100 << NonPointerExpr->getType() << DiagType 8101 << NonPointerExpr->getSourceRange(); 8102 return true; 8103 } 8104 8105 /// Return false if the condition expression is valid, true otherwise. 8106 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 8107 QualType CondTy = Cond->getType(); 8108 8109 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 8110 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 8111 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8112 << CondTy << Cond->getSourceRange(); 8113 return true; 8114 } 8115 8116 // C99 6.5.15p2 8117 if (CondTy->isScalarType()) return false; 8118 8119 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 8120 << CondTy << Cond->getSourceRange(); 8121 return true; 8122 } 8123 8124 /// Handle when one or both operands are void type. 8125 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 8126 ExprResult &RHS) { 8127 Expr *LHSExpr = LHS.get(); 8128 Expr *RHSExpr = RHS.get(); 8129 8130 if (!LHSExpr->getType()->isVoidType()) 8131 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 8132 << RHSExpr->getSourceRange(); 8133 if (!RHSExpr->getType()->isVoidType()) 8134 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 8135 << LHSExpr->getSourceRange(); 8136 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 8137 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 8138 return S.Context.VoidTy; 8139 } 8140 8141 /// Return false if the NullExpr can be promoted to PointerTy, 8142 /// true otherwise. 8143 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 8144 QualType PointerTy) { 8145 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 8146 !NullExpr.get()->isNullPointerConstant(S.Context, 8147 Expr::NPC_ValueDependentIsNull)) 8148 return true; 8149 8150 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 8151 return false; 8152 } 8153 8154 /// Checks compatibility between two pointers and return the resulting 8155 /// type. 8156 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 8157 ExprResult &RHS, 8158 SourceLocation Loc) { 8159 QualType LHSTy = LHS.get()->getType(); 8160 QualType RHSTy = RHS.get()->getType(); 8161 8162 if (S.Context.hasSameType(LHSTy, RHSTy)) { 8163 // Two identical pointers types are always compatible. 8164 return LHSTy; 8165 } 8166 8167 QualType lhptee, rhptee; 8168 8169 // Get the pointee types. 8170 bool IsBlockPointer = false; 8171 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 8172 lhptee = LHSBTy->getPointeeType(); 8173 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 8174 IsBlockPointer = true; 8175 } else { 8176 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8177 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8178 } 8179 8180 // C99 6.5.15p6: If both operands are pointers to compatible types or to 8181 // differently qualified versions of compatible types, the result type is 8182 // a pointer to an appropriately qualified version of the composite 8183 // type. 8184 8185 // Only CVR-qualifiers exist in the standard, and the differently-qualified 8186 // clause doesn't make sense for our extensions. E.g. address space 2 should 8187 // be incompatible with address space 3: they may live on different devices or 8188 // anything. 8189 Qualifiers lhQual = lhptee.getQualifiers(); 8190 Qualifiers rhQual = rhptee.getQualifiers(); 8191 8192 LangAS ResultAddrSpace = LangAS::Default; 8193 LangAS LAddrSpace = lhQual.getAddressSpace(); 8194 LangAS RAddrSpace = rhQual.getAddressSpace(); 8195 8196 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 8197 // spaces is disallowed. 8198 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 8199 ResultAddrSpace = LAddrSpace; 8200 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 8201 ResultAddrSpace = RAddrSpace; 8202 else { 8203 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8204 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 8205 << RHS.get()->getSourceRange(); 8206 return QualType(); 8207 } 8208 8209 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 8210 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 8211 lhQual.removeCVRQualifiers(); 8212 rhQual.removeCVRQualifiers(); 8213 8214 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 8215 // (C99 6.7.3) for address spaces. We assume that the check should behave in 8216 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 8217 // qual types are compatible iff 8218 // * corresponded types are compatible 8219 // * CVR qualifiers are equal 8220 // * address spaces are equal 8221 // Thus for conditional operator we merge CVR and address space unqualified 8222 // pointees and if there is a composite type we return a pointer to it with 8223 // merged qualifiers. 8224 LHSCastKind = 8225 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 8226 RHSCastKind = 8227 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 8228 lhQual.removeAddressSpace(); 8229 rhQual.removeAddressSpace(); 8230 8231 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 8232 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 8233 8234 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 8235 8236 if (CompositeTy.isNull()) { 8237 // In this situation, we assume void* type. No especially good 8238 // reason, but this is what gcc does, and we do have to pick 8239 // to get a consistent AST. 8240 QualType incompatTy; 8241 incompatTy = S.Context.getPointerType( 8242 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 8243 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 8244 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 8245 8246 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 8247 // for casts between types with incompatible address space qualifiers. 8248 // For the following code the compiler produces casts between global and 8249 // local address spaces of the corresponded innermost pointees: 8250 // local int *global *a; 8251 // global int *global *b; 8252 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 8253 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 8254 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8255 << RHS.get()->getSourceRange(); 8256 8257 return incompatTy; 8258 } 8259 8260 // The pointer types are compatible. 8261 // In case of OpenCL ResultTy should have the address space qualifier 8262 // which is a superset of address spaces of both the 2nd and the 3rd 8263 // operands of the conditional operator. 8264 QualType ResultTy = [&, ResultAddrSpace]() { 8265 if (S.getLangOpts().OpenCL) { 8266 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 8267 CompositeQuals.setAddressSpace(ResultAddrSpace); 8268 return S.Context 8269 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 8270 .withCVRQualifiers(MergedCVRQual); 8271 } 8272 return CompositeTy.withCVRQualifiers(MergedCVRQual); 8273 }(); 8274 if (IsBlockPointer) 8275 ResultTy = S.Context.getBlockPointerType(ResultTy); 8276 else 8277 ResultTy = S.Context.getPointerType(ResultTy); 8278 8279 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 8280 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 8281 return ResultTy; 8282 } 8283 8284 /// Return the resulting type when the operands are both block pointers. 8285 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 8286 ExprResult &LHS, 8287 ExprResult &RHS, 8288 SourceLocation Loc) { 8289 QualType LHSTy = LHS.get()->getType(); 8290 QualType RHSTy = RHS.get()->getType(); 8291 8292 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 8293 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 8294 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 8295 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8296 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8297 return destType; 8298 } 8299 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 8300 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8301 << RHS.get()->getSourceRange(); 8302 return QualType(); 8303 } 8304 8305 // We have 2 block pointer types. 8306 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8307 } 8308 8309 /// Return the resulting type when the operands are both pointers. 8310 static QualType 8311 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8312 ExprResult &RHS, 8313 SourceLocation Loc) { 8314 // get the pointer types 8315 QualType LHSTy = LHS.get()->getType(); 8316 QualType RHSTy = RHS.get()->getType(); 8317 8318 // get the "pointed to" types 8319 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8320 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8321 8322 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8323 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8324 // Figure out necessary qualifiers (C99 6.5.15p6) 8325 QualType destPointee 8326 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8327 QualType destType = S.Context.getPointerType(destPointee); 8328 // Add qualifiers if necessary. 8329 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8330 // Promote to void*. 8331 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8332 return destType; 8333 } 8334 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8335 QualType destPointee 8336 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8337 QualType destType = S.Context.getPointerType(destPointee); 8338 // Add qualifiers if necessary. 8339 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8340 // Promote to void*. 8341 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8342 return destType; 8343 } 8344 8345 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8346 } 8347 8348 /// Return false if the first expression is not an integer and the second 8349 /// expression is not a pointer, true otherwise. 8350 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8351 Expr* PointerExpr, SourceLocation Loc, 8352 bool IsIntFirstExpr) { 8353 if (!PointerExpr->getType()->isPointerType() || 8354 !Int.get()->getType()->isIntegerType()) 8355 return false; 8356 8357 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8358 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8359 8360 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8361 << Expr1->getType() << Expr2->getType() 8362 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8363 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8364 CK_IntegralToPointer); 8365 return true; 8366 } 8367 8368 /// Simple conversion between integer and floating point types. 8369 /// 8370 /// Used when handling the OpenCL conditional operator where the 8371 /// condition is a vector while the other operands are scalar. 8372 /// 8373 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8374 /// types are either integer or floating type. Between the two 8375 /// operands, the type with the higher rank is defined as the "result 8376 /// type". The other operand needs to be promoted to the same type. No 8377 /// other type promotion is allowed. We cannot use 8378 /// UsualArithmeticConversions() for this purpose, since it always 8379 /// promotes promotable types. 8380 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8381 ExprResult &RHS, 8382 SourceLocation QuestionLoc) { 8383 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8384 if (LHS.isInvalid()) 8385 return QualType(); 8386 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8387 if (RHS.isInvalid()) 8388 return QualType(); 8389 8390 // For conversion purposes, we ignore any qualifiers. 8391 // For example, "const float" and "float" are equivalent. 8392 QualType LHSType = 8393 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8394 QualType RHSType = 8395 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8396 8397 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8398 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8399 << LHSType << LHS.get()->getSourceRange(); 8400 return QualType(); 8401 } 8402 8403 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8404 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8405 << RHSType << RHS.get()->getSourceRange(); 8406 return QualType(); 8407 } 8408 8409 // If both types are identical, no conversion is needed. 8410 if (LHSType == RHSType) 8411 return LHSType; 8412 8413 // Now handle "real" floating types (i.e. float, double, long double). 8414 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8415 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8416 /*IsCompAssign = */ false); 8417 8418 // Finally, we have two differing integer types. 8419 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8420 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8421 } 8422 8423 /// Convert scalar operands to a vector that matches the 8424 /// condition in length. 8425 /// 8426 /// Used when handling the OpenCL conditional operator where the 8427 /// condition is a vector while the other operands are scalar. 8428 /// 8429 /// We first compute the "result type" for the scalar operands 8430 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8431 /// into a vector of that type where the length matches the condition 8432 /// vector type. s6.11.6 requires that the element types of the result 8433 /// and the condition must have the same number of bits. 8434 static QualType 8435 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8436 QualType CondTy, SourceLocation QuestionLoc) { 8437 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8438 if (ResTy.isNull()) return QualType(); 8439 8440 const VectorType *CV = CondTy->getAs<VectorType>(); 8441 assert(CV); 8442 8443 // Determine the vector result type 8444 unsigned NumElements = CV->getNumElements(); 8445 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8446 8447 // Ensure that all types have the same number of bits 8448 if (S.Context.getTypeSize(CV->getElementType()) 8449 != S.Context.getTypeSize(ResTy)) { 8450 // Since VectorTy is created internally, it does not pretty print 8451 // with an OpenCL name. Instead, we just print a description. 8452 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8453 SmallString<64> Str; 8454 llvm::raw_svector_ostream OS(Str); 8455 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8456 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8457 << CondTy << OS.str(); 8458 return QualType(); 8459 } 8460 8461 // Convert operands to the vector result type 8462 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8463 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8464 8465 return VectorTy; 8466 } 8467 8468 /// Return false if this is a valid OpenCL condition vector 8469 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8470 SourceLocation QuestionLoc) { 8471 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8472 // integral type. 8473 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8474 assert(CondTy); 8475 QualType EleTy = CondTy->getElementType(); 8476 if (EleTy->isIntegerType()) return false; 8477 8478 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8479 << Cond->getType() << Cond->getSourceRange(); 8480 return true; 8481 } 8482 8483 /// Return false if the vector condition type and the vector 8484 /// result type are compatible. 8485 /// 8486 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8487 /// number of elements, and their element types have the same number 8488 /// of bits. 8489 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8490 SourceLocation QuestionLoc) { 8491 const VectorType *CV = CondTy->getAs<VectorType>(); 8492 const VectorType *RV = VecResTy->getAs<VectorType>(); 8493 assert(CV && RV); 8494 8495 if (CV->getNumElements() != RV->getNumElements()) { 8496 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8497 << CondTy << VecResTy; 8498 return true; 8499 } 8500 8501 QualType CVE = CV->getElementType(); 8502 QualType RVE = RV->getElementType(); 8503 8504 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8505 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8506 << CondTy << VecResTy; 8507 return true; 8508 } 8509 8510 return false; 8511 } 8512 8513 /// Return the resulting type for the conditional operator in 8514 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8515 /// s6.3.i) when the condition is a vector type. 8516 static QualType 8517 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8518 ExprResult &LHS, ExprResult &RHS, 8519 SourceLocation QuestionLoc) { 8520 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8521 if (Cond.isInvalid()) 8522 return QualType(); 8523 QualType CondTy = Cond.get()->getType(); 8524 8525 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8526 return QualType(); 8527 8528 // If either operand is a vector then find the vector type of the 8529 // result as specified in OpenCL v1.1 s6.3.i. 8530 if (LHS.get()->getType()->isVectorType() || 8531 RHS.get()->getType()->isVectorType()) { 8532 bool IsBoolVecLang = 8533 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus; 8534 QualType VecResTy = 8535 S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8536 /*isCompAssign*/ false, 8537 /*AllowBothBool*/ true, 8538 /*AllowBoolConversions*/ false, 8539 /*AllowBooleanOperation*/ IsBoolVecLang, 8540 /*ReportInvalid*/ true); 8541 if (VecResTy.isNull()) 8542 return QualType(); 8543 // The result type must match the condition type as specified in 8544 // OpenCL v1.1 s6.11.6. 8545 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8546 return QualType(); 8547 return VecResTy; 8548 } 8549 8550 // Both operands are scalar. 8551 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8552 } 8553 8554 /// Return true if the Expr is block type 8555 static bool checkBlockType(Sema &S, const Expr *E) { 8556 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8557 QualType Ty = CE->getCallee()->getType(); 8558 if (Ty->isBlockPointerType()) { 8559 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8560 return true; 8561 } 8562 } 8563 return false; 8564 } 8565 8566 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8567 /// In that case, LHS = cond. 8568 /// C99 6.5.15 8569 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8570 ExprResult &RHS, ExprValueKind &VK, 8571 ExprObjectKind &OK, 8572 SourceLocation QuestionLoc) { 8573 8574 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8575 if (!LHSResult.isUsable()) return QualType(); 8576 LHS = LHSResult; 8577 8578 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8579 if (!RHSResult.isUsable()) return QualType(); 8580 RHS = RHSResult; 8581 8582 // C++ is sufficiently different to merit its own checker. 8583 if (getLangOpts().CPlusPlus) 8584 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8585 8586 VK = VK_PRValue; 8587 OK = OK_Ordinary; 8588 8589 if (Context.isDependenceAllowed() && 8590 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8591 RHS.get()->isTypeDependent())) { 8592 assert(!getLangOpts().CPlusPlus); 8593 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8594 RHS.get()->containsErrors()) && 8595 "should only occur in error-recovery path."); 8596 return Context.DependentTy; 8597 } 8598 8599 // The OpenCL operator with a vector condition is sufficiently 8600 // different to merit its own checker. 8601 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8602 Cond.get()->getType()->isExtVectorType()) 8603 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8604 8605 // First, check the condition. 8606 Cond = UsualUnaryConversions(Cond.get()); 8607 if (Cond.isInvalid()) 8608 return QualType(); 8609 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8610 return QualType(); 8611 8612 // Now check the two expressions. 8613 if (LHS.get()->getType()->isVectorType() || 8614 RHS.get()->getType()->isVectorType()) 8615 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false, 8616 /*AllowBothBool*/ true, 8617 /*AllowBoolConversions*/ false, 8618 /*AllowBooleanOperation*/ false, 8619 /*ReportInvalid*/ true); 8620 8621 QualType ResTy = 8622 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8623 if (LHS.isInvalid() || RHS.isInvalid()) 8624 return QualType(); 8625 8626 QualType LHSTy = LHS.get()->getType(); 8627 QualType RHSTy = RHS.get()->getType(); 8628 8629 // Diagnose attempts to convert between __ibm128, __float128 and long double 8630 // where such conversions currently can't be handled. 8631 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8632 Diag(QuestionLoc, 8633 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8634 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8635 return QualType(); 8636 } 8637 8638 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8639 // selection operator (?:). 8640 if (getLangOpts().OpenCL && 8641 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) { 8642 return QualType(); 8643 } 8644 8645 // If both operands have arithmetic type, do the usual arithmetic conversions 8646 // to find a common type: C99 6.5.15p3,5. 8647 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8648 // Disallow invalid arithmetic conversions, such as those between bit- 8649 // precise integers types of different sizes, or between a bit-precise 8650 // integer and another type. 8651 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) { 8652 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8653 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8654 << RHS.get()->getSourceRange(); 8655 return QualType(); 8656 } 8657 8658 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8659 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8660 8661 return ResTy; 8662 } 8663 8664 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8665 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8666 return LHSTy; 8667 } 8668 8669 // If both operands are the same structure or union type, the result is that 8670 // type. 8671 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8672 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8673 if (LHSRT->getDecl() == RHSRT->getDecl()) 8674 // "If both the operands have structure or union type, the result has 8675 // that type." This implies that CV qualifiers are dropped. 8676 return LHSTy.getUnqualifiedType(); 8677 // FIXME: Type of conditional expression must be complete in C mode. 8678 } 8679 8680 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8681 // The following || allows only one side to be void (a GCC-ism). 8682 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8683 return checkConditionalVoidType(*this, LHS, RHS); 8684 } 8685 8686 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8687 // the type of the other operand." 8688 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8689 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8690 8691 // All objective-c pointer type analysis is done here. 8692 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8693 QuestionLoc); 8694 if (LHS.isInvalid() || RHS.isInvalid()) 8695 return QualType(); 8696 if (!compositeType.isNull()) 8697 return compositeType; 8698 8699 8700 // Handle block pointer types. 8701 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8702 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8703 QuestionLoc); 8704 8705 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8706 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8707 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8708 QuestionLoc); 8709 8710 // GCC compatibility: soften pointer/integer mismatch. Note that 8711 // null pointers have been filtered out by this point. 8712 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8713 /*IsIntFirstExpr=*/true)) 8714 return RHSTy; 8715 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8716 /*IsIntFirstExpr=*/false)) 8717 return LHSTy; 8718 8719 // Allow ?: operations in which both operands have the same 8720 // built-in sizeless type. 8721 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) 8722 return LHSTy; 8723 8724 // Emit a better diagnostic if one of the expressions is a null pointer 8725 // constant and the other is not a pointer type. In this case, the user most 8726 // likely forgot to take the address of the other expression. 8727 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8728 return QualType(); 8729 8730 // Otherwise, the operands are not compatible. 8731 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8732 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8733 << RHS.get()->getSourceRange(); 8734 return QualType(); 8735 } 8736 8737 /// FindCompositeObjCPointerType - Helper method to find composite type of 8738 /// two objective-c pointer types of the two input expressions. 8739 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8740 SourceLocation QuestionLoc) { 8741 QualType LHSTy = LHS.get()->getType(); 8742 QualType RHSTy = RHS.get()->getType(); 8743 8744 // Handle things like Class and struct objc_class*. Here we case the result 8745 // to the pseudo-builtin, because that will be implicitly cast back to the 8746 // redefinition type if an attempt is made to access its fields. 8747 if (LHSTy->isObjCClassType() && 8748 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8749 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8750 return LHSTy; 8751 } 8752 if (RHSTy->isObjCClassType() && 8753 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8754 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8755 return RHSTy; 8756 } 8757 // And the same for struct objc_object* / id 8758 if (LHSTy->isObjCIdType() && 8759 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8760 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8761 return LHSTy; 8762 } 8763 if (RHSTy->isObjCIdType() && 8764 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8765 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8766 return RHSTy; 8767 } 8768 // And the same for struct objc_selector* / SEL 8769 if (Context.isObjCSelType(LHSTy) && 8770 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8771 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8772 return LHSTy; 8773 } 8774 if (Context.isObjCSelType(RHSTy) && 8775 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8776 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8777 return RHSTy; 8778 } 8779 // Check constraints for Objective-C object pointers types. 8780 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8781 8782 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8783 // Two identical object pointer types are always compatible. 8784 return LHSTy; 8785 } 8786 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8787 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8788 QualType compositeType = LHSTy; 8789 8790 // If both operands are interfaces and either operand can be 8791 // assigned to the other, use that type as the composite 8792 // type. This allows 8793 // xxx ? (A*) a : (B*) b 8794 // where B is a subclass of A. 8795 // 8796 // Additionally, as for assignment, if either type is 'id' 8797 // allow silent coercion. Finally, if the types are 8798 // incompatible then make sure to use 'id' as the composite 8799 // type so the result is acceptable for sending messages to. 8800 8801 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8802 // It could return the composite type. 8803 if (!(compositeType = 8804 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8805 // Nothing more to do. 8806 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8807 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8808 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8809 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8810 } else if ((LHSOPT->isObjCQualifiedIdType() || 8811 RHSOPT->isObjCQualifiedIdType()) && 8812 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8813 true)) { 8814 // Need to handle "id<xx>" explicitly. 8815 // GCC allows qualified id and any Objective-C type to devolve to 8816 // id. Currently localizing to here until clear this should be 8817 // part of ObjCQualifiedIdTypesAreCompatible. 8818 compositeType = Context.getObjCIdType(); 8819 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8820 compositeType = Context.getObjCIdType(); 8821 } else { 8822 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8823 << LHSTy << RHSTy 8824 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8825 QualType incompatTy = Context.getObjCIdType(); 8826 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8827 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8828 return incompatTy; 8829 } 8830 // The object pointer types are compatible. 8831 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8832 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8833 return compositeType; 8834 } 8835 // Check Objective-C object pointer types and 'void *' 8836 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 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<PointerType>()->getPointeeType(); 8846 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8847 QualType destPointee 8848 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8849 QualType destType = Context.getPointerType(destPointee); 8850 // Add qualifiers if necessary. 8851 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8852 // Promote to void*. 8853 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8854 return destType; 8855 } 8856 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8857 if (getLangOpts().ObjCAutoRefCount) { 8858 // ARC forbids the implicit conversion of object pointers to 'void *', 8859 // so these types are not compatible. 8860 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8861 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8862 LHS = RHS = true; 8863 return QualType(); 8864 } 8865 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8866 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8867 QualType destPointee 8868 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8869 QualType destType = Context.getPointerType(destPointee); 8870 // Add qualifiers if necessary. 8871 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8872 // Promote to void*. 8873 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8874 return destType; 8875 } 8876 return QualType(); 8877 } 8878 8879 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8880 /// ParenRange in parentheses. 8881 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8882 const PartialDiagnostic &Note, 8883 SourceRange ParenRange) { 8884 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8885 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8886 EndLoc.isValid()) { 8887 Self.Diag(Loc, Note) 8888 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8889 << FixItHint::CreateInsertion(EndLoc, ")"); 8890 } else { 8891 // We can't display the parentheses, so just show the bare note. 8892 Self.Diag(Loc, Note) << ParenRange; 8893 } 8894 } 8895 8896 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8897 return BinaryOperator::isAdditiveOp(Opc) || 8898 BinaryOperator::isMultiplicativeOp(Opc) || 8899 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8900 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8901 // not any of the logical operators. Bitwise-xor is commonly used as a 8902 // logical-xor because there is no logical-xor operator. The logical 8903 // operators, including uses of xor, have a high false positive rate for 8904 // precedence warnings. 8905 } 8906 8907 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8908 /// expression, either using a built-in or overloaded operator, 8909 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8910 /// expression. 8911 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8912 Expr **RHSExprs) { 8913 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8914 E = E->IgnoreImpCasts(); 8915 E = E->IgnoreConversionOperatorSingleStep(); 8916 E = E->IgnoreImpCasts(); 8917 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8918 E = MTE->getSubExpr(); 8919 E = E->IgnoreImpCasts(); 8920 } 8921 8922 // Built-in binary operator. 8923 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8924 if (IsArithmeticOp(OP->getOpcode())) { 8925 *Opcode = OP->getOpcode(); 8926 *RHSExprs = OP->getRHS(); 8927 return true; 8928 } 8929 } 8930 8931 // Overloaded operator. 8932 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8933 if (Call->getNumArgs() != 2) 8934 return false; 8935 8936 // Make sure this is really a binary operator that is safe to pass into 8937 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8938 OverloadedOperatorKind OO = Call->getOperator(); 8939 if (OO < OO_Plus || OO > OO_Arrow || 8940 OO == OO_PlusPlus || OO == OO_MinusMinus) 8941 return false; 8942 8943 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8944 if (IsArithmeticOp(OpKind)) { 8945 *Opcode = OpKind; 8946 *RHSExprs = Call->getArg(1); 8947 return true; 8948 } 8949 } 8950 8951 return false; 8952 } 8953 8954 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8955 /// or is a logical expression such as (x==y) which has int type, but is 8956 /// commonly interpreted as boolean. 8957 static bool ExprLooksBoolean(Expr *E) { 8958 E = E->IgnoreParenImpCasts(); 8959 8960 if (E->getType()->isBooleanType()) 8961 return true; 8962 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8963 return OP->isComparisonOp() || OP->isLogicalOp(); 8964 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8965 return OP->getOpcode() == UO_LNot; 8966 if (E->getType()->isPointerType()) 8967 return true; 8968 // FIXME: What about overloaded operator calls returning "unspecified boolean 8969 // type"s (commonly pointer-to-members)? 8970 8971 return false; 8972 } 8973 8974 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8975 /// and binary operator are mixed in a way that suggests the programmer assumed 8976 /// the conditional operator has higher precedence, for example: 8977 /// "int x = a + someBinaryCondition ? 1 : 2". 8978 static void DiagnoseConditionalPrecedence(Sema &Self, 8979 SourceLocation OpLoc, 8980 Expr *Condition, 8981 Expr *LHSExpr, 8982 Expr *RHSExpr) { 8983 BinaryOperatorKind CondOpcode; 8984 Expr *CondRHS; 8985 8986 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8987 return; 8988 if (!ExprLooksBoolean(CondRHS)) 8989 return; 8990 8991 // The condition is an arithmetic binary expression, with a right- 8992 // hand side that looks boolean, so warn. 8993 8994 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8995 ? diag::warn_precedence_bitwise_conditional 8996 : diag::warn_precedence_conditional; 8997 8998 Self.Diag(OpLoc, DiagID) 8999 << Condition->getSourceRange() 9000 << BinaryOperator::getOpcodeStr(CondOpcode); 9001 9002 SuggestParentheses( 9003 Self, OpLoc, 9004 Self.PDiag(diag::note_precedence_silence) 9005 << BinaryOperator::getOpcodeStr(CondOpcode), 9006 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 9007 9008 SuggestParentheses(Self, OpLoc, 9009 Self.PDiag(diag::note_precedence_conditional_first), 9010 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 9011 } 9012 9013 /// Compute the nullability of a conditional expression. 9014 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 9015 QualType LHSTy, QualType RHSTy, 9016 ASTContext &Ctx) { 9017 if (!ResTy->isAnyPointerType()) 9018 return ResTy; 9019 9020 auto GetNullability = [&Ctx](QualType Ty) { 9021 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 9022 if (Kind) { 9023 // For our purposes, treat _Nullable_result as _Nullable. 9024 if (*Kind == NullabilityKind::NullableResult) 9025 return NullabilityKind::Nullable; 9026 return *Kind; 9027 } 9028 return NullabilityKind::Unspecified; 9029 }; 9030 9031 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 9032 NullabilityKind MergedKind; 9033 9034 // Compute nullability of a binary conditional expression. 9035 if (IsBin) { 9036 if (LHSKind == NullabilityKind::NonNull) 9037 MergedKind = NullabilityKind::NonNull; 9038 else 9039 MergedKind = RHSKind; 9040 // Compute nullability of a normal conditional expression. 9041 } else { 9042 if (LHSKind == NullabilityKind::Nullable || 9043 RHSKind == NullabilityKind::Nullable) 9044 MergedKind = NullabilityKind::Nullable; 9045 else if (LHSKind == NullabilityKind::NonNull) 9046 MergedKind = RHSKind; 9047 else if (RHSKind == NullabilityKind::NonNull) 9048 MergedKind = LHSKind; 9049 else 9050 MergedKind = NullabilityKind::Unspecified; 9051 } 9052 9053 // Return if ResTy already has the correct nullability. 9054 if (GetNullability(ResTy) == MergedKind) 9055 return ResTy; 9056 9057 // Strip all nullability from ResTy. 9058 while (ResTy->getNullability(Ctx)) 9059 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 9060 9061 // Create a new AttributedType with the new nullability kind. 9062 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 9063 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 9064 } 9065 9066 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 9067 /// in the case of a the GNU conditional expr extension. 9068 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 9069 SourceLocation ColonLoc, 9070 Expr *CondExpr, Expr *LHSExpr, 9071 Expr *RHSExpr) { 9072 if (!Context.isDependenceAllowed()) { 9073 // C cannot handle TypoExpr nodes in the condition because it 9074 // doesn't handle dependent types properly, so make sure any TypoExprs have 9075 // been dealt with before checking the operands. 9076 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 9077 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 9078 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 9079 9080 if (!CondResult.isUsable()) 9081 return ExprError(); 9082 9083 if (LHSExpr) { 9084 if (!LHSResult.isUsable()) 9085 return ExprError(); 9086 } 9087 9088 if (!RHSResult.isUsable()) 9089 return ExprError(); 9090 9091 CondExpr = CondResult.get(); 9092 LHSExpr = LHSResult.get(); 9093 RHSExpr = RHSResult.get(); 9094 } 9095 9096 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 9097 // was the condition. 9098 OpaqueValueExpr *opaqueValue = nullptr; 9099 Expr *commonExpr = nullptr; 9100 if (!LHSExpr) { 9101 commonExpr = CondExpr; 9102 // Lower out placeholder types first. This is important so that we don't 9103 // try to capture a placeholder. This happens in few cases in C++; such 9104 // as Objective-C++'s dictionary subscripting syntax. 9105 if (commonExpr->hasPlaceholderType()) { 9106 ExprResult result = CheckPlaceholderExpr(commonExpr); 9107 if (!result.isUsable()) return ExprError(); 9108 commonExpr = result.get(); 9109 } 9110 // We usually want to apply unary conversions *before* saving, except 9111 // in the special case of a C++ l-value conditional. 9112 if (!(getLangOpts().CPlusPlus 9113 && !commonExpr->isTypeDependent() 9114 && commonExpr->getValueKind() == RHSExpr->getValueKind() 9115 && commonExpr->isGLValue() 9116 && commonExpr->isOrdinaryOrBitFieldObject() 9117 && RHSExpr->isOrdinaryOrBitFieldObject() 9118 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 9119 ExprResult commonRes = UsualUnaryConversions(commonExpr); 9120 if (commonRes.isInvalid()) 9121 return ExprError(); 9122 commonExpr = commonRes.get(); 9123 } 9124 9125 // If the common expression is a class or array prvalue, materialize it 9126 // so that we can safely refer to it multiple times. 9127 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 9128 commonExpr->getType()->isArrayType())) { 9129 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 9130 if (MatExpr.isInvalid()) 9131 return ExprError(); 9132 commonExpr = MatExpr.get(); 9133 } 9134 9135 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 9136 commonExpr->getType(), 9137 commonExpr->getValueKind(), 9138 commonExpr->getObjectKind(), 9139 commonExpr); 9140 LHSExpr = CondExpr = opaqueValue; 9141 } 9142 9143 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 9144 ExprValueKind VK = VK_PRValue; 9145 ExprObjectKind OK = OK_Ordinary; 9146 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 9147 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 9148 VK, OK, QuestionLoc); 9149 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 9150 RHS.isInvalid()) 9151 return ExprError(); 9152 9153 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 9154 RHS.get()); 9155 9156 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 9157 9158 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 9159 Context); 9160 9161 if (!commonExpr) 9162 return new (Context) 9163 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 9164 RHS.get(), result, VK, OK); 9165 9166 return new (Context) BinaryConditionalOperator( 9167 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 9168 ColonLoc, result, VK, OK); 9169 } 9170 9171 // Check if we have a conversion between incompatible cmse function pointer 9172 // types, that is, a conversion between a function pointer with the 9173 // cmse_nonsecure_call attribute and one without. 9174 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 9175 QualType ToType) { 9176 if (const auto *ToFn = 9177 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 9178 if (const auto *FromFn = 9179 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 9180 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 9181 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 9182 9183 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 9184 } 9185 } 9186 return false; 9187 } 9188 9189 // checkPointerTypesForAssignment - This is a very tricky routine (despite 9190 // being closely modeled after the C99 spec:-). The odd characteristic of this 9191 // routine is it effectively iqnores the qualifiers on the top level pointee. 9192 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 9193 // FIXME: add a couple examples in this comment. 9194 static Sema::AssignConvertType 9195 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 9196 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9197 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9198 9199 // get the "pointed to" type (ignoring qualifiers at the top level) 9200 const Type *lhptee, *rhptee; 9201 Qualifiers lhq, rhq; 9202 std::tie(lhptee, lhq) = 9203 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 9204 std::tie(rhptee, rhq) = 9205 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 9206 9207 Sema::AssignConvertType ConvTy = Sema::Compatible; 9208 9209 // C99 6.5.16.1p1: This following citation is common to constraints 9210 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 9211 // qualifiers of the type *pointed to* by the right; 9212 9213 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 9214 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 9215 lhq.compatiblyIncludesObjCLifetime(rhq)) { 9216 // Ignore lifetime for further calculation. 9217 lhq.removeObjCLifetime(); 9218 rhq.removeObjCLifetime(); 9219 } 9220 9221 if (!lhq.compatiblyIncludes(rhq)) { 9222 // Treat address-space mismatches as fatal. 9223 if (!lhq.isAddressSpaceSupersetOf(rhq)) 9224 return Sema::IncompatiblePointerDiscardsQualifiers; 9225 9226 // It's okay to add or remove GC or lifetime qualifiers when converting to 9227 // and from void*. 9228 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 9229 .compatiblyIncludes( 9230 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 9231 && (lhptee->isVoidType() || rhptee->isVoidType())) 9232 ; // keep old 9233 9234 // Treat lifetime mismatches as fatal. 9235 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 9236 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 9237 9238 // For GCC/MS compatibility, other qualifier mismatches are treated 9239 // as still compatible in C. 9240 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9241 } 9242 9243 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 9244 // incomplete type and the other is a pointer to a qualified or unqualified 9245 // version of void... 9246 if (lhptee->isVoidType()) { 9247 if (rhptee->isIncompleteOrObjectType()) 9248 return ConvTy; 9249 9250 // As an extension, we allow cast to/from void* to function pointer. 9251 assert(rhptee->isFunctionType()); 9252 return Sema::FunctionVoidPointer; 9253 } 9254 9255 if (rhptee->isVoidType()) { 9256 if (lhptee->isIncompleteOrObjectType()) 9257 return ConvTy; 9258 9259 // As an extension, we allow cast to/from void* to function pointer. 9260 assert(lhptee->isFunctionType()); 9261 return Sema::FunctionVoidPointer; 9262 } 9263 9264 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 9265 // unqualified versions of compatible types, ... 9266 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 9267 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 9268 // Check if the pointee types are compatible ignoring the sign. 9269 // We explicitly check for char so that we catch "char" vs 9270 // "unsigned char" on systems where "char" is unsigned. 9271 if (lhptee->isCharType()) 9272 ltrans = S.Context.UnsignedCharTy; 9273 else if (lhptee->hasSignedIntegerRepresentation()) 9274 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 9275 9276 if (rhptee->isCharType()) 9277 rtrans = S.Context.UnsignedCharTy; 9278 else if (rhptee->hasSignedIntegerRepresentation()) 9279 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 9280 9281 if (ltrans == rtrans) { 9282 // Types are compatible ignoring the sign. Qualifier incompatibility 9283 // takes priority over sign incompatibility because the sign 9284 // warning can be disabled. 9285 if (ConvTy != Sema::Compatible) 9286 return ConvTy; 9287 9288 return Sema::IncompatiblePointerSign; 9289 } 9290 9291 // If we are a multi-level pointer, it's possible that our issue is simply 9292 // one of qualification - e.g. char ** -> const char ** is not allowed. If 9293 // the eventual target type is the same and the pointers have the same 9294 // level of indirection, this must be the issue. 9295 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 9296 do { 9297 std::tie(lhptee, lhq) = 9298 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 9299 std::tie(rhptee, rhq) = 9300 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 9301 9302 // Inconsistent address spaces at this point is invalid, even if the 9303 // address spaces would be compatible. 9304 // FIXME: This doesn't catch address space mismatches for pointers of 9305 // different nesting levels, like: 9306 // __local int *** a; 9307 // int ** b = a; 9308 // It's not clear how to actually determine when such pointers are 9309 // invalidly incompatible. 9310 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 9311 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 9312 9313 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 9314 9315 if (lhptee == rhptee) 9316 return Sema::IncompatibleNestedPointerQualifiers; 9317 } 9318 9319 // General pointer incompatibility takes priority over qualifiers. 9320 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9321 return Sema::IncompatibleFunctionPointer; 9322 return Sema::IncompatiblePointer; 9323 } 9324 if (!S.getLangOpts().CPlusPlus && 9325 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9326 return Sema::IncompatibleFunctionPointer; 9327 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9328 return Sema::IncompatibleFunctionPointer; 9329 return ConvTy; 9330 } 9331 9332 /// checkBlockPointerTypesForAssignment - This routine determines whether two 9333 /// block pointer types are compatible or whether a block and normal pointer 9334 /// are compatible. It is more restrict than comparing two function pointer 9335 // types. 9336 static Sema::AssignConvertType 9337 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9338 QualType RHSType) { 9339 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9340 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9341 9342 QualType lhptee, rhptee; 9343 9344 // get the "pointed to" type (ignoring qualifiers at the top level) 9345 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9346 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9347 9348 // In C++, the types have to match exactly. 9349 if (S.getLangOpts().CPlusPlus) 9350 return Sema::IncompatibleBlockPointer; 9351 9352 Sema::AssignConvertType ConvTy = Sema::Compatible; 9353 9354 // For blocks we enforce that qualifiers are identical. 9355 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9356 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9357 if (S.getLangOpts().OpenCL) { 9358 LQuals.removeAddressSpace(); 9359 RQuals.removeAddressSpace(); 9360 } 9361 if (LQuals != RQuals) 9362 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9363 9364 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9365 // assignment. 9366 // The current behavior is similar to C++ lambdas. A block might be 9367 // assigned to a variable iff its return type and parameters are compatible 9368 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9369 // an assignment. Presumably it should behave in way that a function pointer 9370 // assignment does in C, so for each parameter and return type: 9371 // * CVR and address space of LHS should be a superset of CVR and address 9372 // space of RHS. 9373 // * unqualified types should be compatible. 9374 if (S.getLangOpts().OpenCL) { 9375 if (!S.Context.typesAreBlockPointerCompatible( 9376 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9377 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9378 return Sema::IncompatibleBlockPointer; 9379 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9380 return Sema::IncompatibleBlockPointer; 9381 9382 return ConvTy; 9383 } 9384 9385 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9386 /// for assignment compatibility. 9387 static Sema::AssignConvertType 9388 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9389 QualType RHSType) { 9390 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9391 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9392 9393 if (LHSType->isObjCBuiltinType()) { 9394 // Class is not compatible with ObjC object pointers. 9395 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9396 !RHSType->isObjCQualifiedClassType()) 9397 return Sema::IncompatiblePointer; 9398 return Sema::Compatible; 9399 } 9400 if (RHSType->isObjCBuiltinType()) { 9401 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9402 !LHSType->isObjCQualifiedClassType()) 9403 return Sema::IncompatiblePointer; 9404 return Sema::Compatible; 9405 } 9406 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9407 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9408 9409 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9410 // make an exception for id<P> 9411 !LHSType->isObjCQualifiedIdType()) 9412 return Sema::CompatiblePointerDiscardsQualifiers; 9413 9414 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9415 return Sema::Compatible; 9416 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9417 return Sema::IncompatibleObjCQualifiedId; 9418 return Sema::IncompatiblePointer; 9419 } 9420 9421 Sema::AssignConvertType 9422 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9423 QualType LHSType, QualType RHSType) { 9424 // Fake up an opaque expression. We don't actually care about what 9425 // cast operations are required, so if CheckAssignmentConstraints 9426 // adds casts to this they'll be wasted, but fortunately that doesn't 9427 // usually happen on valid code. 9428 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 9429 ExprResult RHSPtr = &RHSExpr; 9430 CastKind K; 9431 9432 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9433 } 9434 9435 /// This helper function returns true if QT is a vector type that has element 9436 /// type ElementType. 9437 static bool isVector(QualType QT, QualType ElementType) { 9438 if (const VectorType *VT = QT->getAs<VectorType>()) 9439 return VT->getElementType().getCanonicalType() == ElementType; 9440 return false; 9441 } 9442 9443 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9444 /// has code to accommodate several GCC extensions when type checking 9445 /// pointers. Here are some objectionable examples that GCC considers warnings: 9446 /// 9447 /// int a, *pint; 9448 /// short *pshort; 9449 /// struct foo *pfoo; 9450 /// 9451 /// pint = pshort; // warning: assignment from incompatible pointer type 9452 /// a = pint; // warning: assignment makes integer from pointer without a cast 9453 /// pint = a; // warning: assignment makes pointer from integer without a cast 9454 /// pint = pfoo; // warning: assignment from incompatible pointer type 9455 /// 9456 /// As a result, the code for dealing with pointers is more complex than the 9457 /// C99 spec dictates. 9458 /// 9459 /// Sets 'Kind' for any result kind except Incompatible. 9460 Sema::AssignConvertType 9461 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9462 CastKind &Kind, bool ConvertRHS) { 9463 QualType RHSType = RHS.get()->getType(); 9464 QualType OrigLHSType = LHSType; 9465 9466 // Get canonical types. We're not formatting these types, just comparing 9467 // them. 9468 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9469 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9470 9471 // Common case: no conversion required. 9472 if (LHSType == RHSType) { 9473 Kind = CK_NoOp; 9474 return Compatible; 9475 } 9476 9477 // If the LHS has an __auto_type, there are no additional type constraints 9478 // to be worried about. 9479 if (const auto *AT = dyn_cast<AutoType>(LHSType)) { 9480 if (AT->isGNUAutoType()) { 9481 Kind = CK_NoOp; 9482 return Compatible; 9483 } 9484 } 9485 9486 // If we have an atomic type, try a non-atomic assignment, then just add an 9487 // atomic qualification step. 9488 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9489 Sema::AssignConvertType result = 9490 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9491 if (result != Compatible) 9492 return result; 9493 if (Kind != CK_NoOp && ConvertRHS) 9494 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9495 Kind = CK_NonAtomicToAtomic; 9496 return Compatible; 9497 } 9498 9499 // If the left-hand side is a reference type, then we are in a 9500 // (rare!) case where we've allowed the use of references in C, 9501 // e.g., as a parameter type in a built-in function. In this case, 9502 // just make sure that the type referenced is compatible with the 9503 // right-hand side type. The caller is responsible for adjusting 9504 // LHSType so that the resulting expression does not have reference 9505 // type. 9506 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9507 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9508 Kind = CK_LValueBitCast; 9509 return Compatible; 9510 } 9511 return Incompatible; 9512 } 9513 9514 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9515 // to the same ExtVector type. 9516 if (LHSType->isExtVectorType()) { 9517 if (RHSType->isExtVectorType()) 9518 return Incompatible; 9519 if (RHSType->isArithmeticType()) { 9520 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9521 if (ConvertRHS) 9522 RHS = prepareVectorSplat(LHSType, RHS.get()); 9523 Kind = CK_VectorSplat; 9524 return Compatible; 9525 } 9526 } 9527 9528 // Conversions to or from vector type. 9529 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9530 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9531 // Allow assignments of an AltiVec vector type to an equivalent GCC 9532 // vector type and vice versa 9533 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9534 Kind = CK_BitCast; 9535 return Compatible; 9536 } 9537 9538 // If we are allowing lax vector conversions, and LHS and RHS are both 9539 // vectors, the total size only needs to be the same. This is a bitcast; 9540 // no bits are changed but the result type is different. 9541 if (isLaxVectorConversion(RHSType, LHSType)) { 9542 Kind = CK_BitCast; 9543 return IncompatibleVectors; 9544 } 9545 } 9546 9547 // When the RHS comes from another lax conversion (e.g. binops between 9548 // scalars and vectors) the result is canonicalized as a vector. When the 9549 // LHS is also a vector, the lax is allowed by the condition above. Handle 9550 // the case where LHS is a scalar. 9551 if (LHSType->isScalarType()) { 9552 const VectorType *VecType = RHSType->getAs<VectorType>(); 9553 if (VecType && VecType->getNumElements() == 1 && 9554 isLaxVectorConversion(RHSType, LHSType)) { 9555 ExprResult *VecExpr = &RHS; 9556 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9557 Kind = CK_BitCast; 9558 return Compatible; 9559 } 9560 } 9561 9562 // Allow assignments between fixed-length and sizeless SVE vectors. 9563 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9564 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9565 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9566 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9567 Kind = CK_BitCast; 9568 return Compatible; 9569 } 9570 9571 return Incompatible; 9572 } 9573 9574 // Diagnose attempts to convert between __ibm128, __float128 and long double 9575 // where such conversions currently can't be handled. 9576 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9577 return Incompatible; 9578 9579 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9580 // discards the imaginary part. 9581 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9582 !LHSType->getAs<ComplexType>()) 9583 return Incompatible; 9584 9585 // Arithmetic conversions. 9586 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9587 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9588 if (ConvertRHS) 9589 Kind = PrepareScalarCast(RHS, LHSType); 9590 return Compatible; 9591 } 9592 9593 // Conversions to normal pointers. 9594 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9595 // U* -> T* 9596 if (isa<PointerType>(RHSType)) { 9597 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9598 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9599 if (AddrSpaceL != AddrSpaceR) 9600 Kind = CK_AddressSpaceConversion; 9601 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9602 Kind = CK_NoOp; 9603 else 9604 Kind = CK_BitCast; 9605 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9606 } 9607 9608 // int -> T* 9609 if (RHSType->isIntegerType()) { 9610 Kind = CK_IntegralToPointer; // FIXME: null? 9611 return IntToPointer; 9612 } 9613 9614 // C pointers are not compatible with ObjC object pointers, 9615 // with two exceptions: 9616 if (isa<ObjCObjectPointerType>(RHSType)) { 9617 // - conversions to void* 9618 if (LHSPointer->getPointeeType()->isVoidType()) { 9619 Kind = CK_BitCast; 9620 return Compatible; 9621 } 9622 9623 // - conversions from 'Class' to the redefinition type 9624 if (RHSType->isObjCClassType() && 9625 Context.hasSameType(LHSType, 9626 Context.getObjCClassRedefinitionType())) { 9627 Kind = CK_BitCast; 9628 return Compatible; 9629 } 9630 9631 Kind = CK_BitCast; 9632 return IncompatiblePointer; 9633 } 9634 9635 // U^ -> void* 9636 if (RHSType->getAs<BlockPointerType>()) { 9637 if (LHSPointer->getPointeeType()->isVoidType()) { 9638 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9639 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9640 ->getPointeeType() 9641 .getAddressSpace(); 9642 Kind = 9643 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9644 return Compatible; 9645 } 9646 } 9647 9648 return Incompatible; 9649 } 9650 9651 // Conversions to block pointers. 9652 if (isa<BlockPointerType>(LHSType)) { 9653 // U^ -> T^ 9654 if (RHSType->isBlockPointerType()) { 9655 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9656 ->getPointeeType() 9657 .getAddressSpace(); 9658 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9659 ->getPointeeType() 9660 .getAddressSpace(); 9661 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9662 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9663 } 9664 9665 // int or null -> T^ 9666 if (RHSType->isIntegerType()) { 9667 Kind = CK_IntegralToPointer; // FIXME: null 9668 return IntToBlockPointer; 9669 } 9670 9671 // id -> T^ 9672 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9673 Kind = CK_AnyPointerToBlockPointerCast; 9674 return Compatible; 9675 } 9676 9677 // void* -> T^ 9678 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9679 if (RHSPT->getPointeeType()->isVoidType()) { 9680 Kind = CK_AnyPointerToBlockPointerCast; 9681 return Compatible; 9682 } 9683 9684 return Incompatible; 9685 } 9686 9687 // Conversions to Objective-C pointers. 9688 if (isa<ObjCObjectPointerType>(LHSType)) { 9689 // A* -> B* 9690 if (RHSType->isObjCObjectPointerType()) { 9691 Kind = CK_BitCast; 9692 Sema::AssignConvertType result = 9693 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9694 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9695 result == Compatible && 9696 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9697 result = IncompatibleObjCWeakRef; 9698 return result; 9699 } 9700 9701 // int or null -> A* 9702 if (RHSType->isIntegerType()) { 9703 Kind = CK_IntegralToPointer; // FIXME: null 9704 return IntToPointer; 9705 } 9706 9707 // In general, C pointers are not compatible with ObjC object pointers, 9708 // with two exceptions: 9709 if (isa<PointerType>(RHSType)) { 9710 Kind = CK_CPointerToObjCPointerCast; 9711 9712 // - conversions from 'void*' 9713 if (RHSType->isVoidPointerType()) { 9714 return Compatible; 9715 } 9716 9717 // - conversions to 'Class' from its redefinition type 9718 if (LHSType->isObjCClassType() && 9719 Context.hasSameType(RHSType, 9720 Context.getObjCClassRedefinitionType())) { 9721 return Compatible; 9722 } 9723 9724 return IncompatiblePointer; 9725 } 9726 9727 // Only under strict condition T^ is compatible with an Objective-C pointer. 9728 if (RHSType->isBlockPointerType() && 9729 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9730 if (ConvertRHS) 9731 maybeExtendBlockObject(RHS); 9732 Kind = CK_BlockPointerToObjCPointerCast; 9733 return Compatible; 9734 } 9735 9736 return Incompatible; 9737 } 9738 9739 // Conversions from pointers that are not covered by the above. 9740 if (isa<PointerType>(RHSType)) { 9741 // T* -> _Bool 9742 if (LHSType == Context.BoolTy) { 9743 Kind = CK_PointerToBoolean; 9744 return Compatible; 9745 } 9746 9747 // T* -> int 9748 if (LHSType->isIntegerType()) { 9749 Kind = CK_PointerToIntegral; 9750 return PointerToInt; 9751 } 9752 9753 return Incompatible; 9754 } 9755 9756 // Conversions from Objective-C pointers that are not covered by the above. 9757 if (isa<ObjCObjectPointerType>(RHSType)) { 9758 // T* -> _Bool 9759 if (LHSType == Context.BoolTy) { 9760 Kind = CK_PointerToBoolean; 9761 return Compatible; 9762 } 9763 9764 // T* -> int 9765 if (LHSType->isIntegerType()) { 9766 Kind = CK_PointerToIntegral; 9767 return PointerToInt; 9768 } 9769 9770 return Incompatible; 9771 } 9772 9773 // struct A -> struct B 9774 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9775 if (Context.typesAreCompatible(LHSType, RHSType)) { 9776 Kind = CK_NoOp; 9777 return Compatible; 9778 } 9779 } 9780 9781 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9782 Kind = CK_IntToOCLSampler; 9783 return Compatible; 9784 } 9785 9786 return Incompatible; 9787 } 9788 9789 /// Constructs a transparent union from an expression that is 9790 /// used to initialize the transparent union. 9791 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9792 ExprResult &EResult, QualType UnionType, 9793 FieldDecl *Field) { 9794 // Build an initializer list that designates the appropriate member 9795 // of the transparent union. 9796 Expr *E = EResult.get(); 9797 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9798 E, SourceLocation()); 9799 Initializer->setType(UnionType); 9800 Initializer->setInitializedFieldInUnion(Field); 9801 9802 // Build a compound literal constructing a value of the transparent 9803 // union type from this initializer list. 9804 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9805 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9806 VK_PRValue, Initializer, false); 9807 } 9808 9809 Sema::AssignConvertType 9810 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9811 ExprResult &RHS) { 9812 QualType RHSType = RHS.get()->getType(); 9813 9814 // If the ArgType is a Union type, we want to handle a potential 9815 // transparent_union GCC extension. 9816 const RecordType *UT = ArgType->getAsUnionType(); 9817 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9818 return Incompatible; 9819 9820 // The field to initialize within the transparent union. 9821 RecordDecl *UD = UT->getDecl(); 9822 FieldDecl *InitField = nullptr; 9823 // It's compatible if the expression matches any of the fields. 9824 for (auto *it : UD->fields()) { 9825 if (it->getType()->isPointerType()) { 9826 // If the transparent union contains a pointer type, we allow: 9827 // 1) void pointer 9828 // 2) null pointer constant 9829 if (RHSType->isPointerType()) 9830 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9831 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9832 InitField = it; 9833 break; 9834 } 9835 9836 if (RHS.get()->isNullPointerConstant(Context, 9837 Expr::NPC_ValueDependentIsNull)) { 9838 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9839 CK_NullToPointer); 9840 InitField = it; 9841 break; 9842 } 9843 } 9844 9845 CastKind Kind; 9846 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9847 == Compatible) { 9848 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9849 InitField = it; 9850 break; 9851 } 9852 } 9853 9854 if (!InitField) 9855 return Incompatible; 9856 9857 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9858 return Compatible; 9859 } 9860 9861 Sema::AssignConvertType 9862 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9863 bool Diagnose, 9864 bool DiagnoseCFAudited, 9865 bool ConvertRHS) { 9866 // We need to be able to tell the caller whether we diagnosed a problem, if 9867 // they ask us to issue diagnostics. 9868 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9869 9870 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9871 // we can't avoid *all* modifications at the moment, so we need some somewhere 9872 // to put the updated value. 9873 ExprResult LocalRHS = CallerRHS; 9874 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9875 9876 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9877 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9878 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9879 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9880 Diag(RHS.get()->getExprLoc(), 9881 diag::warn_noderef_to_dereferenceable_pointer) 9882 << RHS.get()->getSourceRange(); 9883 } 9884 } 9885 } 9886 9887 if (getLangOpts().CPlusPlus) { 9888 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9889 // C++ 5.17p3: If the left operand is not of class type, the 9890 // expression is implicitly converted (C++ 4) to the 9891 // cv-unqualified type of the left operand. 9892 QualType RHSType = RHS.get()->getType(); 9893 if (Diagnose) { 9894 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9895 AA_Assigning); 9896 } else { 9897 ImplicitConversionSequence ICS = 9898 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9899 /*SuppressUserConversions=*/false, 9900 AllowedExplicit::None, 9901 /*InOverloadResolution=*/false, 9902 /*CStyle=*/false, 9903 /*AllowObjCWritebackConversion=*/false); 9904 if (ICS.isFailure()) 9905 return Incompatible; 9906 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9907 ICS, AA_Assigning); 9908 } 9909 if (RHS.isInvalid()) 9910 return Incompatible; 9911 Sema::AssignConvertType result = Compatible; 9912 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9913 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9914 result = IncompatibleObjCWeakRef; 9915 return result; 9916 } 9917 9918 // FIXME: Currently, we fall through and treat C++ classes like C 9919 // structures. 9920 // FIXME: We also fall through for atomics; not sure what should 9921 // happen there, though. 9922 } else if (RHS.get()->getType() == Context.OverloadTy) { 9923 // As a set of extensions to C, we support overloading on functions. These 9924 // functions need to be resolved here. 9925 DeclAccessPair DAP; 9926 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9927 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9928 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9929 else 9930 return Incompatible; 9931 } 9932 9933 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9934 // a null pointer constant. 9935 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9936 LHSType->isBlockPointerType()) && 9937 RHS.get()->isNullPointerConstant(Context, 9938 Expr::NPC_ValueDependentIsNull)) { 9939 if (Diagnose || ConvertRHS) { 9940 CastKind Kind; 9941 CXXCastPath Path; 9942 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9943 /*IgnoreBaseAccess=*/false, Diagnose); 9944 if (ConvertRHS) 9945 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 9946 } 9947 return Compatible; 9948 } 9949 9950 // OpenCL queue_t type assignment. 9951 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9952 Context, Expr::NPC_ValueDependentIsNull)) { 9953 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9954 return Compatible; 9955 } 9956 9957 // This check seems unnatural, however it is necessary to ensure the proper 9958 // conversion of functions/arrays. If the conversion were done for all 9959 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9960 // expressions that suppress this implicit conversion (&, sizeof). 9961 // 9962 // Suppress this for references: C++ 8.5.3p5. 9963 if (!LHSType->isReferenceType()) { 9964 // FIXME: We potentially allocate here even if ConvertRHS is false. 9965 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9966 if (RHS.isInvalid()) 9967 return Incompatible; 9968 } 9969 CastKind Kind; 9970 Sema::AssignConvertType result = 9971 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9972 9973 // C99 6.5.16.1p2: The value of the right operand is converted to the 9974 // type of the assignment expression. 9975 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9976 // so that we can use references in built-in functions even in C. 9977 // The getNonReferenceType() call makes sure that the resulting expression 9978 // does not have reference type. 9979 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9980 QualType Ty = LHSType.getNonLValueExprType(Context); 9981 Expr *E = RHS.get(); 9982 9983 // Check for various Objective-C errors. If we are not reporting 9984 // diagnostics and just checking for errors, e.g., during overload 9985 // resolution, return Incompatible to indicate the failure. 9986 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9987 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9988 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9989 if (!Diagnose) 9990 return Incompatible; 9991 } 9992 if (getLangOpts().ObjC && 9993 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9994 E->getType(), E, Diagnose) || 9995 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9996 if (!Diagnose) 9997 return Incompatible; 9998 // Replace the expression with a corrected version and continue so we 9999 // can find further errors. 10000 RHS = E; 10001 return Compatible; 10002 } 10003 10004 if (ConvertRHS) 10005 RHS = ImpCastExprToType(E, Ty, Kind); 10006 } 10007 10008 return result; 10009 } 10010 10011 namespace { 10012 /// The original operand to an operator, prior to the application of the usual 10013 /// arithmetic conversions and converting the arguments of a builtin operator 10014 /// candidate. 10015 struct OriginalOperand { 10016 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 10017 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 10018 Op = MTE->getSubExpr(); 10019 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 10020 Op = BTE->getSubExpr(); 10021 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 10022 Orig = ICE->getSubExprAsWritten(); 10023 Conversion = ICE->getConversionFunction(); 10024 } 10025 } 10026 10027 QualType getType() const { return Orig->getType(); } 10028 10029 Expr *Orig; 10030 NamedDecl *Conversion; 10031 }; 10032 } 10033 10034 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 10035 ExprResult &RHS) { 10036 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 10037 10038 Diag(Loc, diag::err_typecheck_invalid_operands) 10039 << OrigLHS.getType() << OrigRHS.getType() 10040 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10041 10042 // If a user-defined conversion was applied to either of the operands prior 10043 // to applying the built-in operator rules, tell the user about it. 10044 if (OrigLHS.Conversion) { 10045 Diag(OrigLHS.Conversion->getLocation(), 10046 diag::note_typecheck_invalid_operands_converted) 10047 << 0 << LHS.get()->getType(); 10048 } 10049 if (OrigRHS.Conversion) { 10050 Diag(OrigRHS.Conversion->getLocation(), 10051 diag::note_typecheck_invalid_operands_converted) 10052 << 1 << RHS.get()->getType(); 10053 } 10054 10055 return QualType(); 10056 } 10057 10058 // Diagnose cases where a scalar was implicitly converted to a vector and 10059 // diagnose the underlying types. Otherwise, diagnose the error 10060 // as invalid vector logical operands for non-C++ cases. 10061 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 10062 ExprResult &RHS) { 10063 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 10064 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 10065 10066 bool LHSNatVec = LHSType->isVectorType(); 10067 bool RHSNatVec = RHSType->isVectorType(); 10068 10069 if (!(LHSNatVec && RHSNatVec)) { 10070 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 10071 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 10072 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 10073 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 10074 << Vector->getSourceRange(); 10075 return QualType(); 10076 } 10077 10078 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 10079 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 10080 << RHS.get()->getSourceRange(); 10081 10082 return QualType(); 10083 } 10084 10085 /// Try to convert a value of non-vector type to a vector type by converting 10086 /// the type to the element type of the vector and then performing a splat. 10087 /// If the language is OpenCL, we only use conversions that promote scalar 10088 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 10089 /// for float->int. 10090 /// 10091 /// OpenCL V2.0 6.2.6.p2: 10092 /// An error shall occur if any scalar operand type has greater rank 10093 /// than the type of the vector element. 10094 /// 10095 /// \param scalar - if non-null, actually perform the conversions 10096 /// \return true if the operation fails (but without diagnosing the failure) 10097 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 10098 QualType scalarTy, 10099 QualType vectorEltTy, 10100 QualType vectorTy, 10101 unsigned &DiagID) { 10102 // The conversion to apply to the scalar before splatting it, 10103 // if necessary. 10104 CastKind scalarCast = CK_NoOp; 10105 10106 if (vectorEltTy->isIntegralType(S.Context)) { 10107 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 10108 (scalarTy->isIntegerType() && 10109 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 10110 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 10111 return true; 10112 } 10113 if (!scalarTy->isIntegralType(S.Context)) 10114 return true; 10115 scalarCast = CK_IntegralCast; 10116 } else if (vectorEltTy->isRealFloatingType()) { 10117 if (scalarTy->isRealFloatingType()) { 10118 if (S.getLangOpts().OpenCL && 10119 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 10120 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 10121 return true; 10122 } 10123 scalarCast = CK_FloatingCast; 10124 } 10125 else if (scalarTy->isIntegralType(S.Context)) 10126 scalarCast = CK_IntegralToFloating; 10127 else 10128 return true; 10129 } else { 10130 return true; 10131 } 10132 10133 // Adjust scalar if desired. 10134 if (scalar) { 10135 if (scalarCast != CK_NoOp) 10136 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 10137 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 10138 } 10139 return false; 10140 } 10141 10142 /// Convert vector E to a vector with the same number of elements but different 10143 /// element type. 10144 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 10145 const auto *VecTy = E->getType()->getAs<VectorType>(); 10146 assert(VecTy && "Expression E must be a vector"); 10147 QualType NewVecTy = 10148 VecTy->isExtVectorType() 10149 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements()) 10150 : S.Context.getVectorType(ElementType, VecTy->getNumElements(), 10151 VecTy->getVectorKind()); 10152 10153 // Look through the implicit cast. Return the subexpression if its type is 10154 // NewVecTy. 10155 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10156 if (ICE->getSubExpr()->getType() == NewVecTy) 10157 return ICE->getSubExpr(); 10158 10159 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 10160 return S.ImpCastExprToType(E, NewVecTy, Cast); 10161 } 10162 10163 /// Test if a (constant) integer Int can be casted to another integer type 10164 /// IntTy without losing precision. 10165 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 10166 QualType OtherIntTy) { 10167 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 10168 10169 // Reject cases where the value of the Int is unknown as that would 10170 // possibly cause truncation, but accept cases where the scalar can be 10171 // demoted without loss of precision. 10172 Expr::EvalResult EVResult; 10173 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 10174 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 10175 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 10176 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 10177 10178 if (CstInt) { 10179 // If the scalar is constant and is of a higher order and has more active 10180 // bits that the vector element type, reject it. 10181 llvm::APSInt Result = EVResult.Val.getInt(); 10182 unsigned NumBits = IntSigned 10183 ? (Result.isNegative() ? Result.getMinSignedBits() 10184 : Result.getActiveBits()) 10185 : Result.getActiveBits(); 10186 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 10187 return true; 10188 10189 // If the signedness of the scalar type and the vector element type 10190 // differs and the number of bits is greater than that of the vector 10191 // element reject it. 10192 return (IntSigned != OtherIntSigned && 10193 NumBits > S.Context.getIntWidth(OtherIntTy)); 10194 } 10195 10196 // Reject cases where the value of the scalar is not constant and it's 10197 // order is greater than that of the vector element type. 10198 return (Order < 0); 10199 } 10200 10201 /// Test if a (constant) integer Int can be casted to floating point type 10202 /// FloatTy without losing precision. 10203 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 10204 QualType FloatTy) { 10205 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 10206 10207 // Determine if the integer constant can be expressed as a floating point 10208 // number of the appropriate type. 10209 Expr::EvalResult EVResult; 10210 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 10211 10212 uint64_t Bits = 0; 10213 if (CstInt) { 10214 // Reject constants that would be truncated if they were converted to 10215 // the floating point type. Test by simple to/from conversion. 10216 // FIXME: Ideally the conversion to an APFloat and from an APFloat 10217 // could be avoided if there was a convertFromAPInt method 10218 // which could signal back if implicit truncation occurred. 10219 llvm::APSInt Result = EVResult.Val.getInt(); 10220 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 10221 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 10222 llvm::APFloat::rmTowardZero); 10223 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 10224 !IntTy->hasSignedIntegerRepresentation()); 10225 bool Ignored = false; 10226 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 10227 &Ignored); 10228 if (Result != ConvertBack) 10229 return true; 10230 } else { 10231 // Reject types that cannot be fully encoded into the mantissa of 10232 // the float. 10233 Bits = S.Context.getTypeSize(IntTy); 10234 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 10235 S.Context.getFloatTypeSemantics(FloatTy)); 10236 if (Bits > FloatPrec) 10237 return true; 10238 } 10239 10240 return false; 10241 } 10242 10243 /// Attempt to convert and splat Scalar into a vector whose types matches 10244 /// Vector following GCC conversion rules. The rule is that implicit 10245 /// conversion can occur when Scalar can be casted to match Vector's element 10246 /// type without causing truncation of Scalar. 10247 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 10248 ExprResult *Vector) { 10249 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 10250 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 10251 const auto *VT = VectorTy->castAs<VectorType>(); 10252 10253 assert(!isa<ExtVectorType>(VT) && 10254 "ExtVectorTypes should not be handled here!"); 10255 10256 QualType VectorEltTy = VT->getElementType(); 10257 10258 // Reject cases where the vector element type or the scalar element type are 10259 // not integral or floating point types. 10260 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 10261 return true; 10262 10263 // The conversion to apply to the scalar before splatting it, 10264 // if necessary. 10265 CastKind ScalarCast = CK_NoOp; 10266 10267 // Accept cases where the vector elements are integers and the scalar is 10268 // an integer. 10269 // FIXME: Notionally if the scalar was a floating point value with a precise 10270 // integral representation, we could cast it to an appropriate integer 10271 // type and then perform the rest of the checks here. GCC will perform 10272 // this conversion in some cases as determined by the input language. 10273 // We should accept it on a language independent basis. 10274 if (VectorEltTy->isIntegralType(S.Context) && 10275 ScalarTy->isIntegralType(S.Context) && 10276 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 10277 10278 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 10279 return true; 10280 10281 ScalarCast = CK_IntegralCast; 10282 } else if (VectorEltTy->isIntegralType(S.Context) && 10283 ScalarTy->isRealFloatingType()) { 10284 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 10285 ScalarCast = CK_FloatingToIntegral; 10286 else 10287 return true; 10288 } else if (VectorEltTy->isRealFloatingType()) { 10289 if (ScalarTy->isRealFloatingType()) { 10290 10291 // Reject cases where the scalar type is not a constant and has a higher 10292 // Order than the vector element type. 10293 llvm::APFloat Result(0.0); 10294 10295 // Determine whether this is a constant scalar. In the event that the 10296 // value is dependent (and thus cannot be evaluated by the constant 10297 // evaluator), skip the evaluation. This will then diagnose once the 10298 // expression is instantiated. 10299 bool CstScalar = Scalar->get()->isValueDependent() || 10300 Scalar->get()->EvaluateAsFloat(Result, S.Context); 10301 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 10302 if (!CstScalar && Order < 0) 10303 return true; 10304 10305 // If the scalar cannot be safely casted to the vector element type, 10306 // reject it. 10307 if (CstScalar) { 10308 bool Truncated = false; 10309 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 10310 llvm::APFloat::rmNearestTiesToEven, &Truncated); 10311 if (Truncated) 10312 return true; 10313 } 10314 10315 ScalarCast = CK_FloatingCast; 10316 } else if (ScalarTy->isIntegralType(S.Context)) { 10317 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 10318 return true; 10319 10320 ScalarCast = CK_IntegralToFloating; 10321 } else 10322 return true; 10323 } else if (ScalarTy->isEnumeralType()) 10324 return true; 10325 10326 // Adjust scalar if desired. 10327 if (Scalar) { 10328 if (ScalarCast != CK_NoOp) 10329 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 10330 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 10331 } 10332 return false; 10333 } 10334 10335 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 10336 SourceLocation Loc, bool IsCompAssign, 10337 bool AllowBothBool, 10338 bool AllowBoolConversions, 10339 bool AllowBoolOperation, 10340 bool ReportInvalid) { 10341 if (!IsCompAssign) { 10342 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10343 if (LHS.isInvalid()) 10344 return QualType(); 10345 } 10346 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10347 if (RHS.isInvalid()) 10348 return QualType(); 10349 10350 // For conversion purposes, we ignore any qualifiers. 10351 // For example, "const float" and "float" are equivalent. 10352 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10353 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10354 10355 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10356 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10357 assert(LHSVecType || RHSVecType); 10358 10359 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10360 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10361 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); 10362 10363 // AltiVec-style "vector bool op vector bool" combinations are allowed 10364 // for some operators but not others. 10365 if (!AllowBothBool && 10366 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10367 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10368 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); 10369 10370 // This operation may not be performed on boolean vectors. 10371 if (!AllowBoolOperation && 10372 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType())) 10373 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); 10374 10375 // If the vector types are identical, return. 10376 if (Context.hasSameType(LHSType, RHSType)) 10377 return LHSType; 10378 10379 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10380 if (LHSVecType && RHSVecType && 10381 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10382 if (isa<ExtVectorType>(LHSVecType)) { 10383 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10384 return LHSType; 10385 } 10386 10387 if (!IsCompAssign) 10388 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10389 return RHSType; 10390 } 10391 10392 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10393 // can be mixed, with the result being the non-bool type. The non-bool 10394 // operand must have integer element type. 10395 if (AllowBoolConversions && LHSVecType && RHSVecType && 10396 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10397 (Context.getTypeSize(LHSVecType->getElementType()) == 10398 Context.getTypeSize(RHSVecType->getElementType()))) { 10399 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10400 LHSVecType->getElementType()->isIntegerType() && 10401 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10402 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10403 return LHSType; 10404 } 10405 if (!IsCompAssign && 10406 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10407 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10408 RHSVecType->getElementType()->isIntegerType()) { 10409 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10410 return RHSType; 10411 } 10412 } 10413 10414 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10415 // since the ambiguity can affect the ABI. 10416 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10417 const VectorType *VecType = SecondType->getAs<VectorType>(); 10418 return FirstType->isSizelessBuiltinType() && VecType && 10419 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10420 VecType->getVectorKind() == 10421 VectorType::SveFixedLengthPredicateVector); 10422 }; 10423 10424 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10425 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10426 return QualType(); 10427 } 10428 10429 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10430 // since the ambiguity can affect the ABI. 10431 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10432 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10433 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10434 10435 if (FirstVecType && SecondVecType) 10436 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10437 (SecondVecType->getVectorKind() == 10438 VectorType::SveFixedLengthDataVector || 10439 SecondVecType->getVectorKind() == 10440 VectorType::SveFixedLengthPredicateVector); 10441 10442 return FirstType->isSizelessBuiltinType() && SecondVecType && 10443 SecondVecType->getVectorKind() == VectorType::GenericVector; 10444 }; 10445 10446 if (IsSveGnuConversion(LHSType, RHSType) || 10447 IsSveGnuConversion(RHSType, LHSType)) { 10448 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10449 return QualType(); 10450 } 10451 10452 // If there's a vector type and a scalar, try to convert the scalar to 10453 // the vector element type and splat. 10454 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10455 if (!RHSVecType) { 10456 if (isa<ExtVectorType>(LHSVecType)) { 10457 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10458 LHSVecType->getElementType(), LHSType, 10459 DiagID)) 10460 return LHSType; 10461 } else { 10462 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10463 return LHSType; 10464 } 10465 } 10466 if (!LHSVecType) { 10467 if (isa<ExtVectorType>(RHSVecType)) { 10468 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10469 LHSType, RHSVecType->getElementType(), 10470 RHSType, DiagID)) 10471 return RHSType; 10472 } else { 10473 if (LHS.get()->isLValue() || 10474 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10475 return RHSType; 10476 } 10477 } 10478 10479 // FIXME: The code below also handles conversion between vectors and 10480 // non-scalars, we should break this down into fine grained specific checks 10481 // and emit proper diagnostics. 10482 QualType VecType = LHSVecType ? LHSType : RHSType; 10483 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10484 QualType OtherType = LHSVecType ? RHSType : LHSType; 10485 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10486 if (isLaxVectorConversion(OtherType, VecType)) { 10487 // If we're allowing lax vector conversions, only the total (data) size 10488 // needs to be the same. For non compound assignment, if one of the types is 10489 // scalar, the result is always the vector type. 10490 if (!IsCompAssign) { 10491 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10492 return VecType; 10493 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10494 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10495 // type. Note that this is already done by non-compound assignments in 10496 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10497 // <1 x T> -> T. The result is also a vector type. 10498 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10499 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10500 ExprResult *RHSExpr = &RHS; 10501 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10502 return VecType; 10503 } 10504 } 10505 10506 // Okay, the expression is invalid. 10507 10508 // If there's a non-vector, non-real operand, diagnose that. 10509 if ((!RHSVecType && !RHSType->isRealType()) || 10510 (!LHSVecType && !LHSType->isRealType())) { 10511 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10512 << LHSType << RHSType 10513 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10514 return QualType(); 10515 } 10516 10517 // OpenCL V1.1 6.2.6.p1: 10518 // If the operands are of more than one vector type, then an error shall 10519 // occur. Implicit conversions between vector types are not permitted, per 10520 // section 6.2.1. 10521 if (getLangOpts().OpenCL && 10522 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10523 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10524 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10525 << RHSType; 10526 return QualType(); 10527 } 10528 10529 10530 // If there is a vector type that is not a ExtVector and a scalar, we reach 10531 // this point if scalar could not be converted to the vector's element type 10532 // without truncation. 10533 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10534 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10535 QualType Scalar = LHSVecType ? RHSType : LHSType; 10536 QualType Vector = LHSVecType ? LHSType : RHSType; 10537 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10538 Diag(Loc, 10539 diag::err_typecheck_vector_not_convertable_implict_truncation) 10540 << ScalarOrVector << Scalar << Vector; 10541 10542 return QualType(); 10543 } 10544 10545 // Otherwise, use the generic diagnostic. 10546 Diag(Loc, DiagID) 10547 << LHSType << RHSType 10548 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10549 return QualType(); 10550 } 10551 10552 QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, 10553 SourceLocation Loc, 10554 bool IsCompAssign, 10555 ArithConvKind OperationKind) { 10556 if (!IsCompAssign) { 10557 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10558 if (LHS.isInvalid()) 10559 return QualType(); 10560 } 10561 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10562 if (RHS.isInvalid()) 10563 return QualType(); 10564 10565 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10566 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10567 10568 unsigned DiagID = diag::err_typecheck_invalid_operands; 10569 if ((OperationKind == ACK_Arithmetic) && 10570 (LHSType->castAs<BuiltinType>()->isSVEBool() || 10571 RHSType->castAs<BuiltinType>()->isSVEBool())) { 10572 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 10573 << RHS.get()->getSourceRange(); 10574 return QualType(); 10575 } 10576 10577 if (Context.hasSameType(LHSType, RHSType)) 10578 return LHSType; 10579 10580 auto tryScalableVectorConvert = [this](ExprResult *Src, QualType SrcType, 10581 QualType DestType) { 10582 const QualType DestBaseType = DestType->getSveEltType(Context); 10583 if (DestBaseType->getUnqualifiedDesugaredType() == 10584 SrcType->getUnqualifiedDesugaredType()) { 10585 unsigned DiagID = diag::err_typecheck_invalid_operands; 10586 if (!tryVectorConvertAndSplat(*this, Src, SrcType, DestBaseType, DestType, 10587 DiagID)) 10588 return DestType; 10589 } 10590 return QualType(); 10591 }; 10592 10593 if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) { 10594 auto DestType = tryScalableVectorConvert(&RHS, RHSType, LHSType); 10595 if (DestType == QualType()) 10596 return InvalidOperands(Loc, LHS, RHS); 10597 return DestType; 10598 } 10599 10600 if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) { 10601 auto DestType = tryScalableVectorConvert((IsCompAssign ? nullptr : &LHS), 10602 LHSType, RHSType); 10603 if (DestType == QualType()) 10604 return InvalidOperands(Loc, LHS, RHS); 10605 return DestType; 10606 } 10607 10608 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 10609 << RHS.get()->getSourceRange(); 10610 return QualType(); 10611 } 10612 10613 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10614 // expression. These are mainly cases where the null pointer is used as an 10615 // integer instead of a pointer. 10616 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10617 SourceLocation Loc, bool IsCompare) { 10618 // The canonical way to check for a GNU null is with isNullPointerConstant, 10619 // but we use a bit of a hack here for speed; this is a relatively 10620 // hot path, and isNullPointerConstant is slow. 10621 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10622 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10623 10624 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10625 10626 // Avoid analyzing cases where the result will either be invalid (and 10627 // diagnosed as such) or entirely valid and not something to warn about. 10628 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10629 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10630 return; 10631 10632 // Comparison operations would not make sense with a null pointer no matter 10633 // what the other expression is. 10634 if (!IsCompare) { 10635 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10636 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10637 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10638 return; 10639 } 10640 10641 // The rest of the operations only make sense with a null pointer 10642 // if the other expression is a pointer. 10643 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10644 NonNullType->canDecayToPointerType()) 10645 return; 10646 10647 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10648 << LHSNull /* LHS is NULL */ << NonNullType 10649 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10650 } 10651 10652 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10653 SourceLocation Loc) { 10654 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10655 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10656 if (!LUE || !RUE) 10657 return; 10658 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10659 RUE->getKind() != UETT_SizeOf) 10660 return; 10661 10662 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10663 QualType LHSTy = LHSArg->getType(); 10664 QualType RHSTy; 10665 10666 if (RUE->isArgumentType()) 10667 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10668 else 10669 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10670 10671 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10672 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10673 return; 10674 10675 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10676 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10677 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10678 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10679 << LHSArgDecl; 10680 } 10681 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10682 QualType ArrayElemTy = ArrayTy->getElementType(); 10683 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10684 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10685 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10686 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10687 return; 10688 S.Diag(Loc, diag::warn_division_sizeof_array) 10689 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10690 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10691 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10692 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10693 << LHSArgDecl; 10694 } 10695 10696 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10697 } 10698 } 10699 10700 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10701 ExprResult &RHS, 10702 SourceLocation Loc, bool IsDiv) { 10703 // Check for division/remainder by zero. 10704 Expr::EvalResult RHSValue; 10705 if (!RHS.get()->isValueDependent() && 10706 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10707 RHSValue.Val.getInt() == 0) 10708 S.DiagRuntimeBehavior(Loc, RHS.get(), 10709 S.PDiag(diag::warn_remainder_division_by_zero) 10710 << IsDiv << RHS.get()->getSourceRange()); 10711 } 10712 10713 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10714 SourceLocation Loc, 10715 bool IsCompAssign, bool IsDiv) { 10716 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10717 10718 QualType LHSTy = LHS.get()->getType(); 10719 QualType RHSTy = RHS.get()->getType(); 10720 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10721 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10722 /*AllowBothBool*/ getLangOpts().AltiVec, 10723 /*AllowBoolConversions*/ false, 10724 /*AllowBooleanOperation*/ false, 10725 /*ReportInvalid*/ true); 10726 if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType()) 10727 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 10728 ACK_Arithmetic); 10729 if (!IsDiv && 10730 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10731 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10732 // For division, only matrix-by-scalar is supported. Other combinations with 10733 // matrix types are invalid. 10734 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10735 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10736 10737 QualType compType = UsualArithmeticConversions( 10738 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10739 if (LHS.isInvalid() || RHS.isInvalid()) 10740 return QualType(); 10741 10742 10743 if (compType.isNull() || !compType->isArithmeticType()) 10744 return InvalidOperands(Loc, LHS, RHS); 10745 if (IsDiv) { 10746 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10747 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10748 } 10749 return compType; 10750 } 10751 10752 QualType Sema::CheckRemainderOperands( 10753 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10754 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10755 10756 if (LHS.get()->getType()->isVectorType() || 10757 RHS.get()->getType()->isVectorType()) { 10758 if (LHS.get()->getType()->hasIntegerRepresentation() && 10759 RHS.get()->getType()->hasIntegerRepresentation()) 10760 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10761 /*AllowBothBool*/ getLangOpts().AltiVec, 10762 /*AllowBoolConversions*/ false, 10763 /*AllowBooleanOperation*/ false, 10764 /*ReportInvalid*/ true); 10765 return InvalidOperands(Loc, LHS, RHS); 10766 } 10767 10768 if (LHS.get()->getType()->isVLSTBuiltinType() || 10769 RHS.get()->getType()->isVLSTBuiltinType()) { 10770 if (LHS.get()->getType()->hasIntegerRepresentation() && 10771 RHS.get()->getType()->hasIntegerRepresentation()) 10772 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 10773 ACK_Arithmetic); 10774 10775 return InvalidOperands(Loc, LHS, RHS); 10776 } 10777 10778 QualType compType = UsualArithmeticConversions( 10779 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10780 if (LHS.isInvalid() || RHS.isInvalid()) 10781 return QualType(); 10782 10783 if (compType.isNull() || !compType->isIntegerType()) 10784 return InvalidOperands(Loc, LHS, RHS); 10785 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10786 return compType; 10787 } 10788 10789 /// Diagnose invalid arithmetic on two void pointers. 10790 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10791 Expr *LHSExpr, Expr *RHSExpr) { 10792 S.Diag(Loc, S.getLangOpts().CPlusPlus 10793 ? diag::err_typecheck_pointer_arith_void_type 10794 : diag::ext_gnu_void_ptr) 10795 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10796 << RHSExpr->getSourceRange(); 10797 } 10798 10799 /// Diagnose invalid arithmetic on a void pointer. 10800 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10801 Expr *Pointer) { 10802 S.Diag(Loc, S.getLangOpts().CPlusPlus 10803 ? diag::err_typecheck_pointer_arith_void_type 10804 : diag::ext_gnu_void_ptr) 10805 << 0 /* one pointer */ << Pointer->getSourceRange(); 10806 } 10807 10808 /// Diagnose invalid arithmetic on a null pointer. 10809 /// 10810 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10811 /// idiom, which we recognize as a GNU extension. 10812 /// 10813 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10814 Expr *Pointer, bool IsGNUIdiom) { 10815 if (IsGNUIdiom) 10816 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10817 << Pointer->getSourceRange(); 10818 else 10819 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10820 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10821 } 10822 10823 /// Diagnose invalid subraction on a null pointer. 10824 /// 10825 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, 10826 Expr *Pointer, bool BothNull) { 10827 // Null - null is valid in C++ [expr.add]p7 10828 if (BothNull && S.getLangOpts().CPlusPlus) 10829 return; 10830 10831 // Is this s a macro from a system header? 10832 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) 10833 return; 10834 10835 S.Diag(Loc, diag::warn_pointer_sub_null_ptr) 10836 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10837 } 10838 10839 /// Diagnose invalid arithmetic on two function pointers. 10840 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10841 Expr *LHS, Expr *RHS) { 10842 assert(LHS->getType()->isAnyPointerType()); 10843 assert(RHS->getType()->isAnyPointerType()); 10844 S.Diag(Loc, S.getLangOpts().CPlusPlus 10845 ? diag::err_typecheck_pointer_arith_function_type 10846 : diag::ext_gnu_ptr_func_arith) 10847 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10848 // We only show the second type if it differs from the first. 10849 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10850 RHS->getType()) 10851 << RHS->getType()->getPointeeType() 10852 << LHS->getSourceRange() << RHS->getSourceRange(); 10853 } 10854 10855 /// Diagnose invalid arithmetic on a function pointer. 10856 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10857 Expr *Pointer) { 10858 assert(Pointer->getType()->isAnyPointerType()); 10859 S.Diag(Loc, S.getLangOpts().CPlusPlus 10860 ? diag::err_typecheck_pointer_arith_function_type 10861 : diag::ext_gnu_ptr_func_arith) 10862 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10863 << 0 /* one pointer, so only one type */ 10864 << Pointer->getSourceRange(); 10865 } 10866 10867 /// Emit error if Operand is incomplete pointer type 10868 /// 10869 /// \returns True if pointer has incomplete type 10870 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10871 Expr *Operand) { 10872 QualType ResType = Operand->getType(); 10873 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10874 ResType = ResAtomicType->getValueType(); 10875 10876 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10877 QualType PointeeTy = ResType->getPointeeType(); 10878 return S.RequireCompleteSizedType( 10879 Loc, PointeeTy, 10880 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10881 Operand->getSourceRange()); 10882 } 10883 10884 /// Check the validity of an arithmetic pointer operand. 10885 /// 10886 /// If the operand has pointer type, this code will check for pointer types 10887 /// which are invalid in arithmetic operations. These will be diagnosed 10888 /// appropriately, including whether or not the use is supported as an 10889 /// extension. 10890 /// 10891 /// \returns True when the operand is valid to use (even if as an extension). 10892 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10893 Expr *Operand) { 10894 QualType ResType = Operand->getType(); 10895 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10896 ResType = ResAtomicType->getValueType(); 10897 10898 if (!ResType->isAnyPointerType()) return true; 10899 10900 QualType PointeeTy = ResType->getPointeeType(); 10901 if (PointeeTy->isVoidType()) { 10902 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10903 return !S.getLangOpts().CPlusPlus; 10904 } 10905 if (PointeeTy->isFunctionType()) { 10906 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10907 return !S.getLangOpts().CPlusPlus; 10908 } 10909 10910 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10911 10912 return true; 10913 } 10914 10915 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10916 /// operands. 10917 /// 10918 /// This routine will diagnose any invalid arithmetic on pointer operands much 10919 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10920 /// for emitting a single diagnostic even for operations where both LHS and RHS 10921 /// are (potentially problematic) pointers. 10922 /// 10923 /// \returns True when the operand is valid to use (even if as an extension). 10924 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10925 Expr *LHSExpr, Expr *RHSExpr) { 10926 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10927 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10928 if (!isLHSPointer && !isRHSPointer) return true; 10929 10930 QualType LHSPointeeTy, RHSPointeeTy; 10931 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10932 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10933 10934 // if both are pointers check if operation is valid wrt address spaces 10935 if (isLHSPointer && isRHSPointer) { 10936 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10937 S.Diag(Loc, 10938 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10939 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10940 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10941 return false; 10942 } 10943 } 10944 10945 // Check for arithmetic on pointers to incomplete types. 10946 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10947 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10948 if (isLHSVoidPtr || isRHSVoidPtr) { 10949 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10950 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10951 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10952 10953 return !S.getLangOpts().CPlusPlus; 10954 } 10955 10956 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10957 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10958 if (isLHSFuncPtr || isRHSFuncPtr) { 10959 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10960 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10961 RHSExpr); 10962 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10963 10964 return !S.getLangOpts().CPlusPlus; 10965 } 10966 10967 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10968 return false; 10969 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10970 return false; 10971 10972 return true; 10973 } 10974 10975 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10976 /// literal. 10977 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10978 Expr *LHSExpr, Expr *RHSExpr) { 10979 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10980 Expr* IndexExpr = RHSExpr; 10981 if (!StrExpr) { 10982 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10983 IndexExpr = LHSExpr; 10984 } 10985 10986 bool IsStringPlusInt = StrExpr && 10987 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10988 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10989 return; 10990 10991 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10992 Self.Diag(OpLoc, diag::warn_string_plus_int) 10993 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10994 10995 // Only print a fixit for "str" + int, not for int + "str". 10996 if (IndexExpr == RHSExpr) { 10997 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10998 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10999 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 11000 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 11001 << FixItHint::CreateInsertion(EndLoc, "]"); 11002 } else 11003 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 11004 } 11005 11006 /// Emit a warning when adding a char literal to a string. 11007 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 11008 Expr *LHSExpr, Expr *RHSExpr) { 11009 const Expr *StringRefExpr = LHSExpr; 11010 const CharacterLiteral *CharExpr = 11011 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 11012 11013 if (!CharExpr) { 11014 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 11015 StringRefExpr = RHSExpr; 11016 } 11017 11018 if (!CharExpr || !StringRefExpr) 11019 return; 11020 11021 const QualType StringType = StringRefExpr->getType(); 11022 11023 // Return if not a PointerType. 11024 if (!StringType->isAnyPointerType()) 11025 return; 11026 11027 // Return if not a CharacterType. 11028 if (!StringType->getPointeeType()->isAnyCharacterType()) 11029 return; 11030 11031 ASTContext &Ctx = Self.getASTContext(); 11032 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 11033 11034 const QualType CharType = CharExpr->getType(); 11035 if (!CharType->isAnyCharacterType() && 11036 CharType->isIntegerType() && 11037 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 11038 Self.Diag(OpLoc, diag::warn_string_plus_char) 11039 << DiagRange << Ctx.CharTy; 11040 } else { 11041 Self.Diag(OpLoc, diag::warn_string_plus_char) 11042 << DiagRange << CharExpr->getType(); 11043 } 11044 11045 // Only print a fixit for str + char, not for char + str. 11046 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 11047 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 11048 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 11049 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 11050 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 11051 << FixItHint::CreateInsertion(EndLoc, "]"); 11052 } else { 11053 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 11054 } 11055 } 11056 11057 /// Emit error when two pointers are incompatible. 11058 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 11059 Expr *LHSExpr, Expr *RHSExpr) { 11060 assert(LHSExpr->getType()->isAnyPointerType()); 11061 assert(RHSExpr->getType()->isAnyPointerType()); 11062 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 11063 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 11064 << RHSExpr->getSourceRange(); 11065 } 11066 11067 // C99 6.5.6 11068 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 11069 SourceLocation Loc, BinaryOperatorKind Opc, 11070 QualType* CompLHSTy) { 11071 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11072 11073 if (LHS.get()->getType()->isVectorType() || 11074 RHS.get()->getType()->isVectorType()) { 11075 QualType compType = 11076 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy, 11077 /*AllowBothBool*/ getLangOpts().AltiVec, 11078 /*AllowBoolConversions*/ getLangOpts().ZVector, 11079 /*AllowBooleanOperation*/ false, 11080 /*ReportInvalid*/ true); 11081 if (CompLHSTy) *CompLHSTy = compType; 11082 return compType; 11083 } 11084 11085 if (LHS.get()->getType()->isVLSTBuiltinType() || 11086 RHS.get()->getType()->isVLSTBuiltinType()) { 11087 QualType compType = 11088 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic); 11089 if (CompLHSTy) 11090 *CompLHSTy = compType; 11091 return compType; 11092 } 11093 11094 if (LHS.get()->getType()->isConstantMatrixType() || 11095 RHS.get()->getType()->isConstantMatrixType()) { 11096 QualType compType = 11097 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 11098 if (CompLHSTy) 11099 *CompLHSTy = compType; 11100 return compType; 11101 } 11102 11103 QualType compType = UsualArithmeticConversions( 11104 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 11105 if (LHS.isInvalid() || RHS.isInvalid()) 11106 return QualType(); 11107 11108 // Diagnose "string literal" '+' int and string '+' "char literal". 11109 if (Opc == BO_Add) { 11110 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 11111 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 11112 } 11113 11114 // handle the common case first (both operands are arithmetic). 11115 if (!compType.isNull() && compType->isArithmeticType()) { 11116 if (CompLHSTy) *CompLHSTy = compType; 11117 return compType; 11118 } 11119 11120 // Type-checking. Ultimately the pointer's going to be in PExp; 11121 // note that we bias towards the LHS being the pointer. 11122 Expr *PExp = LHS.get(), *IExp = RHS.get(); 11123 11124 bool isObjCPointer; 11125 if (PExp->getType()->isPointerType()) { 11126 isObjCPointer = false; 11127 } else if (PExp->getType()->isObjCObjectPointerType()) { 11128 isObjCPointer = true; 11129 } else { 11130 std::swap(PExp, IExp); 11131 if (PExp->getType()->isPointerType()) { 11132 isObjCPointer = false; 11133 } else if (PExp->getType()->isObjCObjectPointerType()) { 11134 isObjCPointer = true; 11135 } else { 11136 return InvalidOperands(Loc, LHS, RHS); 11137 } 11138 } 11139 assert(PExp->getType()->isAnyPointerType()); 11140 11141 if (!IExp->getType()->isIntegerType()) 11142 return InvalidOperands(Loc, LHS, RHS); 11143 11144 // Adding to a null pointer results in undefined behavior. 11145 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 11146 Context, Expr::NPC_ValueDependentIsNotNull)) { 11147 // In C++ adding zero to a null pointer is defined. 11148 Expr::EvalResult KnownVal; 11149 if (!getLangOpts().CPlusPlus || 11150 (!IExp->isValueDependent() && 11151 (!IExp->EvaluateAsInt(KnownVal, Context) || 11152 KnownVal.Val.getInt() != 0))) { 11153 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 11154 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 11155 Context, BO_Add, PExp, IExp); 11156 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 11157 } 11158 } 11159 11160 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 11161 return QualType(); 11162 11163 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 11164 return QualType(); 11165 11166 // Check array bounds for pointer arithemtic 11167 CheckArrayAccess(PExp, IExp); 11168 11169 if (CompLHSTy) { 11170 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 11171 if (LHSTy.isNull()) { 11172 LHSTy = LHS.get()->getType(); 11173 if (LHSTy->isPromotableIntegerType()) 11174 LHSTy = Context.getPromotedIntegerType(LHSTy); 11175 } 11176 *CompLHSTy = LHSTy; 11177 } 11178 11179 return PExp->getType(); 11180 } 11181 11182 // C99 6.5.6 11183 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 11184 SourceLocation Loc, 11185 QualType* CompLHSTy) { 11186 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11187 11188 if (LHS.get()->getType()->isVectorType() || 11189 RHS.get()->getType()->isVectorType()) { 11190 QualType compType = 11191 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy, 11192 /*AllowBothBool*/ getLangOpts().AltiVec, 11193 /*AllowBoolConversions*/ getLangOpts().ZVector, 11194 /*AllowBooleanOperation*/ false, 11195 /*ReportInvalid*/ true); 11196 if (CompLHSTy) *CompLHSTy = compType; 11197 return compType; 11198 } 11199 11200 if (LHS.get()->getType()->isVLSTBuiltinType() || 11201 RHS.get()->getType()->isVLSTBuiltinType()) { 11202 QualType compType = 11203 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic); 11204 if (CompLHSTy) 11205 *CompLHSTy = compType; 11206 return compType; 11207 } 11208 11209 if (LHS.get()->getType()->isConstantMatrixType() || 11210 RHS.get()->getType()->isConstantMatrixType()) { 11211 QualType compType = 11212 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 11213 if (CompLHSTy) 11214 *CompLHSTy = compType; 11215 return compType; 11216 } 11217 11218 QualType compType = UsualArithmeticConversions( 11219 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 11220 if (LHS.isInvalid() || RHS.isInvalid()) 11221 return QualType(); 11222 11223 // Enforce type constraints: C99 6.5.6p3. 11224 11225 // Handle the common case first (both operands are arithmetic). 11226 if (!compType.isNull() && compType->isArithmeticType()) { 11227 if (CompLHSTy) *CompLHSTy = compType; 11228 return compType; 11229 } 11230 11231 // Either ptr - int or ptr - ptr. 11232 if (LHS.get()->getType()->isAnyPointerType()) { 11233 QualType lpointee = LHS.get()->getType()->getPointeeType(); 11234 11235 // Diagnose bad cases where we step over interface counts. 11236 if (LHS.get()->getType()->isObjCObjectPointerType() && 11237 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 11238 return QualType(); 11239 11240 // The result type of a pointer-int computation is the pointer type. 11241 if (RHS.get()->getType()->isIntegerType()) { 11242 // Subtracting from a null pointer should produce a warning. 11243 // The last argument to the diagnose call says this doesn't match the 11244 // GNU int-to-pointer idiom. 11245 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 11246 Expr::NPC_ValueDependentIsNotNull)) { 11247 // In C++ adding zero to a null pointer is defined. 11248 Expr::EvalResult KnownVal; 11249 if (!getLangOpts().CPlusPlus || 11250 (!RHS.get()->isValueDependent() && 11251 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 11252 KnownVal.Val.getInt() != 0))) { 11253 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 11254 } 11255 } 11256 11257 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 11258 return QualType(); 11259 11260 // Check array bounds for pointer arithemtic 11261 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 11262 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 11263 11264 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 11265 return LHS.get()->getType(); 11266 } 11267 11268 // Handle pointer-pointer subtractions. 11269 if (const PointerType *RHSPTy 11270 = RHS.get()->getType()->getAs<PointerType>()) { 11271 QualType rpointee = RHSPTy->getPointeeType(); 11272 11273 if (getLangOpts().CPlusPlus) { 11274 // Pointee types must be the same: C++ [expr.add] 11275 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 11276 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 11277 } 11278 } else { 11279 // Pointee types must be compatible C99 6.5.6p3 11280 if (!Context.typesAreCompatible( 11281 Context.getCanonicalType(lpointee).getUnqualifiedType(), 11282 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 11283 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 11284 return QualType(); 11285 } 11286 } 11287 11288 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 11289 LHS.get(), RHS.get())) 11290 return QualType(); 11291 11292 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( 11293 Context, Expr::NPC_ValueDependentIsNotNull); 11294 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( 11295 Context, Expr::NPC_ValueDependentIsNotNull); 11296 11297 // Subtracting nullptr or from nullptr is suspect 11298 if (LHSIsNullPtr) 11299 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); 11300 if (RHSIsNullPtr) 11301 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); 11302 11303 // The pointee type may have zero size. As an extension, a structure or 11304 // union may have zero size or an array may have zero length. In this 11305 // case subtraction does not make sense. 11306 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 11307 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 11308 if (ElementSize.isZero()) { 11309 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 11310 << rpointee.getUnqualifiedType() 11311 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11312 } 11313 } 11314 11315 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 11316 return Context.getPointerDiffType(); 11317 } 11318 } 11319 11320 return InvalidOperands(Loc, LHS, RHS); 11321 } 11322 11323 static bool isScopedEnumerationType(QualType T) { 11324 if (const EnumType *ET = T->getAs<EnumType>()) 11325 return ET->getDecl()->isScoped(); 11326 return false; 11327 } 11328 11329 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 11330 SourceLocation Loc, BinaryOperatorKind Opc, 11331 QualType LHSType) { 11332 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 11333 // so skip remaining warnings as we don't want to modify values within Sema. 11334 if (S.getLangOpts().OpenCL) 11335 return; 11336 11337 // Check right/shifter operand 11338 Expr::EvalResult RHSResult; 11339 if (RHS.get()->isValueDependent() || 11340 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 11341 return; 11342 llvm::APSInt Right = RHSResult.Val.getInt(); 11343 11344 if (Right.isNegative()) { 11345 S.DiagRuntimeBehavior(Loc, RHS.get(), 11346 S.PDiag(diag::warn_shift_negative) 11347 << RHS.get()->getSourceRange()); 11348 return; 11349 } 11350 11351 QualType LHSExprType = LHS.get()->getType(); 11352 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 11353 if (LHSExprType->isBitIntType()) 11354 LeftSize = S.Context.getIntWidth(LHSExprType); 11355 else if (LHSExprType->isFixedPointType()) { 11356 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 11357 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 11358 } 11359 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 11360 if (Right.uge(LeftBits)) { 11361 S.DiagRuntimeBehavior(Loc, RHS.get(), 11362 S.PDiag(diag::warn_shift_gt_typewidth) 11363 << RHS.get()->getSourceRange()); 11364 return; 11365 } 11366 11367 // FIXME: We probably need to handle fixed point types specially here. 11368 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 11369 return; 11370 11371 // When left shifting an ICE which is signed, we can check for overflow which 11372 // according to C++ standards prior to C++2a has undefined behavior 11373 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 11374 // more than the maximum value representable in the result type, so never 11375 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 11376 // expression is still probably a bug.) 11377 Expr::EvalResult LHSResult; 11378 if (LHS.get()->isValueDependent() || 11379 LHSType->hasUnsignedIntegerRepresentation() || 11380 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 11381 return; 11382 llvm::APSInt Left = LHSResult.Val.getInt(); 11383 11384 // If LHS does not have a signed type and non-negative value 11385 // then, the behavior is undefined before C++2a. Warn about it. 11386 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 11387 !S.getLangOpts().CPlusPlus20) { 11388 S.DiagRuntimeBehavior(Loc, LHS.get(), 11389 S.PDiag(diag::warn_shift_lhs_negative) 11390 << LHS.get()->getSourceRange()); 11391 return; 11392 } 11393 11394 llvm::APInt ResultBits = 11395 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 11396 if (LeftBits.uge(ResultBits)) 11397 return; 11398 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 11399 Result = Result.shl(Right); 11400 11401 // Print the bit representation of the signed integer as an unsigned 11402 // hexadecimal number. 11403 SmallString<40> HexResult; 11404 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 11405 11406 // If we are only missing a sign bit, this is less likely to result in actual 11407 // bugs -- if the result is cast back to an unsigned type, it will have the 11408 // expected value. Thus we place this behind a different warning that can be 11409 // turned off separately if needed. 11410 if (LeftBits == ResultBits - 1) { 11411 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 11412 << HexResult << LHSType 11413 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11414 return; 11415 } 11416 11417 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 11418 << HexResult.str() << Result.getMinSignedBits() << LHSType 11419 << Left.getBitWidth() << LHS.get()->getSourceRange() 11420 << RHS.get()->getSourceRange(); 11421 } 11422 11423 /// Return the resulting type when a vector is shifted 11424 /// by a scalar or vector shift amount. 11425 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 11426 SourceLocation Loc, bool IsCompAssign) { 11427 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 11428 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 11429 !LHS.get()->getType()->isVectorType()) { 11430 S.Diag(Loc, diag::err_shift_rhs_only_vector) 11431 << RHS.get()->getType() << LHS.get()->getType() 11432 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11433 return QualType(); 11434 } 11435 11436 if (!IsCompAssign) { 11437 LHS = S.UsualUnaryConversions(LHS.get()); 11438 if (LHS.isInvalid()) return QualType(); 11439 } 11440 11441 RHS = S.UsualUnaryConversions(RHS.get()); 11442 if (RHS.isInvalid()) return QualType(); 11443 11444 QualType LHSType = LHS.get()->getType(); 11445 // Note that LHS might be a scalar because the routine calls not only in 11446 // OpenCL case. 11447 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 11448 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 11449 11450 // Note that RHS might not be a vector. 11451 QualType RHSType = RHS.get()->getType(); 11452 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 11453 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 11454 11455 // Do not allow shifts for boolean vectors. 11456 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) || 11457 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) { 11458 S.Diag(Loc, diag::err_typecheck_invalid_operands) 11459 << LHS.get()->getType() << RHS.get()->getType() 11460 << LHS.get()->getSourceRange(); 11461 return QualType(); 11462 } 11463 11464 // The operands need to be integers. 11465 if (!LHSEleType->isIntegerType()) { 11466 S.Diag(Loc, diag::err_typecheck_expect_int) 11467 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11468 return QualType(); 11469 } 11470 11471 if (!RHSEleType->isIntegerType()) { 11472 S.Diag(Loc, diag::err_typecheck_expect_int) 11473 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11474 return QualType(); 11475 } 11476 11477 if (!LHSVecTy) { 11478 assert(RHSVecTy); 11479 if (IsCompAssign) 11480 return RHSType; 11481 if (LHSEleType != RHSEleType) { 11482 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 11483 LHSEleType = RHSEleType; 11484 } 11485 QualType VecTy = 11486 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11487 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11488 LHSType = VecTy; 11489 } else if (RHSVecTy) { 11490 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11491 // are applied component-wise. So if RHS is a vector, then ensure 11492 // that the number of elements is the same as LHS... 11493 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11494 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11495 << LHS.get()->getType() << RHS.get()->getType() 11496 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11497 return QualType(); 11498 } 11499 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11500 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11501 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11502 if (LHSBT != RHSBT && 11503 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11504 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11505 << LHS.get()->getType() << RHS.get()->getType() 11506 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11507 } 11508 } 11509 } else { 11510 // ...else expand RHS to match the number of elements in LHS. 11511 QualType VecTy = 11512 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11513 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11514 } 11515 11516 return LHSType; 11517 } 11518 11519 static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, 11520 ExprResult &RHS, SourceLocation Loc, 11521 bool IsCompAssign) { 11522 if (!IsCompAssign) { 11523 LHS = S.UsualUnaryConversions(LHS.get()); 11524 if (LHS.isInvalid()) 11525 return QualType(); 11526 } 11527 11528 RHS = S.UsualUnaryConversions(RHS.get()); 11529 if (RHS.isInvalid()) 11530 return QualType(); 11531 11532 QualType LHSType = LHS.get()->getType(); 11533 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); 11534 QualType LHSEleType = LHSType->isVLSTBuiltinType() 11535 ? LHSBuiltinTy->getSveEltType(S.getASTContext()) 11536 : LHSType; 11537 11538 // Note that RHS might not be a vector 11539 QualType RHSType = RHS.get()->getType(); 11540 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>(); 11541 QualType RHSEleType = RHSType->isVLSTBuiltinType() 11542 ? RHSBuiltinTy->getSveEltType(S.getASTContext()) 11543 : RHSType; 11544 11545 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) || 11546 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) { 11547 S.Diag(Loc, diag::err_typecheck_invalid_operands) 11548 << LHSType << RHSType << LHS.get()->getSourceRange(); 11549 return QualType(); 11550 } 11551 11552 if (!LHSEleType->isIntegerType()) { 11553 S.Diag(Loc, diag::err_typecheck_expect_int) 11554 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11555 return QualType(); 11556 } 11557 11558 if (!RHSEleType->isIntegerType()) { 11559 S.Diag(Loc, diag::err_typecheck_expect_int) 11560 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11561 return QualType(); 11562 } 11563 11564 if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() && 11565 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC != 11566 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) { 11567 S.Diag(Loc, diag::err_typecheck_invalid_operands) 11568 << LHSType << RHSType << LHS.get()->getSourceRange() 11569 << RHS.get()->getSourceRange(); 11570 return QualType(); 11571 } 11572 11573 if (!LHSType->isVLSTBuiltinType()) { 11574 assert(RHSType->isVLSTBuiltinType()); 11575 if (IsCompAssign) 11576 return RHSType; 11577 if (LHSEleType != RHSEleType) { 11578 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast); 11579 LHSEleType = RHSEleType; 11580 } 11581 const llvm::ElementCount VecSize = 11582 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC; 11583 QualType VecTy = 11584 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue()); 11585 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat); 11586 LHSType = VecTy; 11587 } else if (RHSBuiltinTy && RHSBuiltinTy->isVLSTBuiltinType()) { 11588 if (S.Context.getTypeSize(RHSBuiltinTy) != 11589 S.Context.getTypeSize(LHSBuiltinTy)) { 11590 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11591 << LHSType << RHSType << LHS.get()->getSourceRange() 11592 << RHS.get()->getSourceRange(); 11593 return QualType(); 11594 } 11595 } else { 11596 const llvm::ElementCount VecSize = 11597 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC; 11598 if (LHSEleType != RHSEleType) { 11599 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast); 11600 RHSEleType = LHSEleType; 11601 } 11602 QualType VecTy = 11603 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue()); 11604 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11605 } 11606 11607 return LHSType; 11608 } 11609 11610 // C99 6.5.7 11611 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11612 SourceLocation Loc, BinaryOperatorKind Opc, 11613 bool IsCompAssign) { 11614 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11615 11616 // Vector shifts promote their scalar inputs to vector type. 11617 if (LHS.get()->getType()->isVectorType() || 11618 RHS.get()->getType()->isVectorType()) { 11619 if (LangOpts.ZVector) { 11620 // The shift operators for the z vector extensions work basically 11621 // like general shifts, except that neither the LHS nor the RHS is 11622 // allowed to be a "vector bool". 11623 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11624 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11625 return InvalidOperands(Loc, LHS, RHS); 11626 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11627 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11628 return InvalidOperands(Loc, LHS, RHS); 11629 } 11630 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11631 } 11632 11633 if (LHS.get()->getType()->isVLSTBuiltinType() || 11634 RHS.get()->getType()->isVLSTBuiltinType()) 11635 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11636 11637 // Shifts don't perform usual arithmetic conversions, they just do integer 11638 // promotions on each operand. C99 6.5.7p3 11639 11640 // For the LHS, do usual unary conversions, but then reset them away 11641 // if this is a compound assignment. 11642 ExprResult OldLHS = LHS; 11643 LHS = UsualUnaryConversions(LHS.get()); 11644 if (LHS.isInvalid()) 11645 return QualType(); 11646 QualType LHSType = LHS.get()->getType(); 11647 if (IsCompAssign) LHS = OldLHS; 11648 11649 // The RHS is simpler. 11650 RHS = UsualUnaryConversions(RHS.get()); 11651 if (RHS.isInvalid()) 11652 return QualType(); 11653 QualType RHSType = RHS.get()->getType(); 11654 11655 // C99 6.5.7p2: Each of the operands shall have integer type. 11656 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11657 if ((!LHSType->isFixedPointOrIntegerType() && 11658 !LHSType->hasIntegerRepresentation()) || 11659 !RHSType->hasIntegerRepresentation()) 11660 return InvalidOperands(Loc, LHS, RHS); 11661 11662 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11663 // hasIntegerRepresentation() above instead of this. 11664 if (isScopedEnumerationType(LHSType) || 11665 isScopedEnumerationType(RHSType)) { 11666 return InvalidOperands(Loc, LHS, RHS); 11667 } 11668 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11669 11670 // "The type of the result is that of the promoted left operand." 11671 return LHSType; 11672 } 11673 11674 /// Diagnose bad pointer comparisons. 11675 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11676 ExprResult &LHS, ExprResult &RHS, 11677 bool IsError) { 11678 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11679 : diag::ext_typecheck_comparison_of_distinct_pointers) 11680 << LHS.get()->getType() << RHS.get()->getType() 11681 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11682 } 11683 11684 /// Returns false if the pointers are converted to a composite type, 11685 /// true otherwise. 11686 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11687 ExprResult &LHS, ExprResult &RHS) { 11688 // C++ [expr.rel]p2: 11689 // [...] Pointer conversions (4.10) and qualification 11690 // conversions (4.4) are performed on pointer operands (or on 11691 // a pointer operand and a null pointer constant) to bring 11692 // them to their composite pointer type. [...] 11693 // 11694 // C++ [expr.eq]p1 uses the same notion for (in)equality 11695 // comparisons of pointers. 11696 11697 QualType LHSType = LHS.get()->getType(); 11698 QualType RHSType = RHS.get()->getType(); 11699 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11700 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11701 11702 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11703 if (T.isNull()) { 11704 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11705 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11706 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11707 else 11708 S.InvalidOperands(Loc, LHS, RHS); 11709 return true; 11710 } 11711 11712 return false; 11713 } 11714 11715 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11716 ExprResult &LHS, 11717 ExprResult &RHS, 11718 bool IsError) { 11719 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11720 : diag::ext_typecheck_comparison_of_fptr_to_void) 11721 << LHS.get()->getType() << RHS.get()->getType() 11722 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11723 } 11724 11725 static bool isObjCObjectLiteral(ExprResult &E) { 11726 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11727 case Stmt::ObjCArrayLiteralClass: 11728 case Stmt::ObjCDictionaryLiteralClass: 11729 case Stmt::ObjCStringLiteralClass: 11730 case Stmt::ObjCBoxedExprClass: 11731 return true; 11732 default: 11733 // Note that ObjCBoolLiteral is NOT an object literal! 11734 return false; 11735 } 11736 } 11737 11738 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11739 const ObjCObjectPointerType *Type = 11740 LHS->getType()->getAs<ObjCObjectPointerType>(); 11741 11742 // If this is not actually an Objective-C object, bail out. 11743 if (!Type) 11744 return false; 11745 11746 // Get the LHS object's interface type. 11747 QualType InterfaceType = Type->getPointeeType(); 11748 11749 // If the RHS isn't an Objective-C object, bail out. 11750 if (!RHS->getType()->isObjCObjectPointerType()) 11751 return false; 11752 11753 // Try to find the -isEqual: method. 11754 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11755 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11756 InterfaceType, 11757 /*IsInstance=*/true); 11758 if (!Method) { 11759 if (Type->isObjCIdType()) { 11760 // For 'id', just check the global pool. 11761 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11762 /*receiverId=*/true); 11763 } else { 11764 // Check protocols. 11765 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11766 /*IsInstance=*/true); 11767 } 11768 } 11769 11770 if (!Method) 11771 return false; 11772 11773 QualType T = Method->parameters()[0]->getType(); 11774 if (!T->isObjCObjectPointerType()) 11775 return false; 11776 11777 QualType R = Method->getReturnType(); 11778 if (!R->isScalarType()) 11779 return false; 11780 11781 return true; 11782 } 11783 11784 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11785 FromE = FromE->IgnoreParenImpCasts(); 11786 switch (FromE->getStmtClass()) { 11787 default: 11788 break; 11789 case Stmt::ObjCStringLiteralClass: 11790 // "string literal" 11791 return LK_String; 11792 case Stmt::ObjCArrayLiteralClass: 11793 // "array literal" 11794 return LK_Array; 11795 case Stmt::ObjCDictionaryLiteralClass: 11796 // "dictionary literal" 11797 return LK_Dictionary; 11798 case Stmt::BlockExprClass: 11799 return LK_Block; 11800 case Stmt::ObjCBoxedExprClass: { 11801 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11802 switch (Inner->getStmtClass()) { 11803 case Stmt::IntegerLiteralClass: 11804 case Stmt::FloatingLiteralClass: 11805 case Stmt::CharacterLiteralClass: 11806 case Stmt::ObjCBoolLiteralExprClass: 11807 case Stmt::CXXBoolLiteralExprClass: 11808 // "numeric literal" 11809 return LK_Numeric; 11810 case Stmt::ImplicitCastExprClass: { 11811 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11812 // Boolean literals can be represented by implicit casts. 11813 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11814 return LK_Numeric; 11815 break; 11816 } 11817 default: 11818 break; 11819 } 11820 return LK_Boxed; 11821 } 11822 } 11823 return LK_None; 11824 } 11825 11826 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11827 ExprResult &LHS, ExprResult &RHS, 11828 BinaryOperator::Opcode Opc){ 11829 Expr *Literal; 11830 Expr *Other; 11831 if (isObjCObjectLiteral(LHS)) { 11832 Literal = LHS.get(); 11833 Other = RHS.get(); 11834 } else { 11835 Literal = RHS.get(); 11836 Other = LHS.get(); 11837 } 11838 11839 // Don't warn on comparisons against nil. 11840 Other = Other->IgnoreParenCasts(); 11841 if (Other->isNullPointerConstant(S.getASTContext(), 11842 Expr::NPC_ValueDependentIsNotNull)) 11843 return; 11844 11845 // This should be kept in sync with warn_objc_literal_comparison. 11846 // LK_String should always be after the other literals, since it has its own 11847 // warning flag. 11848 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11849 assert(LiteralKind != Sema::LK_Block); 11850 if (LiteralKind == Sema::LK_None) { 11851 llvm_unreachable("Unknown Objective-C object literal kind"); 11852 } 11853 11854 if (LiteralKind == Sema::LK_String) 11855 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11856 << Literal->getSourceRange(); 11857 else 11858 S.Diag(Loc, diag::warn_objc_literal_comparison) 11859 << LiteralKind << Literal->getSourceRange(); 11860 11861 if (BinaryOperator::isEqualityOp(Opc) && 11862 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11863 SourceLocation Start = LHS.get()->getBeginLoc(); 11864 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11865 CharSourceRange OpRange = 11866 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11867 11868 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11869 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11870 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11871 << FixItHint::CreateInsertion(End, "]"); 11872 } 11873 } 11874 11875 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11876 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11877 ExprResult &RHS, SourceLocation Loc, 11878 BinaryOperatorKind Opc) { 11879 // Check that left hand side is !something. 11880 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11881 if (!UO || UO->getOpcode() != UO_LNot) return; 11882 11883 // Only check if the right hand side is non-bool arithmetic type. 11884 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11885 11886 // Make sure that the something in !something is not bool. 11887 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11888 if (SubExpr->isKnownToHaveBooleanValue()) return; 11889 11890 // Emit warning. 11891 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11892 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11893 << Loc << IsBitwiseOp; 11894 11895 // First note suggest !(x < y) 11896 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11897 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11898 FirstClose = S.getLocForEndOfToken(FirstClose); 11899 if (FirstClose.isInvalid()) 11900 FirstOpen = SourceLocation(); 11901 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11902 << IsBitwiseOp 11903 << FixItHint::CreateInsertion(FirstOpen, "(") 11904 << FixItHint::CreateInsertion(FirstClose, ")"); 11905 11906 // Second note suggests (!x) < y 11907 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11908 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11909 SecondClose = S.getLocForEndOfToken(SecondClose); 11910 if (SecondClose.isInvalid()) 11911 SecondOpen = SourceLocation(); 11912 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11913 << FixItHint::CreateInsertion(SecondOpen, "(") 11914 << FixItHint::CreateInsertion(SecondClose, ")"); 11915 } 11916 11917 // Returns true if E refers to a non-weak array. 11918 static bool checkForArray(const Expr *E) { 11919 const ValueDecl *D = nullptr; 11920 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11921 D = DR->getDecl(); 11922 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11923 if (Mem->isImplicitAccess()) 11924 D = Mem->getMemberDecl(); 11925 } 11926 if (!D) 11927 return false; 11928 return D->getType()->isArrayType() && !D->isWeak(); 11929 } 11930 11931 /// Diagnose some forms of syntactically-obvious tautological comparison. 11932 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11933 Expr *LHS, Expr *RHS, 11934 BinaryOperatorKind Opc) { 11935 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11936 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11937 11938 QualType LHSType = LHS->getType(); 11939 QualType RHSType = RHS->getType(); 11940 if (LHSType->hasFloatingRepresentation() || 11941 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11942 S.inTemplateInstantiation()) 11943 return; 11944 11945 // Comparisons between two array types are ill-formed for operator<=>, so 11946 // we shouldn't emit any additional warnings about it. 11947 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11948 return; 11949 11950 // For non-floating point types, check for self-comparisons of the form 11951 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11952 // often indicate logic errors in the program. 11953 // 11954 // NOTE: Don't warn about comparison expressions resulting from macro 11955 // expansion. Also don't warn about comparisons which are only self 11956 // comparisons within a template instantiation. The warnings should catch 11957 // obvious cases in the definition of the template anyways. The idea is to 11958 // warn when the typed comparison operator will always evaluate to the same 11959 // result. 11960 11961 // Used for indexing into %select in warn_comparison_always 11962 enum { 11963 AlwaysConstant, 11964 AlwaysTrue, 11965 AlwaysFalse, 11966 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11967 }; 11968 11969 // C++2a [depr.array.comp]: 11970 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11971 // operands of array type are deprecated. 11972 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11973 RHSStripped->getType()->isArrayType()) { 11974 S.Diag(Loc, diag::warn_depr_array_comparison) 11975 << LHS->getSourceRange() << RHS->getSourceRange() 11976 << LHSStripped->getType() << RHSStripped->getType(); 11977 // Carry on to produce the tautological comparison warning, if this 11978 // expression is potentially-evaluated, we can resolve the array to a 11979 // non-weak declaration, and so on. 11980 } 11981 11982 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11983 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11984 unsigned Result; 11985 switch (Opc) { 11986 case BO_EQ: 11987 case BO_LE: 11988 case BO_GE: 11989 Result = AlwaysTrue; 11990 break; 11991 case BO_NE: 11992 case BO_LT: 11993 case BO_GT: 11994 Result = AlwaysFalse; 11995 break; 11996 case BO_Cmp: 11997 Result = AlwaysEqual; 11998 break; 11999 default: 12000 Result = AlwaysConstant; 12001 break; 12002 } 12003 S.DiagRuntimeBehavior(Loc, nullptr, 12004 S.PDiag(diag::warn_comparison_always) 12005 << 0 /*self-comparison*/ 12006 << Result); 12007 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 12008 // What is it always going to evaluate to? 12009 unsigned Result; 12010 switch (Opc) { 12011 case BO_EQ: // e.g. array1 == array2 12012 Result = AlwaysFalse; 12013 break; 12014 case BO_NE: // e.g. array1 != array2 12015 Result = AlwaysTrue; 12016 break; 12017 default: // e.g. array1 <= array2 12018 // The best we can say is 'a constant' 12019 Result = AlwaysConstant; 12020 break; 12021 } 12022 S.DiagRuntimeBehavior(Loc, nullptr, 12023 S.PDiag(diag::warn_comparison_always) 12024 << 1 /*array comparison*/ 12025 << Result); 12026 } 12027 } 12028 12029 if (isa<CastExpr>(LHSStripped)) 12030 LHSStripped = LHSStripped->IgnoreParenCasts(); 12031 if (isa<CastExpr>(RHSStripped)) 12032 RHSStripped = RHSStripped->IgnoreParenCasts(); 12033 12034 // Warn about comparisons against a string constant (unless the other 12035 // operand is null); the user probably wants string comparison function. 12036 Expr *LiteralString = nullptr; 12037 Expr *LiteralStringStripped = nullptr; 12038 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 12039 !RHSStripped->isNullPointerConstant(S.Context, 12040 Expr::NPC_ValueDependentIsNull)) { 12041 LiteralString = LHS; 12042 LiteralStringStripped = LHSStripped; 12043 } else if ((isa<StringLiteral>(RHSStripped) || 12044 isa<ObjCEncodeExpr>(RHSStripped)) && 12045 !LHSStripped->isNullPointerConstant(S.Context, 12046 Expr::NPC_ValueDependentIsNull)) { 12047 LiteralString = RHS; 12048 LiteralStringStripped = RHSStripped; 12049 } 12050 12051 if (LiteralString) { 12052 S.DiagRuntimeBehavior(Loc, nullptr, 12053 S.PDiag(diag::warn_stringcompare) 12054 << isa<ObjCEncodeExpr>(LiteralStringStripped) 12055 << LiteralString->getSourceRange()); 12056 } 12057 } 12058 12059 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 12060 switch (CK) { 12061 default: { 12062 #ifndef NDEBUG 12063 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 12064 << "\n"; 12065 #endif 12066 llvm_unreachable("unhandled cast kind"); 12067 } 12068 case CK_UserDefinedConversion: 12069 return ICK_Identity; 12070 case CK_LValueToRValue: 12071 return ICK_Lvalue_To_Rvalue; 12072 case CK_ArrayToPointerDecay: 12073 return ICK_Array_To_Pointer; 12074 case CK_FunctionToPointerDecay: 12075 return ICK_Function_To_Pointer; 12076 case CK_IntegralCast: 12077 return ICK_Integral_Conversion; 12078 case CK_FloatingCast: 12079 return ICK_Floating_Conversion; 12080 case CK_IntegralToFloating: 12081 case CK_FloatingToIntegral: 12082 return ICK_Floating_Integral; 12083 case CK_IntegralComplexCast: 12084 case CK_FloatingComplexCast: 12085 case CK_FloatingComplexToIntegralComplex: 12086 case CK_IntegralComplexToFloatingComplex: 12087 return ICK_Complex_Conversion; 12088 case CK_FloatingComplexToReal: 12089 case CK_FloatingRealToComplex: 12090 case CK_IntegralComplexToReal: 12091 case CK_IntegralRealToComplex: 12092 return ICK_Complex_Real; 12093 } 12094 } 12095 12096 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 12097 QualType FromType, 12098 SourceLocation Loc) { 12099 // Check for a narrowing implicit conversion. 12100 StandardConversionSequence SCS; 12101 SCS.setAsIdentityConversion(); 12102 SCS.setToType(0, FromType); 12103 SCS.setToType(1, ToType); 12104 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 12105 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 12106 12107 APValue PreNarrowingValue; 12108 QualType PreNarrowingType; 12109 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 12110 PreNarrowingType, 12111 /*IgnoreFloatToIntegralConversion*/ true)) { 12112 case NK_Dependent_Narrowing: 12113 // Implicit conversion to a narrower type, but the expression is 12114 // value-dependent so we can't tell whether it's actually narrowing. 12115 case NK_Not_Narrowing: 12116 return false; 12117 12118 case NK_Constant_Narrowing: 12119 // Implicit conversion to a narrower type, and the value is not a constant 12120 // expression. 12121 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 12122 << /*Constant*/ 1 12123 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 12124 return true; 12125 12126 case NK_Variable_Narrowing: 12127 // Implicit conversion to a narrower type, and the value is not a constant 12128 // expression. 12129 case NK_Type_Narrowing: 12130 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 12131 << /*Constant*/ 0 << FromType << ToType; 12132 // TODO: It's not a constant expression, but what if the user intended it 12133 // to be? Can we produce notes to help them figure out why it isn't? 12134 return true; 12135 } 12136 llvm_unreachable("unhandled case in switch"); 12137 } 12138 12139 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 12140 ExprResult &LHS, 12141 ExprResult &RHS, 12142 SourceLocation Loc) { 12143 QualType LHSType = LHS.get()->getType(); 12144 QualType RHSType = RHS.get()->getType(); 12145 // Dig out the original argument type and expression before implicit casts 12146 // were applied. These are the types/expressions we need to check the 12147 // [expr.spaceship] requirements against. 12148 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 12149 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 12150 QualType LHSStrippedType = LHSStripped.get()->getType(); 12151 QualType RHSStrippedType = RHSStripped.get()->getType(); 12152 12153 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 12154 // other is not, the program is ill-formed. 12155 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 12156 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 12157 return QualType(); 12158 } 12159 12160 // FIXME: Consider combining this with checkEnumArithmeticConversions. 12161 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 12162 RHSStrippedType->isEnumeralType(); 12163 if (NumEnumArgs == 1) { 12164 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 12165 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 12166 if (OtherTy->hasFloatingRepresentation()) { 12167 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 12168 return QualType(); 12169 } 12170 } 12171 if (NumEnumArgs == 2) { 12172 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 12173 // type E, the operator yields the result of converting the operands 12174 // to the underlying type of E and applying <=> to the converted operands. 12175 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 12176 S.InvalidOperands(Loc, LHS, RHS); 12177 return QualType(); 12178 } 12179 QualType IntType = 12180 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 12181 assert(IntType->isArithmeticType()); 12182 12183 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 12184 // promote the boolean type, and all other promotable integer types, to 12185 // avoid this. 12186 if (IntType->isPromotableIntegerType()) 12187 IntType = S.Context.getPromotedIntegerType(IntType); 12188 12189 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 12190 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 12191 LHSType = RHSType = IntType; 12192 } 12193 12194 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 12195 // usual arithmetic conversions are applied to the operands. 12196 QualType Type = 12197 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 12198 if (LHS.isInvalid() || RHS.isInvalid()) 12199 return QualType(); 12200 if (Type.isNull()) 12201 return S.InvalidOperands(Loc, LHS, RHS); 12202 12203 Optional<ComparisonCategoryType> CCT = 12204 getComparisonCategoryForBuiltinCmp(Type); 12205 if (!CCT) 12206 return S.InvalidOperands(Loc, LHS, RHS); 12207 12208 bool HasNarrowing = checkThreeWayNarrowingConversion( 12209 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 12210 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 12211 RHS.get()->getBeginLoc()); 12212 if (HasNarrowing) 12213 return QualType(); 12214 12215 assert(!Type.isNull() && "composite type for <=> has not been set"); 12216 12217 return S.CheckComparisonCategoryType( 12218 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 12219 } 12220 12221 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 12222 ExprResult &RHS, 12223 SourceLocation Loc, 12224 BinaryOperatorKind Opc) { 12225 if (Opc == BO_Cmp) 12226 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 12227 12228 // C99 6.5.8p3 / C99 6.5.9p4 12229 QualType Type = 12230 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 12231 if (LHS.isInvalid() || RHS.isInvalid()) 12232 return QualType(); 12233 if (Type.isNull()) 12234 return S.InvalidOperands(Loc, LHS, RHS); 12235 assert(Type->isArithmeticType() || Type->isEnumeralType()); 12236 12237 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 12238 return S.InvalidOperands(Loc, LHS, RHS); 12239 12240 // Check for comparisons of floating point operands using != and ==. 12241 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 12242 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); 12243 12244 // The result of comparisons is 'bool' in C++, 'int' in C. 12245 return S.Context.getLogicalOperationType(); 12246 } 12247 12248 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 12249 if (!NullE.get()->getType()->isAnyPointerType()) 12250 return; 12251 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 12252 if (!E.get()->getType()->isAnyPointerType() && 12253 E.get()->isNullPointerConstant(Context, 12254 Expr::NPC_ValueDependentIsNotNull) == 12255 Expr::NPCK_ZeroExpression) { 12256 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 12257 if (CL->getValue() == 0) 12258 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 12259 << NullValue 12260 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 12261 NullValue ? "NULL" : "(void *)0"); 12262 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 12263 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 12264 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 12265 if (T == Context.CharTy) 12266 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 12267 << NullValue 12268 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 12269 NullValue ? "NULL" : "(void *)0"); 12270 } 12271 } 12272 } 12273 12274 // C99 6.5.8, C++ [expr.rel] 12275 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 12276 SourceLocation Loc, 12277 BinaryOperatorKind Opc) { 12278 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 12279 bool IsThreeWay = Opc == BO_Cmp; 12280 bool IsOrdered = IsRelational || IsThreeWay; 12281 auto IsAnyPointerType = [](ExprResult E) { 12282 QualType Ty = E.get()->getType(); 12283 return Ty->isPointerType() || Ty->isMemberPointerType(); 12284 }; 12285 12286 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 12287 // type, array-to-pointer, ..., conversions are performed on both operands to 12288 // bring them to their composite type. 12289 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 12290 // any type-related checks. 12291 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 12292 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12293 if (LHS.isInvalid()) 12294 return QualType(); 12295 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12296 if (RHS.isInvalid()) 12297 return QualType(); 12298 } else { 12299 LHS = DefaultLvalueConversion(LHS.get()); 12300 if (LHS.isInvalid()) 12301 return QualType(); 12302 RHS = DefaultLvalueConversion(RHS.get()); 12303 if (RHS.isInvalid()) 12304 return QualType(); 12305 } 12306 12307 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 12308 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 12309 CheckPtrComparisonWithNullChar(LHS, RHS); 12310 CheckPtrComparisonWithNullChar(RHS, LHS); 12311 } 12312 12313 // Handle vector comparisons separately. 12314 if (LHS.get()->getType()->isVectorType() || 12315 RHS.get()->getType()->isVectorType()) 12316 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 12317 12318 if (LHS.get()->getType()->isVLSTBuiltinType() || 12319 RHS.get()->getType()->isVLSTBuiltinType()) 12320 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc); 12321 12322 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12323 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12324 12325 QualType LHSType = LHS.get()->getType(); 12326 QualType RHSType = RHS.get()->getType(); 12327 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 12328 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 12329 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 12330 12331 const Expr::NullPointerConstantKind LHSNullKind = 12332 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 12333 const Expr::NullPointerConstantKind RHSNullKind = 12334 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 12335 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 12336 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 12337 12338 auto computeResultTy = [&]() { 12339 if (Opc != BO_Cmp) 12340 return Context.getLogicalOperationType(); 12341 assert(getLangOpts().CPlusPlus); 12342 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 12343 12344 QualType CompositeTy = LHS.get()->getType(); 12345 assert(!CompositeTy->isReferenceType()); 12346 12347 Optional<ComparisonCategoryType> CCT = 12348 getComparisonCategoryForBuiltinCmp(CompositeTy); 12349 if (!CCT) 12350 return InvalidOperands(Loc, LHS, RHS); 12351 12352 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 12353 // P0946R0: Comparisons between a null pointer constant and an object 12354 // pointer result in std::strong_equality, which is ill-formed under 12355 // P1959R0. 12356 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 12357 << (LHSIsNull ? LHS.get()->getSourceRange() 12358 : RHS.get()->getSourceRange()); 12359 return QualType(); 12360 } 12361 12362 return CheckComparisonCategoryType( 12363 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 12364 }; 12365 12366 if (!IsOrdered && LHSIsNull != RHSIsNull) { 12367 bool IsEquality = Opc == BO_EQ; 12368 if (RHSIsNull) 12369 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 12370 RHS.get()->getSourceRange()); 12371 else 12372 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 12373 LHS.get()->getSourceRange()); 12374 } 12375 12376 if (IsOrdered && LHSType->isFunctionPointerType() && 12377 RHSType->isFunctionPointerType()) { 12378 // Valid unless a relational comparison of function pointers 12379 bool IsError = Opc == BO_Cmp; 12380 auto DiagID = 12381 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 12382 : getLangOpts().CPlusPlus 12383 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 12384 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 12385 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 12386 << RHS.get()->getSourceRange(); 12387 if (IsError) 12388 return QualType(); 12389 } 12390 12391 if ((LHSType->isIntegerType() && !LHSIsNull) || 12392 (RHSType->isIntegerType() && !RHSIsNull)) { 12393 // Skip normal pointer conversion checks in this case; we have better 12394 // diagnostics for this below. 12395 } else if (getLangOpts().CPlusPlus) { 12396 // Equality comparison of a function pointer to a void pointer is invalid, 12397 // but we allow it as an extension. 12398 // FIXME: If we really want to allow this, should it be part of composite 12399 // pointer type computation so it works in conditionals too? 12400 if (!IsOrdered && 12401 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 12402 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 12403 // This is a gcc extension compatibility comparison. 12404 // In a SFINAE context, we treat this as a hard error to maintain 12405 // conformance with the C++ standard. 12406 diagnoseFunctionPointerToVoidComparison( 12407 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 12408 12409 if (isSFINAEContext()) 12410 return QualType(); 12411 12412 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12413 return computeResultTy(); 12414 } 12415 12416 // C++ [expr.eq]p2: 12417 // If at least one operand is a pointer [...] bring them to their 12418 // composite pointer type. 12419 // C++ [expr.spaceship]p6 12420 // If at least one of the operands is of pointer type, [...] bring them 12421 // to their composite pointer type. 12422 // C++ [expr.rel]p2: 12423 // If both operands are pointers, [...] bring them to their composite 12424 // pointer type. 12425 // For <=>, the only valid non-pointer types are arrays and functions, and 12426 // we already decayed those, so this is really the same as the relational 12427 // comparison rule. 12428 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 12429 (IsOrdered ? 2 : 1) && 12430 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 12431 RHSType->isObjCObjectPointerType()))) { 12432 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12433 return QualType(); 12434 return computeResultTy(); 12435 } 12436 } else if (LHSType->isPointerType() && 12437 RHSType->isPointerType()) { // C99 6.5.8p2 12438 // All of the following pointer-related warnings are GCC extensions, except 12439 // when handling null pointer constants. 12440 QualType LCanPointeeTy = 12441 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 12442 QualType RCanPointeeTy = 12443 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 12444 12445 // C99 6.5.9p2 and C99 6.5.8p2 12446 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 12447 RCanPointeeTy.getUnqualifiedType())) { 12448 if (IsRelational) { 12449 // Pointers both need to point to complete or incomplete types 12450 if ((LCanPointeeTy->isIncompleteType() != 12451 RCanPointeeTy->isIncompleteType()) && 12452 !getLangOpts().C11) { 12453 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 12454 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 12455 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 12456 << RCanPointeeTy->isIncompleteType(); 12457 } 12458 } 12459 } else if (!IsRelational && 12460 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 12461 // Valid unless comparison between non-null pointer and function pointer 12462 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 12463 && !LHSIsNull && !RHSIsNull) 12464 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 12465 /*isError*/false); 12466 } else { 12467 // Invalid 12468 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 12469 } 12470 if (LCanPointeeTy != RCanPointeeTy) { 12471 // Treat NULL constant as a special case in OpenCL. 12472 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 12473 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 12474 Diag(Loc, 12475 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 12476 << LHSType << RHSType << 0 /* comparison */ 12477 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 12478 } 12479 } 12480 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 12481 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 12482 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 12483 : CK_BitCast; 12484 if (LHSIsNull && !RHSIsNull) 12485 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 12486 else 12487 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 12488 } 12489 return computeResultTy(); 12490 } 12491 12492 if (getLangOpts().CPlusPlus) { 12493 // C++ [expr.eq]p4: 12494 // Two operands of type std::nullptr_t or one operand of type 12495 // std::nullptr_t and the other a null pointer constant compare equal. 12496 if (!IsOrdered && LHSIsNull && RHSIsNull) { 12497 if (LHSType->isNullPtrType()) { 12498 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12499 return computeResultTy(); 12500 } 12501 if (RHSType->isNullPtrType()) { 12502 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12503 return computeResultTy(); 12504 } 12505 } 12506 12507 // Comparison of Objective-C pointers and block pointers against nullptr_t. 12508 // These aren't covered by the composite pointer type rules. 12509 if (!IsOrdered && RHSType->isNullPtrType() && 12510 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 12511 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12512 return computeResultTy(); 12513 } 12514 if (!IsOrdered && LHSType->isNullPtrType() && 12515 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 12516 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12517 return computeResultTy(); 12518 } 12519 12520 if (IsRelational && 12521 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 12522 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 12523 // HACK: Relational comparison of nullptr_t against a pointer type is 12524 // invalid per DR583, but we allow it within std::less<> and friends, 12525 // since otherwise common uses of it break. 12526 // FIXME: Consider removing this hack once LWG fixes std::less<> and 12527 // friends to have std::nullptr_t overload candidates. 12528 DeclContext *DC = CurContext; 12529 if (isa<FunctionDecl>(DC)) 12530 DC = DC->getParent(); 12531 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 12532 if (CTSD->isInStdNamespace() && 12533 llvm::StringSwitch<bool>(CTSD->getName()) 12534 .Cases("less", "less_equal", "greater", "greater_equal", true) 12535 .Default(false)) { 12536 if (RHSType->isNullPtrType()) 12537 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12538 else 12539 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12540 return computeResultTy(); 12541 } 12542 } 12543 } 12544 12545 // C++ [expr.eq]p2: 12546 // If at least one operand is a pointer to member, [...] bring them to 12547 // their composite pointer type. 12548 if (!IsOrdered && 12549 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 12550 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12551 return QualType(); 12552 else 12553 return computeResultTy(); 12554 } 12555 } 12556 12557 // Handle block pointer types. 12558 if (!IsOrdered && LHSType->isBlockPointerType() && 12559 RHSType->isBlockPointerType()) { 12560 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 12561 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 12562 12563 if (!LHSIsNull && !RHSIsNull && 12564 !Context.typesAreCompatible(lpointee, rpointee)) { 12565 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12566 << LHSType << RHSType << LHS.get()->getSourceRange() 12567 << RHS.get()->getSourceRange(); 12568 } 12569 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12570 return computeResultTy(); 12571 } 12572 12573 // Allow block pointers to be compared with null pointer constants. 12574 if (!IsOrdered 12575 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 12576 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 12577 if (!LHSIsNull && !RHSIsNull) { 12578 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 12579 ->getPointeeType()->isVoidType()) 12580 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12581 ->getPointeeType()->isVoidType()))) 12582 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12583 << LHSType << RHSType << LHS.get()->getSourceRange() 12584 << RHS.get()->getSourceRange(); 12585 } 12586 if (LHSIsNull && !RHSIsNull) 12587 LHS = ImpCastExprToType(LHS.get(), RHSType, 12588 RHSType->isPointerType() ? CK_BitCast 12589 : CK_AnyPointerToBlockPointerCast); 12590 else 12591 RHS = ImpCastExprToType(RHS.get(), LHSType, 12592 LHSType->isPointerType() ? CK_BitCast 12593 : CK_AnyPointerToBlockPointerCast); 12594 return computeResultTy(); 12595 } 12596 12597 if (LHSType->isObjCObjectPointerType() || 12598 RHSType->isObjCObjectPointerType()) { 12599 const PointerType *LPT = LHSType->getAs<PointerType>(); 12600 const PointerType *RPT = RHSType->getAs<PointerType>(); 12601 if (LPT || RPT) { 12602 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12603 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12604 12605 if (!LPtrToVoid && !RPtrToVoid && 12606 !Context.typesAreCompatible(LHSType, RHSType)) { 12607 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12608 /*isError*/false); 12609 } 12610 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12611 // the RHS, but we have test coverage for this behavior. 12612 // FIXME: Consider using convertPointersToCompositeType in C++. 12613 if (LHSIsNull && !RHSIsNull) { 12614 Expr *E = LHS.get(); 12615 if (getLangOpts().ObjCAutoRefCount) 12616 CheckObjCConversion(SourceRange(), RHSType, E, 12617 CCK_ImplicitConversion); 12618 LHS = ImpCastExprToType(E, RHSType, 12619 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12620 } 12621 else { 12622 Expr *E = RHS.get(); 12623 if (getLangOpts().ObjCAutoRefCount) 12624 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12625 /*Diagnose=*/true, 12626 /*DiagnoseCFAudited=*/false, Opc); 12627 RHS = ImpCastExprToType(E, LHSType, 12628 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12629 } 12630 return computeResultTy(); 12631 } 12632 if (LHSType->isObjCObjectPointerType() && 12633 RHSType->isObjCObjectPointerType()) { 12634 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12635 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12636 /*isError*/false); 12637 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12638 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12639 12640 if (LHSIsNull && !RHSIsNull) 12641 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12642 else 12643 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12644 return computeResultTy(); 12645 } 12646 12647 if (!IsOrdered && LHSType->isBlockPointerType() && 12648 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12649 LHS = ImpCastExprToType(LHS.get(), RHSType, 12650 CK_BlockPointerToObjCPointerCast); 12651 return computeResultTy(); 12652 } else if (!IsOrdered && 12653 LHSType->isBlockCompatibleObjCPointerType(Context) && 12654 RHSType->isBlockPointerType()) { 12655 RHS = ImpCastExprToType(RHS.get(), LHSType, 12656 CK_BlockPointerToObjCPointerCast); 12657 return computeResultTy(); 12658 } 12659 } 12660 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12661 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12662 unsigned DiagID = 0; 12663 bool isError = false; 12664 if (LangOpts.DebuggerSupport) { 12665 // Under a debugger, allow the comparison of pointers to integers, 12666 // since users tend to want to compare addresses. 12667 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12668 (RHSIsNull && RHSType->isIntegerType())) { 12669 if (IsOrdered) { 12670 isError = getLangOpts().CPlusPlus; 12671 DiagID = 12672 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12673 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12674 } 12675 } else if (getLangOpts().CPlusPlus) { 12676 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12677 isError = true; 12678 } else if (IsOrdered) 12679 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12680 else 12681 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12682 12683 if (DiagID) { 12684 Diag(Loc, DiagID) 12685 << LHSType << RHSType << LHS.get()->getSourceRange() 12686 << RHS.get()->getSourceRange(); 12687 if (isError) 12688 return QualType(); 12689 } 12690 12691 if (LHSType->isIntegerType()) 12692 LHS = ImpCastExprToType(LHS.get(), RHSType, 12693 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12694 else 12695 RHS = ImpCastExprToType(RHS.get(), LHSType, 12696 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12697 return computeResultTy(); 12698 } 12699 12700 // Handle block pointers. 12701 if (!IsOrdered && RHSIsNull 12702 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12703 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12704 return computeResultTy(); 12705 } 12706 if (!IsOrdered && LHSIsNull 12707 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12708 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12709 return computeResultTy(); 12710 } 12711 12712 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 12713 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12714 return computeResultTy(); 12715 } 12716 12717 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12718 return computeResultTy(); 12719 } 12720 12721 if (LHSIsNull && RHSType->isQueueT()) { 12722 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12723 return computeResultTy(); 12724 } 12725 12726 if (LHSType->isQueueT() && RHSIsNull) { 12727 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12728 return computeResultTy(); 12729 } 12730 } 12731 12732 return InvalidOperands(Loc, LHS, RHS); 12733 } 12734 12735 // Return a signed ext_vector_type that is of identical size and number of 12736 // elements. For floating point vectors, return an integer type of identical 12737 // size and number of elements. In the non ext_vector_type case, search from 12738 // the largest type to the smallest type to avoid cases where long long == long, 12739 // where long gets picked over long long. 12740 QualType Sema::GetSignedVectorType(QualType V) { 12741 const VectorType *VTy = V->castAs<VectorType>(); 12742 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12743 12744 if (isa<ExtVectorType>(VTy)) { 12745 if (VTy->isExtVectorBoolType()) 12746 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements()); 12747 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12748 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12749 if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12750 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12751 if (TypeSize == Context.getTypeSize(Context.IntTy)) 12752 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12753 if (TypeSize == Context.getTypeSize(Context.Int128Ty)) 12754 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements()); 12755 if (TypeSize == Context.getTypeSize(Context.LongTy)) 12756 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12757 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12758 "Unhandled vector element size in vector compare"); 12759 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12760 } 12761 12762 if (TypeSize == Context.getTypeSize(Context.Int128Ty)) 12763 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(), 12764 VectorType::GenericVector); 12765 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12766 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12767 VectorType::GenericVector); 12768 if (TypeSize == Context.getTypeSize(Context.LongTy)) 12769 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12770 VectorType::GenericVector); 12771 if (TypeSize == Context.getTypeSize(Context.IntTy)) 12772 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12773 VectorType::GenericVector); 12774 if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12775 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12776 VectorType::GenericVector); 12777 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12778 "Unhandled vector element size in vector compare"); 12779 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12780 VectorType::GenericVector); 12781 } 12782 12783 QualType Sema::GetSignedSizelessVectorType(QualType V) { 12784 const BuiltinType *VTy = V->castAs<BuiltinType>(); 12785 assert(VTy->isSizelessBuiltinType() && "expected sizeless type"); 12786 12787 const QualType ETy = V->getSveEltType(Context); 12788 const auto TypeSize = Context.getTypeSize(ETy); 12789 12790 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true); 12791 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC; 12792 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue()); 12793 } 12794 12795 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12796 /// operates on extended vector types. Instead of producing an IntTy result, 12797 /// like a scalar comparison, a vector comparison produces a vector of integer 12798 /// types. 12799 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12800 SourceLocation Loc, 12801 BinaryOperatorKind Opc) { 12802 if (Opc == BO_Cmp) { 12803 Diag(Loc, diag::err_three_way_vector_comparison); 12804 return QualType(); 12805 } 12806 12807 // Check to make sure we're operating on vectors of the same type and width, 12808 // Allowing one side to be a scalar of element type. 12809 QualType vType = 12810 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false, 12811 /*AllowBothBool*/ true, 12812 /*AllowBoolConversions*/ getLangOpts().ZVector, 12813 /*AllowBooleanOperation*/ true, 12814 /*ReportInvalid*/ true); 12815 if (vType.isNull()) 12816 return vType; 12817 12818 QualType LHSType = LHS.get()->getType(); 12819 12820 // Determine the return type of a vector compare. By default clang will return 12821 // a scalar for all vector compares except vector bool and vector pixel. 12822 // With the gcc compiler we will always return a vector type and with the xl 12823 // compiler we will always return a scalar type. This switch allows choosing 12824 // which behavior is prefered. 12825 if (getLangOpts().AltiVec) { 12826 switch (getLangOpts().getAltivecSrcCompat()) { 12827 case LangOptions::AltivecSrcCompatKind::Mixed: 12828 // If AltiVec, the comparison results in a numeric type, i.e. 12829 // bool for C++, int for C 12830 if (vType->castAs<VectorType>()->getVectorKind() == 12831 VectorType::AltiVecVector) 12832 return Context.getLogicalOperationType(); 12833 else 12834 Diag(Loc, diag::warn_deprecated_altivec_src_compat); 12835 break; 12836 case LangOptions::AltivecSrcCompatKind::GCC: 12837 // For GCC we always return the vector type. 12838 break; 12839 case LangOptions::AltivecSrcCompatKind::XL: 12840 return Context.getLogicalOperationType(); 12841 break; 12842 } 12843 } 12844 12845 // For non-floating point types, check for self-comparisons of the form 12846 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12847 // often indicate logic errors in the program. 12848 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12849 12850 // Check for comparisons of floating point operands using != and ==. 12851 if (BinaryOperator::isEqualityOp(Opc) && 12852 LHSType->hasFloatingRepresentation()) { 12853 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12854 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); 12855 } 12856 12857 // Return a signed type for the vector. 12858 return GetSignedVectorType(vType); 12859 } 12860 12861 QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS, 12862 ExprResult &RHS, 12863 SourceLocation Loc, 12864 BinaryOperatorKind Opc) { 12865 if (Opc == BO_Cmp) { 12866 Diag(Loc, diag::err_three_way_vector_comparison); 12867 return QualType(); 12868 } 12869 12870 // Check to make sure we're operating on vectors of the same type and width, 12871 // Allowing one side to be a scalar of element type. 12872 QualType vType = CheckSizelessVectorOperands( 12873 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison); 12874 12875 if (vType.isNull()) 12876 return vType; 12877 12878 QualType LHSType = LHS.get()->getType(); 12879 12880 // For non-floating point types, check for self-comparisons of the form 12881 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12882 // often indicate logic errors in the program. 12883 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12884 12885 // Check for comparisons of floating point operands using != and ==. 12886 if (BinaryOperator::isEqualityOp(Opc) && 12887 LHSType->hasFloatingRepresentation()) { 12888 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12889 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); 12890 } 12891 12892 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); 12893 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>(); 12894 12895 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() && 12896 RHSBuiltinTy->isSVEBool()) 12897 return LHSType; 12898 12899 // Return a signed type for the vector. 12900 return GetSignedSizelessVectorType(vType); 12901 } 12902 12903 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12904 const ExprResult &XorRHS, 12905 const SourceLocation Loc) { 12906 // Do not diagnose macros. 12907 if (Loc.isMacroID()) 12908 return; 12909 12910 // Do not diagnose if both LHS and RHS are macros. 12911 if (XorLHS.get()->getExprLoc().isMacroID() && 12912 XorRHS.get()->getExprLoc().isMacroID()) 12913 return; 12914 12915 bool Negative = false; 12916 bool ExplicitPlus = false; 12917 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12918 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12919 12920 if (!LHSInt) 12921 return; 12922 if (!RHSInt) { 12923 // Check negative literals. 12924 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12925 UnaryOperatorKind Opc = UO->getOpcode(); 12926 if (Opc != UO_Minus && Opc != UO_Plus) 12927 return; 12928 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12929 if (!RHSInt) 12930 return; 12931 Negative = (Opc == UO_Minus); 12932 ExplicitPlus = !Negative; 12933 } else { 12934 return; 12935 } 12936 } 12937 12938 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12939 llvm::APInt RightSideValue = RHSInt->getValue(); 12940 if (LeftSideValue != 2 && LeftSideValue != 10) 12941 return; 12942 12943 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12944 return; 12945 12946 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12947 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12948 llvm::StringRef ExprStr = 12949 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12950 12951 CharSourceRange XorRange = 12952 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12953 llvm::StringRef XorStr = 12954 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12955 // Do not diagnose if xor keyword/macro is used. 12956 if (XorStr == "xor") 12957 return; 12958 12959 std::string LHSStr = std::string(Lexer::getSourceText( 12960 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12961 S.getSourceManager(), S.getLangOpts())); 12962 std::string RHSStr = std::string(Lexer::getSourceText( 12963 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12964 S.getSourceManager(), S.getLangOpts())); 12965 12966 if (Negative) { 12967 RightSideValue = -RightSideValue; 12968 RHSStr = "-" + RHSStr; 12969 } else if (ExplicitPlus) { 12970 RHSStr = "+" + RHSStr; 12971 } 12972 12973 StringRef LHSStrRef = LHSStr; 12974 StringRef RHSStrRef = RHSStr; 12975 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12976 // literals. 12977 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12978 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12979 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12980 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12981 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12982 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12983 LHSStrRef.contains('\'') || RHSStrRef.contains('\'')) 12984 return; 12985 12986 bool SuggestXor = 12987 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12988 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12989 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12990 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12991 std::string SuggestedExpr = "1 << " + RHSStr; 12992 bool Overflow = false; 12993 llvm::APInt One = (LeftSideValue - 1); 12994 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12995 if (Overflow) { 12996 if (RightSideIntValue < 64) 12997 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12998 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 12999 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 13000 else if (RightSideIntValue == 64) 13001 S.Diag(Loc, diag::warn_xor_used_as_pow) 13002 << ExprStr << toString(XorValue, 10, true); 13003 else 13004 return; 13005 } else { 13006 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 13007 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 13008 << toString(PowValue, 10, true) 13009 << FixItHint::CreateReplacement( 13010 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 13011 } 13012 13013 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 13014 << ("0x2 ^ " + RHSStr) << SuggestXor; 13015 } else if (LeftSideValue == 10) { 13016 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 13017 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 13018 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 13019 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 13020 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 13021 << ("0xA ^ " + RHSStr) << SuggestXor; 13022 } 13023 } 13024 13025 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 13026 SourceLocation Loc) { 13027 // Ensure that either both operands are of the same vector type, or 13028 // one operand is of a vector type and the other is of its element type. 13029 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 13030 /*AllowBothBool*/ true, 13031 /*AllowBoolConversions*/ false, 13032 /*AllowBooleanOperation*/ false, 13033 /*ReportInvalid*/ false); 13034 if (vType.isNull()) 13035 return InvalidOperands(Loc, LHS, RHS); 13036 if (getLangOpts().OpenCL && 13037 getLangOpts().getOpenCLCompatibleVersion() < 120 && 13038 vType->hasFloatingRepresentation()) 13039 return InvalidOperands(Loc, LHS, RHS); 13040 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 13041 // usage of the logical operators && and || with vectors in C. This 13042 // check could be notionally dropped. 13043 if (!getLangOpts().CPlusPlus && 13044 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 13045 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 13046 13047 return GetSignedVectorType(LHS.get()->getType()); 13048 } 13049 13050 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 13051 SourceLocation Loc, 13052 bool IsCompAssign) { 13053 if (!IsCompAssign) { 13054 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 13055 if (LHS.isInvalid()) 13056 return QualType(); 13057 } 13058 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 13059 if (RHS.isInvalid()) 13060 return QualType(); 13061 13062 // For conversion purposes, we ignore any qualifiers. 13063 // For example, "const float" and "float" are equivalent. 13064 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 13065 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 13066 13067 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 13068 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 13069 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 13070 13071 if (Context.hasSameType(LHSType, RHSType)) 13072 return LHSType; 13073 13074 // Type conversion may change LHS/RHS. Keep copies to the original results, in 13075 // case we have to return InvalidOperands. 13076 ExprResult OriginalLHS = LHS; 13077 ExprResult OriginalRHS = RHS; 13078 if (LHSMatType && !RHSMatType) { 13079 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 13080 if (!RHS.isInvalid()) 13081 return LHSType; 13082 13083 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 13084 } 13085 13086 if (!LHSMatType && RHSMatType) { 13087 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 13088 if (!LHS.isInvalid()) 13089 return RHSType; 13090 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 13091 } 13092 13093 return InvalidOperands(Loc, LHS, RHS); 13094 } 13095 13096 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 13097 SourceLocation Loc, 13098 bool IsCompAssign) { 13099 if (!IsCompAssign) { 13100 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 13101 if (LHS.isInvalid()) 13102 return QualType(); 13103 } 13104 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 13105 if (RHS.isInvalid()) 13106 return QualType(); 13107 13108 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 13109 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 13110 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 13111 13112 if (LHSMatType && RHSMatType) { 13113 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 13114 return InvalidOperands(Loc, LHS, RHS); 13115 13116 if (!Context.hasSameType(LHSMatType->getElementType(), 13117 RHSMatType->getElementType())) 13118 return InvalidOperands(Loc, LHS, RHS); 13119 13120 return Context.getConstantMatrixType(LHSMatType->getElementType(), 13121 LHSMatType->getNumRows(), 13122 RHSMatType->getNumColumns()); 13123 } 13124 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 13125 } 13126 13127 static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) { 13128 switch (Opc) { 13129 default: 13130 return false; 13131 case BO_And: 13132 case BO_AndAssign: 13133 case BO_Or: 13134 case BO_OrAssign: 13135 case BO_Xor: 13136 case BO_XorAssign: 13137 return true; 13138 } 13139 } 13140 13141 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 13142 SourceLocation Loc, 13143 BinaryOperatorKind Opc) { 13144 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 13145 13146 bool IsCompAssign = 13147 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 13148 13149 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc); 13150 13151 if (LHS.get()->getType()->isVectorType() || 13152 RHS.get()->getType()->isVectorType()) { 13153 if (LHS.get()->getType()->hasIntegerRepresentation() && 13154 RHS.get()->getType()->hasIntegerRepresentation()) 13155 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 13156 /*AllowBothBool*/ true, 13157 /*AllowBoolConversions*/ getLangOpts().ZVector, 13158 /*AllowBooleanOperation*/ LegalBoolVecOperator, 13159 /*ReportInvalid*/ true); 13160 return InvalidOperands(Loc, LHS, RHS); 13161 } 13162 13163 if (LHS.get()->getType()->isVLSTBuiltinType() || 13164 RHS.get()->getType()->isVLSTBuiltinType()) { 13165 if (LHS.get()->getType()->hasIntegerRepresentation() && 13166 RHS.get()->getType()->hasIntegerRepresentation()) 13167 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 13168 ACK_BitwiseOp); 13169 return InvalidOperands(Loc, LHS, RHS); 13170 } 13171 13172 if (LHS.get()->getType()->isVLSTBuiltinType() || 13173 RHS.get()->getType()->isVLSTBuiltinType()) { 13174 if (LHS.get()->getType()->hasIntegerRepresentation() && 13175 RHS.get()->getType()->hasIntegerRepresentation()) 13176 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 13177 ACK_BitwiseOp); 13178 return InvalidOperands(Loc, LHS, RHS); 13179 } 13180 13181 if (Opc == BO_And) 13182 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 13183 13184 if (LHS.get()->getType()->hasFloatingRepresentation() || 13185 RHS.get()->getType()->hasFloatingRepresentation()) 13186 return InvalidOperands(Loc, LHS, RHS); 13187 13188 ExprResult LHSResult = LHS, RHSResult = RHS; 13189 QualType compType = UsualArithmeticConversions( 13190 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 13191 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 13192 return QualType(); 13193 LHS = LHSResult.get(); 13194 RHS = RHSResult.get(); 13195 13196 if (Opc == BO_Xor) 13197 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 13198 13199 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 13200 return compType; 13201 return InvalidOperands(Loc, LHS, RHS); 13202 } 13203 13204 // C99 6.5.[13,14] 13205 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 13206 SourceLocation Loc, 13207 BinaryOperatorKind Opc) { 13208 // Check vector operands differently. 13209 if (LHS.get()->getType()->isVectorType() || 13210 RHS.get()->getType()->isVectorType()) 13211 return CheckVectorLogicalOperands(LHS, RHS, Loc); 13212 13213 bool EnumConstantInBoolContext = false; 13214 for (const ExprResult &HS : {LHS, RHS}) { 13215 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 13216 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 13217 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 13218 EnumConstantInBoolContext = true; 13219 } 13220 } 13221 13222 if (EnumConstantInBoolContext) 13223 Diag(Loc, diag::warn_enum_constant_in_bool_context); 13224 13225 // Diagnose cases where the user write a logical and/or but probably meant a 13226 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 13227 // is a constant. 13228 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 13229 !LHS.get()->getType()->isBooleanType() && 13230 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 13231 // Don't warn in macros or template instantiations. 13232 !Loc.isMacroID() && !inTemplateInstantiation()) { 13233 // If the RHS can be constant folded, and if it constant folds to something 13234 // that isn't 0 or 1 (which indicate a potential logical operation that 13235 // happened to fold to true/false) then warn. 13236 // Parens on the RHS are ignored. 13237 Expr::EvalResult EVResult; 13238 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 13239 llvm::APSInt Result = EVResult.Val.getInt(); 13240 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 13241 !RHS.get()->getExprLoc().isMacroID()) || 13242 (Result != 0 && Result != 1)) { 13243 Diag(Loc, diag::warn_logical_instead_of_bitwise) 13244 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||"); 13245 // Suggest replacing the logical operator with the bitwise version 13246 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 13247 << (Opc == BO_LAnd ? "&" : "|") 13248 << FixItHint::CreateReplacement( 13249 SourceRange(Loc, getLocForEndOfToken(Loc)), 13250 Opc == BO_LAnd ? "&" : "|"); 13251 if (Opc == BO_LAnd) 13252 // Suggest replacing "Foo() && kNonZero" with "Foo()" 13253 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 13254 << FixItHint::CreateRemoval( 13255 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 13256 RHS.get()->getEndLoc())); 13257 } 13258 } 13259 } 13260 13261 if (!Context.getLangOpts().CPlusPlus) { 13262 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 13263 // not operate on the built-in scalar and vector float types. 13264 if (Context.getLangOpts().OpenCL && 13265 Context.getLangOpts().OpenCLVersion < 120) { 13266 if (LHS.get()->getType()->isFloatingType() || 13267 RHS.get()->getType()->isFloatingType()) 13268 return InvalidOperands(Loc, LHS, RHS); 13269 } 13270 13271 LHS = UsualUnaryConversions(LHS.get()); 13272 if (LHS.isInvalid()) 13273 return QualType(); 13274 13275 RHS = UsualUnaryConversions(RHS.get()); 13276 if (RHS.isInvalid()) 13277 return QualType(); 13278 13279 if (!LHS.get()->getType()->isScalarType() || 13280 !RHS.get()->getType()->isScalarType()) 13281 return InvalidOperands(Loc, LHS, RHS); 13282 13283 return Context.IntTy; 13284 } 13285 13286 // The following is safe because we only use this method for 13287 // non-overloadable operands. 13288 13289 // C++ [expr.log.and]p1 13290 // C++ [expr.log.or]p1 13291 // The operands are both contextually converted to type bool. 13292 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 13293 if (LHSRes.isInvalid()) 13294 return InvalidOperands(Loc, LHS, RHS); 13295 LHS = LHSRes; 13296 13297 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 13298 if (RHSRes.isInvalid()) 13299 return InvalidOperands(Loc, LHS, RHS); 13300 RHS = RHSRes; 13301 13302 // C++ [expr.log.and]p2 13303 // C++ [expr.log.or]p2 13304 // The result is a bool. 13305 return Context.BoolTy; 13306 } 13307 13308 static bool IsReadonlyMessage(Expr *E, Sema &S) { 13309 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 13310 if (!ME) return false; 13311 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 13312 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 13313 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 13314 if (!Base) return false; 13315 return Base->getMethodDecl() != nullptr; 13316 } 13317 13318 /// Is the given expression (which must be 'const') a reference to a 13319 /// variable which was originally non-const, but which has become 13320 /// 'const' due to being captured within a block? 13321 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 13322 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 13323 assert(E->isLValue() && E->getType().isConstQualified()); 13324 E = E->IgnoreParens(); 13325 13326 // Must be a reference to a declaration from an enclosing scope. 13327 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 13328 if (!DRE) return NCCK_None; 13329 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 13330 13331 // The declaration must be a variable which is not declared 'const'. 13332 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 13333 if (!var) return NCCK_None; 13334 if (var->getType().isConstQualified()) return NCCK_None; 13335 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 13336 13337 // Decide whether the first capture was for a block or a lambda. 13338 DeclContext *DC = S.CurContext, *Prev = nullptr; 13339 // Decide whether the first capture was for a block or a lambda. 13340 while (DC) { 13341 // For init-capture, it is possible that the variable belongs to the 13342 // template pattern of the current context. 13343 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 13344 if (var->isInitCapture() && 13345 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 13346 break; 13347 if (DC == var->getDeclContext()) 13348 break; 13349 Prev = DC; 13350 DC = DC->getParent(); 13351 } 13352 // Unless we have an init-capture, we've gone one step too far. 13353 if (!var->isInitCapture()) 13354 DC = Prev; 13355 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 13356 } 13357 13358 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 13359 Ty = Ty.getNonReferenceType(); 13360 if (IsDereference && Ty->isPointerType()) 13361 Ty = Ty->getPointeeType(); 13362 return !Ty.isConstQualified(); 13363 } 13364 13365 // Update err_typecheck_assign_const and note_typecheck_assign_const 13366 // when this enum is changed. 13367 enum { 13368 ConstFunction, 13369 ConstVariable, 13370 ConstMember, 13371 ConstMethod, 13372 NestedConstMember, 13373 ConstUnknown, // Keep as last element 13374 }; 13375 13376 /// Emit the "read-only variable not assignable" error and print notes to give 13377 /// more information about why the variable is not assignable, such as pointing 13378 /// to the declaration of a const variable, showing that a method is const, or 13379 /// that the function is returning a const reference. 13380 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 13381 SourceLocation Loc) { 13382 SourceRange ExprRange = E->getSourceRange(); 13383 13384 // Only emit one error on the first const found. All other consts will emit 13385 // a note to the error. 13386 bool DiagnosticEmitted = false; 13387 13388 // Track if the current expression is the result of a dereference, and if the 13389 // next checked expression is the result of a dereference. 13390 bool IsDereference = false; 13391 bool NextIsDereference = false; 13392 13393 // Loop to process MemberExpr chains. 13394 while (true) { 13395 IsDereference = NextIsDereference; 13396 13397 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 13398 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13399 NextIsDereference = ME->isArrow(); 13400 const ValueDecl *VD = ME->getMemberDecl(); 13401 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 13402 // Mutable fields can be modified even if the class is const. 13403 if (Field->isMutable()) { 13404 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 13405 break; 13406 } 13407 13408 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 13409 if (!DiagnosticEmitted) { 13410 S.Diag(Loc, diag::err_typecheck_assign_const) 13411 << ExprRange << ConstMember << false /*static*/ << Field 13412 << Field->getType(); 13413 DiagnosticEmitted = true; 13414 } 13415 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 13416 << ConstMember << false /*static*/ << Field << Field->getType() 13417 << Field->getSourceRange(); 13418 } 13419 E = ME->getBase(); 13420 continue; 13421 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 13422 if (VDecl->getType().isConstQualified()) { 13423 if (!DiagnosticEmitted) { 13424 S.Diag(Loc, diag::err_typecheck_assign_const) 13425 << ExprRange << ConstMember << true /*static*/ << VDecl 13426 << VDecl->getType(); 13427 DiagnosticEmitted = true; 13428 } 13429 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 13430 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 13431 << VDecl->getSourceRange(); 13432 } 13433 // Static fields do not inherit constness from parents. 13434 break; 13435 } 13436 break; // End MemberExpr 13437 } else if (const ArraySubscriptExpr *ASE = 13438 dyn_cast<ArraySubscriptExpr>(E)) { 13439 E = ASE->getBase()->IgnoreParenImpCasts(); 13440 continue; 13441 } else if (const ExtVectorElementExpr *EVE = 13442 dyn_cast<ExtVectorElementExpr>(E)) { 13443 E = EVE->getBase()->IgnoreParenImpCasts(); 13444 continue; 13445 } 13446 break; 13447 } 13448 13449 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 13450 // Function calls 13451 const FunctionDecl *FD = CE->getDirectCallee(); 13452 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 13453 if (!DiagnosticEmitted) { 13454 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 13455 << ConstFunction << FD; 13456 DiagnosticEmitted = true; 13457 } 13458 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 13459 diag::note_typecheck_assign_const) 13460 << ConstFunction << FD << FD->getReturnType() 13461 << FD->getReturnTypeSourceRange(); 13462 } 13463 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13464 // Point to variable declaration. 13465 if (const ValueDecl *VD = DRE->getDecl()) { 13466 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 13467 if (!DiagnosticEmitted) { 13468 S.Diag(Loc, diag::err_typecheck_assign_const) 13469 << ExprRange << ConstVariable << VD << VD->getType(); 13470 DiagnosticEmitted = true; 13471 } 13472 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 13473 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 13474 } 13475 } 13476 } else if (isa<CXXThisExpr>(E)) { 13477 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 13478 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 13479 if (MD->isConst()) { 13480 if (!DiagnosticEmitted) { 13481 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 13482 << ConstMethod << MD; 13483 DiagnosticEmitted = true; 13484 } 13485 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 13486 << ConstMethod << MD << MD->getSourceRange(); 13487 } 13488 } 13489 } 13490 } 13491 13492 if (DiagnosticEmitted) 13493 return; 13494 13495 // Can't determine a more specific message, so display the generic error. 13496 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 13497 } 13498 13499 enum OriginalExprKind { 13500 OEK_Variable, 13501 OEK_Member, 13502 OEK_LValue 13503 }; 13504 13505 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 13506 const RecordType *Ty, 13507 SourceLocation Loc, SourceRange Range, 13508 OriginalExprKind OEK, 13509 bool &DiagnosticEmitted) { 13510 std::vector<const RecordType *> RecordTypeList; 13511 RecordTypeList.push_back(Ty); 13512 unsigned NextToCheckIndex = 0; 13513 // We walk the record hierarchy breadth-first to ensure that we print 13514 // diagnostics in field nesting order. 13515 while (RecordTypeList.size() > NextToCheckIndex) { 13516 bool IsNested = NextToCheckIndex > 0; 13517 for (const FieldDecl *Field : 13518 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 13519 // First, check every field for constness. 13520 QualType FieldTy = Field->getType(); 13521 if (FieldTy.isConstQualified()) { 13522 if (!DiagnosticEmitted) { 13523 S.Diag(Loc, diag::err_typecheck_assign_const) 13524 << Range << NestedConstMember << OEK << VD 13525 << IsNested << Field; 13526 DiagnosticEmitted = true; 13527 } 13528 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 13529 << NestedConstMember << IsNested << Field 13530 << FieldTy << Field->getSourceRange(); 13531 } 13532 13533 // Then we append it to the list to check next in order. 13534 FieldTy = FieldTy.getCanonicalType(); 13535 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 13536 if (!llvm::is_contained(RecordTypeList, FieldRecTy)) 13537 RecordTypeList.push_back(FieldRecTy); 13538 } 13539 } 13540 ++NextToCheckIndex; 13541 } 13542 } 13543 13544 /// Emit an error for the case where a record we are trying to assign to has a 13545 /// const-qualified field somewhere in its hierarchy. 13546 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 13547 SourceLocation Loc) { 13548 QualType Ty = E->getType(); 13549 assert(Ty->isRecordType() && "lvalue was not record?"); 13550 SourceRange Range = E->getSourceRange(); 13551 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 13552 bool DiagEmitted = false; 13553 13554 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 13555 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 13556 Range, OEK_Member, DiagEmitted); 13557 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13558 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 13559 Range, OEK_Variable, DiagEmitted); 13560 else 13561 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 13562 Range, OEK_LValue, DiagEmitted); 13563 if (!DiagEmitted) 13564 DiagnoseConstAssignment(S, E, Loc); 13565 } 13566 13567 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 13568 /// emit an error and return true. If so, return false. 13569 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 13570 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 13571 13572 S.CheckShadowingDeclModification(E, Loc); 13573 13574 SourceLocation OrigLoc = Loc; 13575 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 13576 &Loc); 13577 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 13578 IsLV = Expr::MLV_InvalidMessageExpression; 13579 if (IsLV == Expr::MLV_Valid) 13580 return false; 13581 13582 unsigned DiagID = 0; 13583 bool NeedType = false; 13584 switch (IsLV) { // C99 6.5.16p2 13585 case Expr::MLV_ConstQualified: 13586 // Use a specialized diagnostic when we're assigning to an object 13587 // from an enclosing function or block. 13588 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 13589 if (NCCK == NCCK_Block) 13590 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 13591 else 13592 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 13593 break; 13594 } 13595 13596 // In ARC, use some specialized diagnostics for occasions where we 13597 // infer 'const'. These are always pseudo-strong variables. 13598 if (S.getLangOpts().ObjCAutoRefCount) { 13599 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 13600 if (declRef && isa<VarDecl>(declRef->getDecl())) { 13601 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 13602 13603 // Use the normal diagnostic if it's pseudo-__strong but the 13604 // user actually wrote 'const'. 13605 if (var->isARCPseudoStrong() && 13606 (!var->getTypeSourceInfo() || 13607 !var->getTypeSourceInfo()->getType().isConstQualified())) { 13608 // There are three pseudo-strong cases: 13609 // - self 13610 ObjCMethodDecl *method = S.getCurMethodDecl(); 13611 if (method && var == method->getSelfDecl()) { 13612 DiagID = method->isClassMethod() 13613 ? diag::err_typecheck_arc_assign_self_class_method 13614 : diag::err_typecheck_arc_assign_self; 13615 13616 // - Objective-C externally_retained attribute. 13617 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 13618 isa<ParmVarDecl>(var)) { 13619 DiagID = diag::err_typecheck_arc_assign_externally_retained; 13620 13621 // - fast enumeration variables 13622 } else { 13623 DiagID = diag::err_typecheck_arr_assign_enumeration; 13624 } 13625 13626 SourceRange Assign; 13627 if (Loc != OrigLoc) 13628 Assign = SourceRange(OrigLoc, OrigLoc); 13629 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13630 // We need to preserve the AST regardless, so migration tool 13631 // can do its job. 13632 return false; 13633 } 13634 } 13635 } 13636 13637 // If none of the special cases above are triggered, then this is a 13638 // simple const assignment. 13639 if (DiagID == 0) { 13640 DiagnoseConstAssignment(S, E, Loc); 13641 return true; 13642 } 13643 13644 break; 13645 case Expr::MLV_ConstAddrSpace: 13646 DiagnoseConstAssignment(S, E, Loc); 13647 return true; 13648 case Expr::MLV_ConstQualifiedField: 13649 DiagnoseRecursiveConstFields(S, E, Loc); 13650 return true; 13651 case Expr::MLV_ArrayType: 13652 case Expr::MLV_ArrayTemporary: 13653 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 13654 NeedType = true; 13655 break; 13656 case Expr::MLV_NotObjectType: 13657 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 13658 NeedType = true; 13659 break; 13660 case Expr::MLV_LValueCast: 13661 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 13662 break; 13663 case Expr::MLV_Valid: 13664 llvm_unreachable("did not take early return for MLV_Valid"); 13665 case Expr::MLV_InvalidExpression: 13666 case Expr::MLV_MemberFunction: 13667 case Expr::MLV_ClassTemporary: 13668 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 13669 break; 13670 case Expr::MLV_IncompleteType: 13671 case Expr::MLV_IncompleteVoidType: 13672 return S.RequireCompleteType(Loc, E->getType(), 13673 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 13674 case Expr::MLV_DuplicateVectorComponents: 13675 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 13676 break; 13677 case Expr::MLV_NoSetterProperty: 13678 llvm_unreachable("readonly properties should be processed differently"); 13679 case Expr::MLV_InvalidMessageExpression: 13680 DiagID = diag::err_readonly_message_assignment; 13681 break; 13682 case Expr::MLV_SubObjCPropertySetting: 13683 DiagID = diag::err_no_subobject_property_setting; 13684 break; 13685 } 13686 13687 SourceRange Assign; 13688 if (Loc != OrigLoc) 13689 Assign = SourceRange(OrigLoc, OrigLoc); 13690 if (NeedType) 13691 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 13692 else 13693 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13694 return true; 13695 } 13696 13697 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 13698 SourceLocation Loc, 13699 Sema &Sema) { 13700 if (Sema.inTemplateInstantiation()) 13701 return; 13702 if (Sema.isUnevaluatedContext()) 13703 return; 13704 if (Loc.isInvalid() || Loc.isMacroID()) 13705 return; 13706 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 13707 return; 13708 13709 // C / C++ fields 13710 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 13711 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 13712 if (ML && MR) { 13713 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 13714 return; 13715 const ValueDecl *LHSDecl = 13716 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 13717 const ValueDecl *RHSDecl = 13718 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13719 if (LHSDecl != RHSDecl) 13720 return; 13721 if (LHSDecl->getType().isVolatileQualified()) 13722 return; 13723 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13724 if (RefTy->getPointeeType().isVolatileQualified()) 13725 return; 13726 13727 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13728 } 13729 13730 // Objective-C instance variables 13731 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13732 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13733 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13734 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13735 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13736 if (RL && RR && RL->getDecl() == RR->getDecl()) 13737 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13738 } 13739 } 13740 13741 // C99 6.5.16.1 13742 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13743 SourceLocation Loc, 13744 QualType CompoundType) { 13745 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13746 13747 // Verify that LHS is a modifiable lvalue, and emit error if not. 13748 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13749 return QualType(); 13750 13751 QualType LHSType = LHSExpr->getType(); 13752 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13753 CompoundType; 13754 // OpenCL v1.2 s6.1.1.1 p2: 13755 // The half data type can only be used to declare a pointer to a buffer that 13756 // contains half values 13757 if (getLangOpts().OpenCL && 13758 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13759 LHSType->isHalfType()) { 13760 Diag(Loc, diag::err_opencl_half_load_store) << 1 13761 << LHSType.getUnqualifiedType(); 13762 return QualType(); 13763 } 13764 13765 AssignConvertType ConvTy; 13766 if (CompoundType.isNull()) { 13767 Expr *RHSCheck = RHS.get(); 13768 13769 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13770 13771 QualType LHSTy(LHSType); 13772 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13773 if (RHS.isInvalid()) 13774 return QualType(); 13775 // Special case of NSObject attributes on c-style pointer types. 13776 if (ConvTy == IncompatiblePointer && 13777 ((Context.isObjCNSObjectType(LHSType) && 13778 RHSType->isObjCObjectPointerType()) || 13779 (Context.isObjCNSObjectType(RHSType) && 13780 LHSType->isObjCObjectPointerType()))) 13781 ConvTy = Compatible; 13782 13783 if (ConvTy == Compatible && 13784 LHSType->isObjCObjectType()) 13785 Diag(Loc, diag::err_objc_object_assignment) 13786 << LHSType; 13787 13788 // If the RHS is a unary plus or minus, check to see if they = and + are 13789 // right next to each other. If so, the user may have typo'd "x =+ 4" 13790 // instead of "x += 4". 13791 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13792 RHSCheck = ICE->getSubExpr(); 13793 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13794 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13795 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13796 // Only if the two operators are exactly adjacent. 13797 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13798 // And there is a space or other character before the subexpr of the 13799 // unary +/-. We don't want to warn on "x=-1". 13800 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13801 UO->getSubExpr()->getBeginLoc().isFileID()) { 13802 Diag(Loc, diag::warn_not_compound_assign) 13803 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13804 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13805 } 13806 } 13807 13808 if (ConvTy == Compatible) { 13809 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13810 // Warn about retain cycles where a block captures the LHS, but 13811 // not if the LHS is a simple variable into which the block is 13812 // being stored...unless that variable can be captured by reference! 13813 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13814 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13815 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13816 checkRetainCycles(LHSExpr, RHS.get()); 13817 } 13818 13819 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13820 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13821 // It is safe to assign a weak reference into a strong variable. 13822 // Although this code can still have problems: 13823 // id x = self.weakProp; 13824 // id y = self.weakProp; 13825 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13826 // paths through the function. This should be revisited if 13827 // -Wrepeated-use-of-weak is made flow-sensitive. 13828 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13829 // variable, which will be valid for the current autorelease scope. 13830 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13831 RHS.get()->getBeginLoc())) 13832 getCurFunction()->markSafeWeakUse(RHS.get()); 13833 13834 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13835 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13836 } 13837 } 13838 } else { 13839 // Compound assignment "x += y" 13840 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13841 } 13842 13843 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13844 RHS.get(), AA_Assigning)) 13845 return QualType(); 13846 13847 CheckForNullPointerDereference(*this, LHSExpr); 13848 13849 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13850 if (CompoundType.isNull()) { 13851 // C++2a [expr.ass]p5: 13852 // A simple-assignment whose left operand is of a volatile-qualified 13853 // type is deprecated unless the assignment is either a discarded-value 13854 // expression or an unevaluated operand 13855 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13856 } else { 13857 // C++2a [expr.ass]p6: 13858 // [Compound-assignment] expressions are deprecated if E1 has 13859 // volatile-qualified type 13860 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13861 } 13862 } 13863 13864 // C11 6.5.16p3: The type of an assignment expression is the type of the 13865 // left operand would have after lvalue conversion. 13866 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has 13867 // qualified type, the value has the unqualified version of the type of the 13868 // lvalue; additionally, if the lvalue has atomic type, the value has the 13869 // non-atomic version of the type of the lvalue. 13870 // C++ 5.17p1: the type of the assignment expression is that of its left 13871 // operand. 13872 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType(); 13873 } 13874 13875 // Only ignore explicit casts to void. 13876 static bool IgnoreCommaOperand(const Expr *E) { 13877 E = E->IgnoreParens(); 13878 13879 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13880 if (CE->getCastKind() == CK_ToVoid) { 13881 return true; 13882 } 13883 13884 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13885 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13886 CE->getSubExpr()->getType()->isDependentType()) { 13887 return true; 13888 } 13889 } 13890 13891 return false; 13892 } 13893 13894 // Look for instances where it is likely the comma operator is confused with 13895 // another operator. There is an explicit list of acceptable expressions for 13896 // the left hand side of the comma operator, otherwise emit a warning. 13897 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13898 // No warnings in macros 13899 if (Loc.isMacroID()) 13900 return; 13901 13902 // Don't warn in template instantiations. 13903 if (inTemplateInstantiation()) 13904 return; 13905 13906 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13907 // instead, skip more than needed, then call back into here with the 13908 // CommaVisitor in SemaStmt.cpp. 13909 // The listed locations are the initialization and increment portions 13910 // of a for loop. The additional checks are on the condition of 13911 // if statements, do/while loops, and for loops. 13912 // Differences in scope flags for C89 mode requires the extra logic. 13913 const unsigned ForIncrementFlags = 13914 getLangOpts().C99 || getLangOpts().CPlusPlus 13915 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13916 : Scope::ContinueScope | Scope::BreakScope; 13917 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13918 const unsigned ScopeFlags = getCurScope()->getFlags(); 13919 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13920 (ScopeFlags & ForInitFlags) == ForInitFlags) 13921 return; 13922 13923 // If there are multiple comma operators used together, get the RHS of the 13924 // of the comma operator as the LHS. 13925 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13926 if (BO->getOpcode() != BO_Comma) 13927 break; 13928 LHS = BO->getRHS(); 13929 } 13930 13931 // Only allow some expressions on LHS to not warn. 13932 if (IgnoreCommaOperand(LHS)) 13933 return; 13934 13935 Diag(Loc, diag::warn_comma_operator); 13936 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13937 << LHS->getSourceRange() 13938 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13939 LangOpts.CPlusPlus ? "static_cast<void>(" 13940 : "(void)(") 13941 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13942 ")"); 13943 } 13944 13945 // C99 6.5.17 13946 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13947 SourceLocation Loc) { 13948 LHS = S.CheckPlaceholderExpr(LHS.get()); 13949 RHS = S.CheckPlaceholderExpr(RHS.get()); 13950 if (LHS.isInvalid() || RHS.isInvalid()) 13951 return QualType(); 13952 13953 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13954 // operands, but not unary promotions. 13955 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13956 13957 // So we treat the LHS as a ignored value, and in C++ we allow the 13958 // containing site to determine what should be done with the RHS. 13959 LHS = S.IgnoredValueConversions(LHS.get()); 13960 if (LHS.isInvalid()) 13961 return QualType(); 13962 13963 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand); 13964 13965 if (!S.getLangOpts().CPlusPlus) { 13966 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13967 if (RHS.isInvalid()) 13968 return QualType(); 13969 if (!RHS.get()->getType()->isVoidType()) 13970 S.RequireCompleteType(Loc, RHS.get()->getType(), 13971 diag::err_incomplete_type); 13972 } 13973 13974 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13975 S.DiagnoseCommaOperator(LHS.get(), Loc); 13976 13977 return RHS.get()->getType(); 13978 } 13979 13980 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13981 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13982 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13983 ExprValueKind &VK, 13984 ExprObjectKind &OK, 13985 SourceLocation OpLoc, 13986 bool IsInc, bool IsPrefix) { 13987 if (Op->isTypeDependent()) 13988 return S.Context.DependentTy; 13989 13990 QualType ResType = Op->getType(); 13991 // Atomic types can be used for increment / decrement where the non-atomic 13992 // versions can, so ignore the _Atomic() specifier for the purpose of 13993 // checking. 13994 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13995 ResType = ResAtomicType->getValueType(); 13996 13997 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13998 13999 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 14000 // Decrement of bool is not allowed. 14001 if (!IsInc) { 14002 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 14003 return QualType(); 14004 } 14005 // Increment of bool sets it to true, but is deprecated. 14006 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 14007 : diag::warn_increment_bool) 14008 << Op->getSourceRange(); 14009 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 14010 // Error on enum increments and decrements in C++ mode 14011 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 14012 return QualType(); 14013 } else if (ResType->isRealType()) { 14014 // OK! 14015 } else if (ResType->isPointerType()) { 14016 // C99 6.5.2.4p2, 6.5.6p2 14017 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 14018 return QualType(); 14019 } else if (ResType->isObjCObjectPointerType()) { 14020 // On modern runtimes, ObjC pointer arithmetic is forbidden. 14021 // Otherwise, we just need a complete type. 14022 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 14023 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 14024 return QualType(); 14025 } else if (ResType->isAnyComplexType()) { 14026 // C99 does not support ++/-- on complex types, we allow as an extension. 14027 S.Diag(OpLoc, diag::ext_integer_increment_complex) 14028 << ResType << Op->getSourceRange(); 14029 } else if (ResType->isPlaceholderType()) { 14030 ExprResult PR = S.CheckPlaceholderExpr(Op); 14031 if (PR.isInvalid()) return QualType(); 14032 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 14033 IsInc, IsPrefix); 14034 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 14035 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 14036 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 14037 (ResType->castAs<VectorType>()->getVectorKind() != 14038 VectorType::AltiVecBool)) { 14039 // The z vector extensions allow ++ and -- for non-bool vectors. 14040 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 14041 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 14042 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 14043 } else { 14044 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 14045 << ResType << int(IsInc) << Op->getSourceRange(); 14046 return QualType(); 14047 } 14048 // At this point, we know we have a real, complex or pointer type. 14049 // Now make sure the operand is a modifiable lvalue. 14050 if (CheckForModifiableLvalue(Op, OpLoc, S)) 14051 return QualType(); 14052 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 14053 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 14054 // An operand with volatile-qualified type is deprecated 14055 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 14056 << IsInc << ResType; 14057 } 14058 // In C++, a prefix increment is the same type as the operand. Otherwise 14059 // (in C or with postfix), the increment is the unqualified type of the 14060 // operand. 14061 if (IsPrefix && S.getLangOpts().CPlusPlus) { 14062 VK = VK_LValue; 14063 OK = Op->getObjectKind(); 14064 return ResType; 14065 } else { 14066 VK = VK_PRValue; 14067 return ResType.getUnqualifiedType(); 14068 } 14069 } 14070 14071 14072 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 14073 /// This routine allows us to typecheck complex/recursive expressions 14074 /// where the declaration is needed for type checking. We only need to 14075 /// handle cases when the expression references a function designator 14076 /// or is an lvalue. Here are some examples: 14077 /// - &(x) => x 14078 /// - &*****f => f for f a function designator. 14079 /// - &s.xx => s 14080 /// - &s.zz[1].yy -> s, if zz is an array 14081 /// - *(x + 1) -> x, if x is an array 14082 /// - &"123"[2] -> 0 14083 /// - & __real__ x -> x 14084 /// 14085 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 14086 /// members. 14087 static ValueDecl *getPrimaryDecl(Expr *E) { 14088 switch (E->getStmtClass()) { 14089 case Stmt::DeclRefExprClass: 14090 return cast<DeclRefExpr>(E)->getDecl(); 14091 case Stmt::MemberExprClass: 14092 // If this is an arrow operator, the address is an offset from 14093 // the base's value, so the object the base refers to is 14094 // irrelevant. 14095 if (cast<MemberExpr>(E)->isArrow()) 14096 return nullptr; 14097 // Otherwise, the expression refers to a part of the base 14098 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 14099 case Stmt::ArraySubscriptExprClass: { 14100 // FIXME: This code shouldn't be necessary! We should catch the implicit 14101 // promotion of register arrays earlier. 14102 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 14103 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 14104 if (ICE->getSubExpr()->getType()->isArrayType()) 14105 return getPrimaryDecl(ICE->getSubExpr()); 14106 } 14107 return nullptr; 14108 } 14109 case Stmt::UnaryOperatorClass: { 14110 UnaryOperator *UO = cast<UnaryOperator>(E); 14111 14112 switch(UO->getOpcode()) { 14113 case UO_Real: 14114 case UO_Imag: 14115 case UO_Extension: 14116 return getPrimaryDecl(UO->getSubExpr()); 14117 default: 14118 return nullptr; 14119 } 14120 } 14121 case Stmt::ParenExprClass: 14122 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 14123 case Stmt::ImplicitCastExprClass: 14124 // If the result of an implicit cast is an l-value, we care about 14125 // the sub-expression; otherwise, the result here doesn't matter. 14126 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 14127 case Stmt::CXXUuidofExprClass: 14128 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 14129 default: 14130 return nullptr; 14131 } 14132 } 14133 14134 namespace { 14135 enum { 14136 AO_Bit_Field = 0, 14137 AO_Vector_Element = 1, 14138 AO_Property_Expansion = 2, 14139 AO_Register_Variable = 3, 14140 AO_Matrix_Element = 4, 14141 AO_No_Error = 5 14142 }; 14143 } 14144 /// Diagnose invalid operand for address of operations. 14145 /// 14146 /// \param Type The type of operand which cannot have its address taken. 14147 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 14148 Expr *E, unsigned Type) { 14149 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 14150 } 14151 14152 /// CheckAddressOfOperand - The operand of & must be either a function 14153 /// designator or an lvalue designating an object. If it is an lvalue, the 14154 /// object cannot be declared with storage class register or be a bit field. 14155 /// Note: The usual conversions are *not* applied to the operand of the & 14156 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 14157 /// In C++, the operand might be an overloaded function name, in which case 14158 /// we allow the '&' but retain the overloaded-function type. 14159 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 14160 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 14161 if (PTy->getKind() == BuiltinType::Overload) { 14162 Expr *E = OrigOp.get()->IgnoreParens(); 14163 if (!isa<OverloadExpr>(E)) { 14164 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 14165 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 14166 << OrigOp.get()->getSourceRange(); 14167 return QualType(); 14168 } 14169 14170 OverloadExpr *Ovl = cast<OverloadExpr>(E); 14171 if (isa<UnresolvedMemberExpr>(Ovl)) 14172 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 14173 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 14174 << OrigOp.get()->getSourceRange(); 14175 return QualType(); 14176 } 14177 14178 return Context.OverloadTy; 14179 } 14180 14181 if (PTy->getKind() == BuiltinType::UnknownAny) 14182 return Context.UnknownAnyTy; 14183 14184 if (PTy->getKind() == BuiltinType::BoundMember) { 14185 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 14186 << OrigOp.get()->getSourceRange(); 14187 return QualType(); 14188 } 14189 14190 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 14191 if (OrigOp.isInvalid()) return QualType(); 14192 } 14193 14194 if (OrigOp.get()->isTypeDependent()) 14195 return Context.DependentTy; 14196 14197 assert(!OrigOp.get()->hasPlaceholderType()); 14198 14199 // Make sure to ignore parentheses in subsequent checks 14200 Expr *op = OrigOp.get()->IgnoreParens(); 14201 14202 // In OpenCL captures for blocks called as lambda functions 14203 // are located in the private address space. Blocks used in 14204 // enqueue_kernel can be located in a different address space 14205 // depending on a vendor implementation. Thus preventing 14206 // taking an address of the capture to avoid invalid AS casts. 14207 if (LangOpts.OpenCL) { 14208 auto* VarRef = dyn_cast<DeclRefExpr>(op); 14209 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 14210 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 14211 return QualType(); 14212 } 14213 } 14214 14215 if (getLangOpts().C99) { 14216 // Implement C99-only parts of addressof rules. 14217 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 14218 if (uOp->getOpcode() == UO_Deref) 14219 // Per C99 6.5.3.2, the address of a deref always returns a valid result 14220 // (assuming the deref expression is valid). 14221 return uOp->getSubExpr()->getType(); 14222 } 14223 // Technically, there should be a check for array subscript 14224 // expressions here, but the result of one is always an lvalue anyway. 14225 } 14226 ValueDecl *dcl = getPrimaryDecl(op); 14227 14228 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 14229 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 14230 op->getBeginLoc())) 14231 return QualType(); 14232 14233 Expr::LValueClassification lval = op->ClassifyLValue(Context); 14234 unsigned AddressOfError = AO_No_Error; 14235 14236 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 14237 bool sfinae = (bool)isSFINAEContext(); 14238 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 14239 : diag::ext_typecheck_addrof_temporary) 14240 << op->getType() << op->getSourceRange(); 14241 if (sfinae) 14242 return QualType(); 14243 // Materialize the temporary as an lvalue so that we can take its address. 14244 OrigOp = op = 14245 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 14246 } else if (isa<ObjCSelectorExpr>(op)) { 14247 return Context.getPointerType(op->getType()); 14248 } else if (lval == Expr::LV_MemberFunction) { 14249 // If it's an instance method, make a member pointer. 14250 // The expression must have exactly the form &A::foo. 14251 14252 // If the underlying expression isn't a decl ref, give up. 14253 if (!isa<DeclRefExpr>(op)) { 14254 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 14255 << OrigOp.get()->getSourceRange(); 14256 return QualType(); 14257 } 14258 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 14259 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 14260 14261 // The id-expression was parenthesized. 14262 if (OrigOp.get() != DRE) { 14263 Diag(OpLoc, diag::err_parens_pointer_member_function) 14264 << OrigOp.get()->getSourceRange(); 14265 14266 // The method was named without a qualifier. 14267 } else if (!DRE->getQualifier()) { 14268 if (MD->getParent()->getName().empty()) 14269 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 14270 << op->getSourceRange(); 14271 else { 14272 SmallString<32> Str; 14273 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 14274 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 14275 << op->getSourceRange() 14276 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 14277 } 14278 } 14279 14280 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 14281 if (isa<CXXDestructorDecl>(MD)) 14282 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 14283 14284 QualType MPTy = Context.getMemberPointerType( 14285 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 14286 // Under the MS ABI, lock down the inheritance model now. 14287 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14288 (void)isCompleteType(OpLoc, MPTy); 14289 return MPTy; 14290 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 14291 // C99 6.5.3.2p1 14292 // The operand must be either an l-value or a function designator 14293 if (!op->getType()->isFunctionType()) { 14294 // Use a special diagnostic for loads from property references. 14295 if (isa<PseudoObjectExpr>(op)) { 14296 AddressOfError = AO_Property_Expansion; 14297 } else { 14298 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 14299 << op->getType() << op->getSourceRange(); 14300 return QualType(); 14301 } 14302 } 14303 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 14304 // The operand cannot be a bit-field 14305 AddressOfError = AO_Bit_Field; 14306 } else if (op->getObjectKind() == OK_VectorComponent) { 14307 // The operand cannot be an element of a vector 14308 AddressOfError = AO_Vector_Element; 14309 } else if (op->getObjectKind() == OK_MatrixComponent) { 14310 // The operand cannot be an element of a matrix. 14311 AddressOfError = AO_Matrix_Element; 14312 } else if (dcl) { // C99 6.5.3.2p1 14313 // We have an lvalue with a decl. Make sure the decl is not declared 14314 // with the register storage-class specifier. 14315 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 14316 // in C++ it is not error to take address of a register 14317 // variable (c++03 7.1.1P3) 14318 if (vd->getStorageClass() == SC_Register && 14319 !getLangOpts().CPlusPlus) { 14320 AddressOfError = AO_Register_Variable; 14321 } 14322 } else if (isa<MSPropertyDecl>(dcl)) { 14323 AddressOfError = AO_Property_Expansion; 14324 } else if (isa<FunctionTemplateDecl>(dcl)) { 14325 return Context.OverloadTy; 14326 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 14327 // Okay: we can take the address of a field. 14328 // Could be a pointer to member, though, if there is an explicit 14329 // scope qualifier for the class. 14330 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 14331 DeclContext *Ctx = dcl->getDeclContext(); 14332 if (Ctx && Ctx->isRecord()) { 14333 if (dcl->getType()->isReferenceType()) { 14334 Diag(OpLoc, 14335 diag::err_cannot_form_pointer_to_member_of_reference_type) 14336 << dcl->getDeclName() << dcl->getType(); 14337 return QualType(); 14338 } 14339 14340 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 14341 Ctx = Ctx->getParent(); 14342 14343 QualType MPTy = Context.getMemberPointerType( 14344 op->getType(), 14345 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 14346 // Under the MS ABI, lock down the inheritance model now. 14347 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14348 (void)isCompleteType(OpLoc, MPTy); 14349 return MPTy; 14350 } 14351 } 14352 } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl, 14353 MSGuidDecl, UnnamedGlobalConstantDecl>(dcl)) 14354 llvm_unreachable("Unknown/unexpected decl type"); 14355 } 14356 14357 if (AddressOfError != AO_No_Error) { 14358 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 14359 return QualType(); 14360 } 14361 14362 if (lval == Expr::LV_IncompleteVoidType) { 14363 // Taking the address of a void variable is technically illegal, but we 14364 // allow it in cases which are otherwise valid. 14365 // Example: "extern void x; void* y = &x;". 14366 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 14367 } 14368 14369 // If the operand has type "type", the result has type "pointer to type". 14370 if (op->getType()->isObjCObjectType()) 14371 return Context.getObjCObjectPointerType(op->getType()); 14372 14373 CheckAddressOfPackedMember(op); 14374 14375 return Context.getPointerType(op->getType()); 14376 } 14377 14378 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 14379 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 14380 if (!DRE) 14381 return; 14382 const Decl *D = DRE->getDecl(); 14383 if (!D) 14384 return; 14385 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 14386 if (!Param) 14387 return; 14388 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 14389 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 14390 return; 14391 if (FunctionScopeInfo *FD = S.getCurFunction()) 14392 if (!FD->ModifiedNonNullParams.count(Param)) 14393 FD->ModifiedNonNullParams.insert(Param); 14394 } 14395 14396 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 14397 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 14398 SourceLocation OpLoc) { 14399 if (Op->isTypeDependent()) 14400 return S.Context.DependentTy; 14401 14402 ExprResult ConvResult = S.UsualUnaryConversions(Op); 14403 if (ConvResult.isInvalid()) 14404 return QualType(); 14405 Op = ConvResult.get(); 14406 QualType OpTy = Op->getType(); 14407 QualType Result; 14408 14409 if (isa<CXXReinterpretCastExpr>(Op)) { 14410 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 14411 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 14412 Op->getSourceRange()); 14413 } 14414 14415 if (const PointerType *PT = OpTy->getAs<PointerType>()) 14416 { 14417 Result = PT->getPointeeType(); 14418 } 14419 else if (const ObjCObjectPointerType *OPT = 14420 OpTy->getAs<ObjCObjectPointerType>()) 14421 Result = OPT->getPointeeType(); 14422 else { 14423 ExprResult PR = S.CheckPlaceholderExpr(Op); 14424 if (PR.isInvalid()) return QualType(); 14425 if (PR.get() != Op) 14426 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 14427 } 14428 14429 if (Result.isNull()) { 14430 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 14431 << OpTy << Op->getSourceRange(); 14432 return QualType(); 14433 } 14434 14435 // Note that per both C89 and C99, indirection is always legal, even if Result 14436 // is an incomplete type or void. It would be possible to warn about 14437 // dereferencing a void pointer, but it's completely well-defined, and such a 14438 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 14439 // for pointers to 'void' but is fine for any other pointer type: 14440 // 14441 // C++ [expr.unary.op]p1: 14442 // [...] the expression to which [the unary * operator] is applied shall 14443 // be a pointer to an object type, or a pointer to a function type 14444 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 14445 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 14446 << OpTy << Op->getSourceRange(); 14447 14448 // Dereferences are usually l-values... 14449 VK = VK_LValue; 14450 14451 // ...except that certain expressions are never l-values in C. 14452 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 14453 VK = VK_PRValue; 14454 14455 return Result; 14456 } 14457 14458 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 14459 BinaryOperatorKind Opc; 14460 switch (Kind) { 14461 default: llvm_unreachable("Unknown binop!"); 14462 case tok::periodstar: Opc = BO_PtrMemD; break; 14463 case tok::arrowstar: Opc = BO_PtrMemI; break; 14464 case tok::star: Opc = BO_Mul; break; 14465 case tok::slash: Opc = BO_Div; break; 14466 case tok::percent: Opc = BO_Rem; break; 14467 case tok::plus: Opc = BO_Add; break; 14468 case tok::minus: Opc = BO_Sub; break; 14469 case tok::lessless: Opc = BO_Shl; break; 14470 case tok::greatergreater: Opc = BO_Shr; break; 14471 case tok::lessequal: Opc = BO_LE; break; 14472 case tok::less: Opc = BO_LT; break; 14473 case tok::greaterequal: Opc = BO_GE; break; 14474 case tok::greater: Opc = BO_GT; break; 14475 case tok::exclaimequal: Opc = BO_NE; break; 14476 case tok::equalequal: Opc = BO_EQ; break; 14477 case tok::spaceship: Opc = BO_Cmp; break; 14478 case tok::amp: Opc = BO_And; break; 14479 case tok::caret: Opc = BO_Xor; break; 14480 case tok::pipe: Opc = BO_Or; break; 14481 case tok::ampamp: Opc = BO_LAnd; break; 14482 case tok::pipepipe: Opc = BO_LOr; break; 14483 case tok::equal: Opc = BO_Assign; break; 14484 case tok::starequal: Opc = BO_MulAssign; break; 14485 case tok::slashequal: Opc = BO_DivAssign; break; 14486 case tok::percentequal: Opc = BO_RemAssign; break; 14487 case tok::plusequal: Opc = BO_AddAssign; break; 14488 case tok::minusequal: Opc = BO_SubAssign; break; 14489 case tok::lesslessequal: Opc = BO_ShlAssign; break; 14490 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 14491 case tok::ampequal: Opc = BO_AndAssign; break; 14492 case tok::caretequal: Opc = BO_XorAssign; break; 14493 case tok::pipeequal: Opc = BO_OrAssign; break; 14494 case tok::comma: Opc = BO_Comma; break; 14495 } 14496 return Opc; 14497 } 14498 14499 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 14500 tok::TokenKind Kind) { 14501 UnaryOperatorKind Opc; 14502 switch (Kind) { 14503 default: llvm_unreachable("Unknown unary op!"); 14504 case tok::plusplus: Opc = UO_PreInc; break; 14505 case tok::minusminus: Opc = UO_PreDec; break; 14506 case tok::amp: Opc = UO_AddrOf; break; 14507 case tok::star: Opc = UO_Deref; break; 14508 case tok::plus: Opc = UO_Plus; break; 14509 case tok::minus: Opc = UO_Minus; break; 14510 case tok::tilde: Opc = UO_Not; break; 14511 case tok::exclaim: Opc = UO_LNot; break; 14512 case tok::kw___real: Opc = UO_Real; break; 14513 case tok::kw___imag: Opc = UO_Imag; break; 14514 case tok::kw___extension__: Opc = UO_Extension; break; 14515 } 14516 return Opc; 14517 } 14518 14519 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 14520 /// This warning suppressed in the event of macro expansions. 14521 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 14522 SourceLocation OpLoc, bool IsBuiltin) { 14523 if (S.inTemplateInstantiation()) 14524 return; 14525 if (S.isUnevaluatedContext()) 14526 return; 14527 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 14528 return; 14529 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14530 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14531 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14532 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14533 if (!LHSDeclRef || !RHSDeclRef || 14534 LHSDeclRef->getLocation().isMacroID() || 14535 RHSDeclRef->getLocation().isMacroID()) 14536 return; 14537 const ValueDecl *LHSDecl = 14538 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 14539 const ValueDecl *RHSDecl = 14540 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 14541 if (LHSDecl != RHSDecl) 14542 return; 14543 if (LHSDecl->getType().isVolatileQualified()) 14544 return; 14545 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 14546 if (RefTy->getPointeeType().isVolatileQualified()) 14547 return; 14548 14549 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 14550 : diag::warn_self_assignment_overloaded) 14551 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 14552 << RHSExpr->getSourceRange(); 14553 } 14554 14555 /// Check if a bitwise-& is performed on an Objective-C pointer. This 14556 /// is usually indicative of introspection within the Objective-C pointer. 14557 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 14558 SourceLocation OpLoc) { 14559 if (!S.getLangOpts().ObjC) 14560 return; 14561 14562 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 14563 const Expr *LHS = L.get(); 14564 const Expr *RHS = R.get(); 14565 14566 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 14567 ObjCPointerExpr = LHS; 14568 OtherExpr = RHS; 14569 } 14570 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 14571 ObjCPointerExpr = RHS; 14572 OtherExpr = LHS; 14573 } 14574 14575 // This warning is deliberately made very specific to reduce false 14576 // positives with logic that uses '&' for hashing. This logic mainly 14577 // looks for code trying to introspect into tagged pointers, which 14578 // code should generally never do. 14579 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 14580 unsigned Diag = diag::warn_objc_pointer_masking; 14581 // Determine if we are introspecting the result of performSelectorXXX. 14582 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 14583 // Special case messages to -performSelector and friends, which 14584 // can return non-pointer values boxed in a pointer value. 14585 // Some clients may wish to silence warnings in this subcase. 14586 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 14587 Selector S = ME->getSelector(); 14588 StringRef SelArg0 = S.getNameForSlot(0); 14589 if (SelArg0.startswith("performSelector")) 14590 Diag = diag::warn_objc_pointer_masking_performSelector; 14591 } 14592 14593 S.Diag(OpLoc, Diag) 14594 << ObjCPointerExpr->getSourceRange(); 14595 } 14596 } 14597 14598 static NamedDecl *getDeclFromExpr(Expr *E) { 14599 if (!E) 14600 return nullptr; 14601 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 14602 return DRE->getDecl(); 14603 if (auto *ME = dyn_cast<MemberExpr>(E)) 14604 return ME->getMemberDecl(); 14605 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 14606 return IRE->getDecl(); 14607 return nullptr; 14608 } 14609 14610 // This helper function promotes a binary operator's operands (which are of a 14611 // half vector type) to a vector of floats and then truncates the result to 14612 // a vector of either half or short. 14613 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 14614 BinaryOperatorKind Opc, QualType ResultTy, 14615 ExprValueKind VK, ExprObjectKind OK, 14616 bool IsCompAssign, SourceLocation OpLoc, 14617 FPOptionsOverride FPFeatures) { 14618 auto &Context = S.getASTContext(); 14619 assert((isVector(ResultTy, Context.HalfTy) || 14620 isVector(ResultTy, Context.ShortTy)) && 14621 "Result must be a vector of half or short"); 14622 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 14623 isVector(RHS.get()->getType(), Context.HalfTy) && 14624 "both operands expected to be a half vector"); 14625 14626 RHS = convertVector(RHS.get(), Context.FloatTy, S); 14627 QualType BinOpResTy = RHS.get()->getType(); 14628 14629 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 14630 // change BinOpResTy to a vector of ints. 14631 if (isVector(ResultTy, Context.ShortTy)) 14632 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 14633 14634 if (IsCompAssign) 14635 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14636 ResultTy, VK, OK, OpLoc, FPFeatures, 14637 BinOpResTy, BinOpResTy); 14638 14639 LHS = convertVector(LHS.get(), Context.FloatTy, S); 14640 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14641 BinOpResTy, VK, OK, OpLoc, FPFeatures); 14642 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 14643 } 14644 14645 static std::pair<ExprResult, ExprResult> 14646 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 14647 Expr *RHSExpr) { 14648 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14649 if (!S.Context.isDependenceAllowed()) { 14650 // C cannot handle TypoExpr nodes on either side of a binop because it 14651 // doesn't handle dependent types properly, so make sure any TypoExprs have 14652 // been dealt with before checking the operands. 14653 LHS = S.CorrectDelayedTyposInExpr(LHS); 14654 RHS = S.CorrectDelayedTyposInExpr( 14655 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 14656 [Opc, LHS](Expr *E) { 14657 if (Opc != BO_Assign) 14658 return ExprResult(E); 14659 // Avoid correcting the RHS to the same Expr as the LHS. 14660 Decl *D = getDeclFromExpr(E); 14661 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 14662 }); 14663 } 14664 return std::make_pair(LHS, RHS); 14665 } 14666 14667 /// Returns true if conversion between vectors of halfs and vectors of floats 14668 /// is needed. 14669 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 14670 Expr *E0, Expr *E1 = nullptr) { 14671 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 14672 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 14673 return false; 14674 14675 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 14676 QualType Ty = E->IgnoreImplicit()->getType(); 14677 14678 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 14679 // to vectors of floats. Although the element type of the vectors is __fp16, 14680 // the vectors shouldn't be treated as storage-only types. See the 14681 // discussion here: https://reviews.llvm.org/rG825235c140e7 14682 if (const VectorType *VT = Ty->getAs<VectorType>()) { 14683 if (VT->getVectorKind() == VectorType::NeonVector) 14684 return false; 14685 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 14686 } 14687 return false; 14688 }; 14689 14690 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 14691 } 14692 14693 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 14694 /// operator @p Opc at location @c TokLoc. This routine only supports 14695 /// built-in operations; ActOnBinOp handles overloaded operators. 14696 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 14697 BinaryOperatorKind Opc, 14698 Expr *LHSExpr, Expr *RHSExpr) { 14699 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 14700 // The syntax only allows initializer lists on the RHS of assignment, 14701 // so we don't need to worry about accepting invalid code for 14702 // non-assignment operators. 14703 // C++11 5.17p9: 14704 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 14705 // of x = {} is x = T(). 14706 InitializationKind Kind = InitializationKind::CreateDirectList( 14707 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14708 InitializedEntity Entity = 14709 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 14710 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 14711 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 14712 if (Init.isInvalid()) 14713 return Init; 14714 RHSExpr = Init.get(); 14715 } 14716 14717 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14718 QualType ResultTy; // Result type of the binary operator. 14719 // The following two variables are used for compound assignment operators 14720 QualType CompLHSTy; // Type of LHS after promotions for computation 14721 QualType CompResultTy; // Type of computation result 14722 ExprValueKind VK = VK_PRValue; 14723 ExprObjectKind OK = OK_Ordinary; 14724 bool ConvertHalfVec = false; 14725 14726 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14727 if (!LHS.isUsable() || !RHS.isUsable()) 14728 return ExprError(); 14729 14730 if (getLangOpts().OpenCL) { 14731 QualType LHSTy = LHSExpr->getType(); 14732 QualType RHSTy = RHSExpr->getType(); 14733 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14734 // the ATOMIC_VAR_INIT macro. 14735 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14736 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14737 if (BO_Assign == Opc) 14738 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14739 else 14740 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14741 return ExprError(); 14742 } 14743 14744 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14745 // only with a builtin functions and therefore should be disallowed here. 14746 if (LHSTy->isImageType() || RHSTy->isImageType() || 14747 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14748 LHSTy->isPipeType() || RHSTy->isPipeType() || 14749 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14750 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14751 return ExprError(); 14752 } 14753 } 14754 14755 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14756 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14757 14758 switch (Opc) { 14759 case BO_Assign: 14760 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14761 if (getLangOpts().CPlusPlus && 14762 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14763 VK = LHS.get()->getValueKind(); 14764 OK = LHS.get()->getObjectKind(); 14765 } 14766 if (!ResultTy.isNull()) { 14767 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14768 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14769 14770 // Avoid copying a block to the heap if the block is assigned to a local 14771 // auto variable that is declared in the same scope as the block. This 14772 // optimization is unsafe if the local variable is declared in an outer 14773 // scope. For example: 14774 // 14775 // BlockTy b; 14776 // { 14777 // b = ^{...}; 14778 // } 14779 // // It is unsafe to invoke the block here if it wasn't copied to the 14780 // // heap. 14781 // b(); 14782 14783 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14784 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14785 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14786 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14787 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14788 14789 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14790 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14791 NTCUC_Assignment, NTCUK_Copy); 14792 } 14793 RecordModifiableNonNullParam(*this, LHS.get()); 14794 break; 14795 case BO_PtrMemD: 14796 case BO_PtrMemI: 14797 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14798 Opc == BO_PtrMemI); 14799 break; 14800 case BO_Mul: 14801 case BO_Div: 14802 ConvertHalfVec = true; 14803 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14804 Opc == BO_Div); 14805 break; 14806 case BO_Rem: 14807 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14808 break; 14809 case BO_Add: 14810 ConvertHalfVec = true; 14811 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14812 break; 14813 case BO_Sub: 14814 ConvertHalfVec = true; 14815 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14816 break; 14817 case BO_Shl: 14818 case BO_Shr: 14819 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14820 break; 14821 case BO_LE: 14822 case BO_LT: 14823 case BO_GE: 14824 case BO_GT: 14825 ConvertHalfVec = true; 14826 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14827 break; 14828 case BO_EQ: 14829 case BO_NE: 14830 ConvertHalfVec = true; 14831 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14832 break; 14833 case BO_Cmp: 14834 ConvertHalfVec = true; 14835 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14836 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14837 break; 14838 case BO_And: 14839 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14840 LLVM_FALLTHROUGH; 14841 case BO_Xor: 14842 case BO_Or: 14843 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14844 break; 14845 case BO_LAnd: 14846 case BO_LOr: 14847 ConvertHalfVec = true; 14848 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14849 break; 14850 case BO_MulAssign: 14851 case BO_DivAssign: 14852 ConvertHalfVec = true; 14853 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14854 Opc == BO_DivAssign); 14855 CompLHSTy = CompResultTy; 14856 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14857 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14858 break; 14859 case BO_RemAssign: 14860 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14861 CompLHSTy = CompResultTy; 14862 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14863 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14864 break; 14865 case BO_AddAssign: 14866 ConvertHalfVec = true; 14867 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14868 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14869 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14870 break; 14871 case BO_SubAssign: 14872 ConvertHalfVec = true; 14873 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14874 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14875 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14876 break; 14877 case BO_ShlAssign: 14878 case BO_ShrAssign: 14879 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14880 CompLHSTy = CompResultTy; 14881 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14882 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14883 break; 14884 case BO_AndAssign: 14885 case BO_OrAssign: // fallthrough 14886 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14887 LLVM_FALLTHROUGH; 14888 case BO_XorAssign: 14889 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14890 CompLHSTy = CompResultTy; 14891 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14892 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14893 break; 14894 case BO_Comma: 14895 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14896 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14897 VK = RHS.get()->getValueKind(); 14898 OK = RHS.get()->getObjectKind(); 14899 } 14900 break; 14901 } 14902 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14903 return ExprError(); 14904 14905 // Some of the binary operations require promoting operands of half vector to 14906 // float vectors and truncating the result back to half vector. For now, we do 14907 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14908 // arm64). 14909 assert( 14910 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14911 isVector(LHS.get()->getType(), Context.HalfTy)) && 14912 "both sides are half vectors or neither sides are"); 14913 ConvertHalfVec = 14914 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14915 14916 // Check for array bounds violations for both sides of the BinaryOperator 14917 CheckArrayAccess(LHS.get()); 14918 CheckArrayAccess(RHS.get()); 14919 14920 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14921 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14922 &Context.Idents.get("object_setClass"), 14923 SourceLocation(), LookupOrdinaryName); 14924 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14925 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14926 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14927 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14928 "object_setClass(") 14929 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14930 ",") 14931 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14932 } 14933 else 14934 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14935 } 14936 else if (const ObjCIvarRefExpr *OIRE = 14937 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14938 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14939 14940 // Opc is not a compound assignment if CompResultTy is null. 14941 if (CompResultTy.isNull()) { 14942 if (ConvertHalfVec) 14943 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14944 OpLoc, CurFPFeatureOverrides()); 14945 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14946 VK, OK, OpLoc, CurFPFeatureOverrides()); 14947 } 14948 14949 // Handle compound assignments. 14950 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14951 OK_ObjCProperty) { 14952 VK = VK_LValue; 14953 OK = LHS.get()->getObjectKind(); 14954 } 14955 14956 // The LHS is not converted to the result type for fixed-point compound 14957 // assignment as the common type is computed on demand. Reset the CompLHSTy 14958 // to the LHS type we would have gotten after unary conversions. 14959 if (CompResultTy->isFixedPointType()) 14960 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14961 14962 if (ConvertHalfVec) 14963 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14964 OpLoc, CurFPFeatureOverrides()); 14965 14966 return CompoundAssignOperator::Create( 14967 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14968 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14969 } 14970 14971 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14972 /// operators are mixed in a way that suggests that the programmer forgot that 14973 /// comparison operators have higher precedence. The most typical example of 14974 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14975 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14976 SourceLocation OpLoc, Expr *LHSExpr, 14977 Expr *RHSExpr) { 14978 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14979 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14980 14981 // Check that one of the sides is a comparison operator and the other isn't. 14982 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14983 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14984 if (isLeftComp == isRightComp) 14985 return; 14986 14987 // Bitwise operations are sometimes used as eager logical ops. 14988 // Don't diagnose this. 14989 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14990 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14991 if (isLeftBitwise || isRightBitwise) 14992 return; 14993 14994 SourceRange DiagRange = isLeftComp 14995 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14996 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14997 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14998 SourceRange ParensRange = 14999 isLeftComp 15000 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 15001 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 15002 15003 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 15004 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 15005 SuggestParentheses(Self, OpLoc, 15006 Self.PDiag(diag::note_precedence_silence) << OpStr, 15007 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 15008 SuggestParentheses(Self, OpLoc, 15009 Self.PDiag(diag::note_precedence_bitwise_first) 15010 << BinaryOperator::getOpcodeStr(Opc), 15011 ParensRange); 15012 } 15013 15014 /// It accepts a '&&' expr that is inside a '||' one. 15015 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 15016 /// in parentheses. 15017 static void 15018 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 15019 BinaryOperator *Bop) { 15020 assert(Bop->getOpcode() == BO_LAnd); 15021 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 15022 << Bop->getSourceRange() << OpLoc; 15023 SuggestParentheses(Self, Bop->getOperatorLoc(), 15024 Self.PDiag(diag::note_precedence_silence) 15025 << Bop->getOpcodeStr(), 15026 Bop->getSourceRange()); 15027 } 15028 15029 /// Returns true if the given expression can be evaluated as a constant 15030 /// 'true'. 15031 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 15032 bool Res; 15033 return !E->isValueDependent() && 15034 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 15035 } 15036 15037 /// Returns true if the given expression can be evaluated as a constant 15038 /// 'false'. 15039 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 15040 bool Res; 15041 return !E->isValueDependent() && 15042 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 15043 } 15044 15045 /// Look for '&&' in the left hand of a '||' expr. 15046 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 15047 Expr *LHSExpr, Expr *RHSExpr) { 15048 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 15049 if (Bop->getOpcode() == BO_LAnd) { 15050 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 15051 if (EvaluatesAsFalse(S, RHSExpr)) 15052 return; 15053 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 15054 if (!EvaluatesAsTrue(S, Bop->getLHS())) 15055 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 15056 } else if (Bop->getOpcode() == BO_LOr) { 15057 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 15058 // If it's "a || b && 1 || c" we didn't warn earlier for 15059 // "a || b && 1", but warn now. 15060 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 15061 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 15062 } 15063 } 15064 } 15065 } 15066 15067 /// Look for '&&' in the right hand of a '||' expr. 15068 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 15069 Expr *LHSExpr, Expr *RHSExpr) { 15070 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 15071 if (Bop->getOpcode() == BO_LAnd) { 15072 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 15073 if (EvaluatesAsFalse(S, LHSExpr)) 15074 return; 15075 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 15076 if (!EvaluatesAsTrue(S, Bop->getRHS())) 15077 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 15078 } 15079 } 15080 } 15081 15082 /// Look for bitwise op in the left or right hand of a bitwise op with 15083 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 15084 /// the '&' expression in parentheses. 15085 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 15086 SourceLocation OpLoc, Expr *SubExpr) { 15087 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 15088 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 15089 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 15090 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 15091 << Bop->getSourceRange() << OpLoc; 15092 SuggestParentheses(S, Bop->getOperatorLoc(), 15093 S.PDiag(diag::note_precedence_silence) 15094 << Bop->getOpcodeStr(), 15095 Bop->getSourceRange()); 15096 } 15097 } 15098 } 15099 15100 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 15101 Expr *SubExpr, StringRef Shift) { 15102 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 15103 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 15104 StringRef Op = Bop->getOpcodeStr(); 15105 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 15106 << Bop->getSourceRange() << OpLoc << Shift << Op; 15107 SuggestParentheses(S, Bop->getOperatorLoc(), 15108 S.PDiag(diag::note_precedence_silence) << Op, 15109 Bop->getSourceRange()); 15110 } 15111 } 15112 } 15113 15114 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 15115 Expr *LHSExpr, Expr *RHSExpr) { 15116 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 15117 if (!OCE) 15118 return; 15119 15120 FunctionDecl *FD = OCE->getDirectCallee(); 15121 if (!FD || !FD->isOverloadedOperator()) 15122 return; 15123 15124 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 15125 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 15126 return; 15127 15128 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 15129 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 15130 << (Kind == OO_LessLess); 15131 SuggestParentheses(S, OCE->getOperatorLoc(), 15132 S.PDiag(diag::note_precedence_silence) 15133 << (Kind == OO_LessLess ? "<<" : ">>"), 15134 OCE->getSourceRange()); 15135 SuggestParentheses( 15136 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 15137 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 15138 } 15139 15140 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 15141 /// precedence. 15142 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 15143 SourceLocation OpLoc, Expr *LHSExpr, 15144 Expr *RHSExpr){ 15145 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 15146 if (BinaryOperator::isBitwiseOp(Opc)) 15147 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 15148 15149 // Diagnose "arg1 & arg2 | arg3" 15150 if ((Opc == BO_Or || Opc == BO_Xor) && 15151 !OpLoc.isMacroID()/* Don't warn in macros. */) { 15152 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 15153 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 15154 } 15155 15156 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 15157 // We don't warn for 'assert(a || b && "bad")' since this is safe. 15158 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 15159 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 15160 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 15161 } 15162 15163 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 15164 || Opc == BO_Shr) { 15165 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 15166 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 15167 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 15168 } 15169 15170 // Warn on overloaded shift operators and comparisons, such as: 15171 // cout << 5 == 4; 15172 if (BinaryOperator::isComparisonOp(Opc)) 15173 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 15174 } 15175 15176 // Binary Operators. 'Tok' is the token for the operator. 15177 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 15178 tok::TokenKind Kind, 15179 Expr *LHSExpr, Expr *RHSExpr) { 15180 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 15181 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 15182 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 15183 15184 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 15185 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 15186 15187 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 15188 } 15189 15190 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 15191 UnresolvedSetImpl &Functions) { 15192 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 15193 if (OverOp != OO_None && OverOp != OO_Equal) 15194 LookupOverloadedOperatorName(OverOp, S, Functions); 15195 15196 // In C++20 onwards, we may have a second operator to look up. 15197 if (getLangOpts().CPlusPlus20) { 15198 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 15199 LookupOverloadedOperatorName(ExtraOp, S, Functions); 15200 } 15201 } 15202 15203 /// Build an overloaded binary operator expression in the given scope. 15204 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 15205 BinaryOperatorKind Opc, 15206 Expr *LHS, Expr *RHS) { 15207 switch (Opc) { 15208 case BO_Assign: 15209 case BO_DivAssign: 15210 case BO_RemAssign: 15211 case BO_SubAssign: 15212 case BO_AndAssign: 15213 case BO_OrAssign: 15214 case BO_XorAssign: 15215 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 15216 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 15217 break; 15218 default: 15219 break; 15220 } 15221 15222 // Find all of the overloaded operators visible from this point. 15223 UnresolvedSet<16> Functions; 15224 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 15225 15226 // Build the (potentially-overloaded, potentially-dependent) 15227 // binary operation. 15228 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 15229 } 15230 15231 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 15232 BinaryOperatorKind Opc, 15233 Expr *LHSExpr, Expr *RHSExpr) { 15234 ExprResult LHS, RHS; 15235 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 15236 if (!LHS.isUsable() || !RHS.isUsable()) 15237 return ExprError(); 15238 LHSExpr = LHS.get(); 15239 RHSExpr = RHS.get(); 15240 15241 // We want to end up calling one of checkPseudoObjectAssignment 15242 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 15243 // both expressions are overloadable or either is type-dependent), 15244 // or CreateBuiltinBinOp (in any other case). We also want to get 15245 // any placeholder types out of the way. 15246 15247 // Handle pseudo-objects in the LHS. 15248 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 15249 // Assignments with a pseudo-object l-value need special analysis. 15250 if (pty->getKind() == BuiltinType::PseudoObject && 15251 BinaryOperator::isAssignmentOp(Opc)) 15252 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 15253 15254 // Don't resolve overloads if the other type is overloadable. 15255 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 15256 // We can't actually test that if we still have a placeholder, 15257 // though. Fortunately, none of the exceptions we see in that 15258 // code below are valid when the LHS is an overload set. Note 15259 // that an overload set can be dependently-typed, but it never 15260 // instantiates to having an overloadable type. 15261 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 15262 if (resolvedRHS.isInvalid()) return ExprError(); 15263 RHSExpr = resolvedRHS.get(); 15264 15265 if (RHSExpr->isTypeDependent() || 15266 RHSExpr->getType()->isOverloadableType()) 15267 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15268 } 15269 15270 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 15271 // template, diagnose the missing 'template' keyword instead of diagnosing 15272 // an invalid use of a bound member function. 15273 // 15274 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 15275 // to C++1z [over.over]/1.4, but we already checked for that case above. 15276 if (Opc == BO_LT && inTemplateInstantiation() && 15277 (pty->getKind() == BuiltinType::BoundMember || 15278 pty->getKind() == BuiltinType::Overload)) { 15279 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 15280 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 15281 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 15282 return isa<FunctionTemplateDecl>(ND); 15283 })) { 15284 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 15285 : OE->getNameLoc(), 15286 diag::err_template_kw_missing) 15287 << OE->getName().getAsString() << ""; 15288 return ExprError(); 15289 } 15290 } 15291 15292 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 15293 if (LHS.isInvalid()) return ExprError(); 15294 LHSExpr = LHS.get(); 15295 } 15296 15297 // Handle pseudo-objects in the RHS. 15298 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 15299 // An overload in the RHS can potentially be resolved by the type 15300 // being assigned to. 15301 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 15302 if (getLangOpts().CPlusPlus && 15303 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 15304 LHSExpr->getType()->isOverloadableType())) 15305 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15306 15307 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 15308 } 15309 15310 // Don't resolve overloads if the other type is overloadable. 15311 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 15312 LHSExpr->getType()->isOverloadableType()) 15313 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15314 15315 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 15316 if (!resolvedRHS.isUsable()) return ExprError(); 15317 RHSExpr = resolvedRHS.get(); 15318 } 15319 15320 if (getLangOpts().CPlusPlus) { 15321 // If either expression is type-dependent, always build an 15322 // overloaded op. 15323 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 15324 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15325 15326 // Otherwise, build an overloaded op if either expression has an 15327 // overloadable type. 15328 if (LHSExpr->getType()->isOverloadableType() || 15329 RHSExpr->getType()->isOverloadableType()) 15330 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15331 } 15332 15333 if (getLangOpts().RecoveryAST && 15334 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 15335 assert(!getLangOpts().CPlusPlus); 15336 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 15337 "Should only occur in error-recovery path."); 15338 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 15339 // C [6.15.16] p3: 15340 // An assignment expression has the value of the left operand after the 15341 // assignment, but is not an lvalue. 15342 return CompoundAssignOperator::Create( 15343 Context, LHSExpr, RHSExpr, Opc, 15344 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 15345 OpLoc, CurFPFeatureOverrides()); 15346 QualType ResultType; 15347 switch (Opc) { 15348 case BO_Assign: 15349 ResultType = LHSExpr->getType().getUnqualifiedType(); 15350 break; 15351 case BO_LT: 15352 case BO_GT: 15353 case BO_LE: 15354 case BO_GE: 15355 case BO_EQ: 15356 case BO_NE: 15357 case BO_LAnd: 15358 case BO_LOr: 15359 // These operators have a fixed result type regardless of operands. 15360 ResultType = Context.IntTy; 15361 break; 15362 case BO_Comma: 15363 ResultType = RHSExpr->getType(); 15364 break; 15365 default: 15366 ResultType = Context.DependentTy; 15367 break; 15368 } 15369 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 15370 VK_PRValue, OK_Ordinary, OpLoc, 15371 CurFPFeatureOverrides()); 15372 } 15373 15374 // Build a built-in binary operation. 15375 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 15376 } 15377 15378 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 15379 if (T.isNull() || T->isDependentType()) 15380 return false; 15381 15382 if (!T->isPromotableIntegerType()) 15383 return true; 15384 15385 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 15386 } 15387 15388 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 15389 UnaryOperatorKind Opc, 15390 Expr *InputExpr) { 15391 ExprResult Input = InputExpr; 15392 ExprValueKind VK = VK_PRValue; 15393 ExprObjectKind OK = OK_Ordinary; 15394 QualType resultType; 15395 bool CanOverflow = false; 15396 15397 bool ConvertHalfVec = false; 15398 if (getLangOpts().OpenCL) { 15399 QualType Ty = InputExpr->getType(); 15400 // The only legal unary operation for atomics is '&'. 15401 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 15402 // OpenCL special types - image, sampler, pipe, and blocks are to be used 15403 // only with a builtin functions and therefore should be disallowed here. 15404 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 15405 || Ty->isBlockPointerType())) { 15406 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15407 << InputExpr->getType() 15408 << Input.get()->getSourceRange()); 15409 } 15410 } 15411 15412 if (getLangOpts().HLSL) { 15413 if (Opc == UO_AddrOf) 15414 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0); 15415 if (Opc == UO_Deref) 15416 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1); 15417 } 15418 15419 switch (Opc) { 15420 case UO_PreInc: 15421 case UO_PreDec: 15422 case UO_PostInc: 15423 case UO_PostDec: 15424 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 15425 OpLoc, 15426 Opc == UO_PreInc || 15427 Opc == UO_PostInc, 15428 Opc == UO_PreInc || 15429 Opc == UO_PreDec); 15430 CanOverflow = isOverflowingIntegerType(Context, resultType); 15431 break; 15432 case UO_AddrOf: 15433 resultType = CheckAddressOfOperand(Input, OpLoc); 15434 CheckAddressOfNoDeref(InputExpr); 15435 RecordModifiableNonNullParam(*this, InputExpr); 15436 break; 15437 case UO_Deref: { 15438 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 15439 if (Input.isInvalid()) return ExprError(); 15440 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 15441 break; 15442 } 15443 case UO_Plus: 15444 case UO_Minus: 15445 CanOverflow = Opc == UO_Minus && 15446 isOverflowingIntegerType(Context, Input.get()->getType()); 15447 Input = UsualUnaryConversions(Input.get()); 15448 if (Input.isInvalid()) return ExprError(); 15449 // Unary plus and minus require promoting an operand of half vector to a 15450 // float vector and truncating the result back to a half vector. For now, we 15451 // do this only when HalfArgsAndReturns is set (that is, when the target is 15452 // arm or arm64). 15453 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 15454 15455 // If the operand is a half vector, promote it to a float vector. 15456 if (ConvertHalfVec) 15457 Input = convertVector(Input.get(), Context.FloatTy, *this); 15458 resultType = Input.get()->getType(); 15459 if (resultType->isDependentType()) 15460 break; 15461 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 15462 break; 15463 else if (resultType->isVectorType() && 15464 // The z vector extensions don't allow + or - with bool vectors. 15465 (!Context.getLangOpts().ZVector || 15466 resultType->castAs<VectorType>()->getVectorKind() != 15467 VectorType::AltiVecBool)) 15468 break; 15469 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 15470 Opc == UO_Plus && 15471 resultType->isPointerType()) 15472 break; 15473 15474 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15475 << resultType << Input.get()->getSourceRange()); 15476 15477 case UO_Not: // bitwise complement 15478 Input = UsualUnaryConversions(Input.get()); 15479 if (Input.isInvalid()) 15480 return ExprError(); 15481 resultType = Input.get()->getType(); 15482 if (resultType->isDependentType()) 15483 break; 15484 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 15485 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 15486 // C99 does not support '~' for complex conjugation. 15487 Diag(OpLoc, diag::ext_integer_complement_complex) 15488 << resultType << Input.get()->getSourceRange(); 15489 else if (resultType->hasIntegerRepresentation()) 15490 break; 15491 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 15492 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 15493 // on vector float types. 15494 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 15495 if (!T->isIntegerType()) 15496 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15497 << resultType << Input.get()->getSourceRange()); 15498 } else { 15499 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15500 << resultType << Input.get()->getSourceRange()); 15501 } 15502 break; 15503 15504 case UO_LNot: // logical negation 15505 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 15506 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 15507 if (Input.isInvalid()) return ExprError(); 15508 resultType = Input.get()->getType(); 15509 15510 // Though we still have to promote half FP to float... 15511 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 15512 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 15513 resultType = Context.FloatTy; 15514 } 15515 15516 if (resultType->isDependentType()) 15517 break; 15518 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 15519 // C99 6.5.3.3p1: ok, fallthrough; 15520 if (Context.getLangOpts().CPlusPlus) { 15521 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 15522 // operand contextually converted to bool. 15523 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 15524 ScalarTypeToBooleanCastKind(resultType)); 15525 } else if (Context.getLangOpts().OpenCL && 15526 Context.getLangOpts().OpenCLVersion < 120) { 15527 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 15528 // operate on scalar float types. 15529 if (!resultType->isIntegerType() && !resultType->isPointerType()) 15530 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15531 << resultType << Input.get()->getSourceRange()); 15532 } 15533 } else if (resultType->isExtVectorType()) { 15534 if (Context.getLangOpts().OpenCL && 15535 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { 15536 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 15537 // operate on vector float types. 15538 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 15539 if (!T->isIntegerType()) 15540 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15541 << resultType << Input.get()->getSourceRange()); 15542 } 15543 // Vector logical not returns the signed variant of the operand type. 15544 resultType = GetSignedVectorType(resultType); 15545 break; 15546 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 15547 const VectorType *VTy = resultType->castAs<VectorType>(); 15548 if (VTy->getVectorKind() != VectorType::GenericVector) 15549 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15550 << resultType << Input.get()->getSourceRange()); 15551 15552 // Vector logical not returns the signed variant of the operand type. 15553 resultType = GetSignedVectorType(resultType); 15554 break; 15555 } else { 15556 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15557 << resultType << Input.get()->getSourceRange()); 15558 } 15559 15560 // LNot always has type int. C99 6.5.3.3p5. 15561 // In C++, it's bool. C++ 5.3.1p8 15562 resultType = Context.getLogicalOperationType(); 15563 break; 15564 case UO_Real: 15565 case UO_Imag: 15566 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 15567 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 15568 // complex l-values to ordinary l-values and all other values to r-values. 15569 if (Input.isInvalid()) return ExprError(); 15570 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 15571 if (Input.get()->isGLValue() && 15572 Input.get()->getObjectKind() == OK_Ordinary) 15573 VK = Input.get()->getValueKind(); 15574 } else if (!getLangOpts().CPlusPlus) { 15575 // In C, a volatile scalar is read by __imag. In C++, it is not. 15576 Input = DefaultLvalueConversion(Input.get()); 15577 } 15578 break; 15579 case UO_Extension: 15580 resultType = Input.get()->getType(); 15581 VK = Input.get()->getValueKind(); 15582 OK = Input.get()->getObjectKind(); 15583 break; 15584 case UO_Coawait: 15585 // It's unnecessary to represent the pass-through operator co_await in the 15586 // AST; just return the input expression instead. 15587 assert(!Input.get()->getType()->isDependentType() && 15588 "the co_await expression must be non-dependant before " 15589 "building operator co_await"); 15590 return Input; 15591 } 15592 if (resultType.isNull() || Input.isInvalid()) 15593 return ExprError(); 15594 15595 // Check for array bounds violations in the operand of the UnaryOperator, 15596 // except for the '*' and '&' operators that have to be handled specially 15597 // by CheckArrayAccess (as there are special cases like &array[arraysize] 15598 // that are explicitly defined as valid by the standard). 15599 if (Opc != UO_AddrOf && Opc != UO_Deref) 15600 CheckArrayAccess(Input.get()); 15601 15602 auto *UO = 15603 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 15604 OpLoc, CanOverflow, CurFPFeatureOverrides()); 15605 15606 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 15607 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 15608 !isUnevaluatedContext()) 15609 ExprEvalContexts.back().PossibleDerefs.insert(UO); 15610 15611 // Convert the result back to a half vector. 15612 if (ConvertHalfVec) 15613 return convertVector(UO, Context.HalfTy, *this); 15614 return UO; 15615 } 15616 15617 /// Determine whether the given expression is a qualified member 15618 /// access expression, of a form that could be turned into a pointer to member 15619 /// with the address-of operator. 15620 bool Sema::isQualifiedMemberAccess(Expr *E) { 15621 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15622 if (!DRE->getQualifier()) 15623 return false; 15624 15625 ValueDecl *VD = DRE->getDecl(); 15626 if (!VD->isCXXClassMember()) 15627 return false; 15628 15629 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 15630 return true; 15631 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 15632 return Method->isInstance(); 15633 15634 return false; 15635 } 15636 15637 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15638 if (!ULE->getQualifier()) 15639 return false; 15640 15641 for (NamedDecl *D : ULE->decls()) { 15642 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 15643 if (Method->isInstance()) 15644 return true; 15645 } else { 15646 // Overload set does not contain methods. 15647 break; 15648 } 15649 } 15650 15651 return false; 15652 } 15653 15654 return false; 15655 } 15656 15657 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 15658 UnaryOperatorKind Opc, Expr *Input) { 15659 // First things first: handle placeholders so that the 15660 // overloaded-operator check considers the right type. 15661 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 15662 // Increment and decrement of pseudo-object references. 15663 if (pty->getKind() == BuiltinType::PseudoObject && 15664 UnaryOperator::isIncrementDecrementOp(Opc)) 15665 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 15666 15667 // extension is always a builtin operator. 15668 if (Opc == UO_Extension) 15669 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15670 15671 // & gets special logic for several kinds of placeholder. 15672 // The builtin code knows what to do. 15673 if (Opc == UO_AddrOf && 15674 (pty->getKind() == BuiltinType::Overload || 15675 pty->getKind() == BuiltinType::UnknownAny || 15676 pty->getKind() == BuiltinType::BoundMember)) 15677 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15678 15679 // Anything else needs to be handled now. 15680 ExprResult Result = CheckPlaceholderExpr(Input); 15681 if (Result.isInvalid()) return ExprError(); 15682 Input = Result.get(); 15683 } 15684 15685 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 15686 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 15687 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 15688 // Find all of the overloaded operators visible from this point. 15689 UnresolvedSet<16> Functions; 15690 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 15691 if (S && OverOp != OO_None) 15692 LookupOverloadedOperatorName(OverOp, S, Functions); 15693 15694 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 15695 } 15696 15697 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15698 } 15699 15700 // Unary Operators. 'Tok' is the token for the operator. 15701 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 15702 tok::TokenKind Op, Expr *Input) { 15703 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 15704 } 15705 15706 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 15707 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 15708 LabelDecl *TheDecl) { 15709 TheDecl->markUsed(Context); 15710 // Create the AST node. The address of a label always has type 'void*'. 15711 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 15712 Context.getPointerType(Context.VoidTy)); 15713 } 15714 15715 void Sema::ActOnStartStmtExpr() { 15716 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15717 } 15718 15719 void Sema::ActOnStmtExprError() { 15720 // Note that function is also called by TreeTransform when leaving a 15721 // StmtExpr scope without rebuilding anything. 15722 15723 DiscardCleanupsInEvaluationContext(); 15724 PopExpressionEvaluationContext(); 15725 } 15726 15727 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15728 SourceLocation RPLoc) { 15729 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15730 } 15731 15732 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15733 SourceLocation RPLoc, unsigned TemplateDepth) { 15734 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15735 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15736 15737 if (hasAnyUnrecoverableErrorsInThisFunction()) 15738 DiscardCleanupsInEvaluationContext(); 15739 assert(!Cleanup.exprNeedsCleanups() && 15740 "cleanups within StmtExpr not correctly bound!"); 15741 PopExpressionEvaluationContext(); 15742 15743 // FIXME: there are a variety of strange constraints to enforce here, for 15744 // example, it is not possible to goto into a stmt expression apparently. 15745 // More semantic analysis is needed. 15746 15747 // If there are sub-stmts in the compound stmt, take the type of the last one 15748 // as the type of the stmtexpr. 15749 QualType Ty = Context.VoidTy; 15750 bool StmtExprMayBindToTemp = false; 15751 if (!Compound->body_empty()) { 15752 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15753 if (const auto *LastStmt = 15754 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15755 if (const Expr *Value = LastStmt->getExprStmt()) { 15756 StmtExprMayBindToTemp = true; 15757 Ty = Value->getType(); 15758 } 15759 } 15760 } 15761 15762 // FIXME: Check that expression type is complete/non-abstract; statement 15763 // expressions are not lvalues. 15764 Expr *ResStmtExpr = 15765 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15766 if (StmtExprMayBindToTemp) 15767 return MaybeBindToTemporary(ResStmtExpr); 15768 return ResStmtExpr; 15769 } 15770 15771 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15772 if (ER.isInvalid()) 15773 return ExprError(); 15774 15775 // Do function/array conversion on the last expression, but not 15776 // lvalue-to-rvalue. However, initialize an unqualified type. 15777 ER = DefaultFunctionArrayConversion(ER.get()); 15778 if (ER.isInvalid()) 15779 return ExprError(); 15780 Expr *E = ER.get(); 15781 15782 if (E->isTypeDependent()) 15783 return E; 15784 15785 // In ARC, if the final expression ends in a consume, splice 15786 // the consume out and bind it later. In the alternate case 15787 // (when dealing with a retainable type), the result 15788 // initialization will create a produce. In both cases the 15789 // result will be +1, and we'll need to balance that out with 15790 // a bind. 15791 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15792 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15793 return Cast->getSubExpr(); 15794 15795 // FIXME: Provide a better location for the initialization. 15796 return PerformCopyInitialization( 15797 InitializedEntity::InitializeStmtExprResult( 15798 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15799 SourceLocation(), E); 15800 } 15801 15802 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15803 TypeSourceInfo *TInfo, 15804 ArrayRef<OffsetOfComponent> Components, 15805 SourceLocation RParenLoc) { 15806 QualType ArgTy = TInfo->getType(); 15807 bool Dependent = ArgTy->isDependentType(); 15808 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15809 15810 // We must have at least one component that refers to the type, and the first 15811 // one is known to be a field designator. Verify that the ArgTy represents 15812 // a struct/union/class. 15813 if (!Dependent && !ArgTy->isRecordType()) 15814 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15815 << ArgTy << TypeRange); 15816 15817 // Type must be complete per C99 7.17p3 because a declaring a variable 15818 // with an incomplete type would be ill-formed. 15819 if (!Dependent 15820 && RequireCompleteType(BuiltinLoc, ArgTy, 15821 diag::err_offsetof_incomplete_type, TypeRange)) 15822 return ExprError(); 15823 15824 bool DidWarnAboutNonPOD = false; 15825 QualType CurrentType = ArgTy; 15826 SmallVector<OffsetOfNode, 4> Comps; 15827 SmallVector<Expr*, 4> Exprs; 15828 for (const OffsetOfComponent &OC : Components) { 15829 if (OC.isBrackets) { 15830 // Offset of an array sub-field. TODO: Should we allow vector elements? 15831 if (!CurrentType->isDependentType()) { 15832 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15833 if(!AT) 15834 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15835 << CurrentType); 15836 CurrentType = AT->getElementType(); 15837 } else 15838 CurrentType = Context.DependentTy; 15839 15840 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15841 if (IdxRval.isInvalid()) 15842 return ExprError(); 15843 Expr *Idx = IdxRval.get(); 15844 15845 // The expression must be an integral expression. 15846 // FIXME: An integral constant expression? 15847 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15848 !Idx->getType()->isIntegerType()) 15849 return ExprError( 15850 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15851 << Idx->getSourceRange()); 15852 15853 // Record this array index. 15854 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15855 Exprs.push_back(Idx); 15856 continue; 15857 } 15858 15859 // Offset of a field. 15860 if (CurrentType->isDependentType()) { 15861 // We have the offset of a field, but we can't look into the dependent 15862 // type. Just record the identifier of the field. 15863 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15864 CurrentType = Context.DependentTy; 15865 continue; 15866 } 15867 15868 // We need to have a complete type to look into. 15869 if (RequireCompleteType(OC.LocStart, CurrentType, 15870 diag::err_offsetof_incomplete_type)) 15871 return ExprError(); 15872 15873 // Look for the designated field. 15874 const RecordType *RC = CurrentType->getAs<RecordType>(); 15875 if (!RC) 15876 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15877 << CurrentType); 15878 RecordDecl *RD = RC->getDecl(); 15879 15880 // C++ [lib.support.types]p5: 15881 // The macro offsetof accepts a restricted set of type arguments in this 15882 // International Standard. type shall be a POD structure or a POD union 15883 // (clause 9). 15884 // C++11 [support.types]p4: 15885 // If type is not a standard-layout class (Clause 9), the results are 15886 // undefined. 15887 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15888 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15889 unsigned DiagID = 15890 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15891 : diag::ext_offsetof_non_pod_type; 15892 15893 if (!IsSafe && !DidWarnAboutNonPOD && 15894 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15895 PDiag(DiagID) 15896 << SourceRange(Components[0].LocStart, OC.LocEnd) 15897 << CurrentType)) 15898 DidWarnAboutNonPOD = true; 15899 } 15900 15901 // Look for the field. 15902 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15903 LookupQualifiedName(R, RD); 15904 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15905 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15906 if (!MemberDecl) { 15907 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15908 MemberDecl = IndirectMemberDecl->getAnonField(); 15909 } 15910 15911 if (!MemberDecl) 15912 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15913 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15914 OC.LocEnd)); 15915 15916 // C99 7.17p3: 15917 // (If the specified member is a bit-field, the behavior is undefined.) 15918 // 15919 // We diagnose this as an error. 15920 if (MemberDecl->isBitField()) { 15921 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15922 << MemberDecl->getDeclName() 15923 << SourceRange(BuiltinLoc, RParenLoc); 15924 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15925 return ExprError(); 15926 } 15927 15928 RecordDecl *Parent = MemberDecl->getParent(); 15929 if (IndirectMemberDecl) 15930 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15931 15932 // If the member was found in a base class, introduce OffsetOfNodes for 15933 // the base class indirections. 15934 CXXBasePaths Paths; 15935 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15936 Paths)) { 15937 if (Paths.getDetectedVirtual()) { 15938 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15939 << MemberDecl->getDeclName() 15940 << SourceRange(BuiltinLoc, RParenLoc); 15941 return ExprError(); 15942 } 15943 15944 CXXBasePath &Path = Paths.front(); 15945 for (const CXXBasePathElement &B : Path) 15946 Comps.push_back(OffsetOfNode(B.Base)); 15947 } 15948 15949 if (IndirectMemberDecl) { 15950 for (auto *FI : IndirectMemberDecl->chain()) { 15951 assert(isa<FieldDecl>(FI)); 15952 Comps.push_back(OffsetOfNode(OC.LocStart, 15953 cast<FieldDecl>(FI), OC.LocEnd)); 15954 } 15955 } else 15956 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15957 15958 CurrentType = MemberDecl->getType().getNonReferenceType(); 15959 } 15960 15961 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15962 Comps, Exprs, RParenLoc); 15963 } 15964 15965 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15966 SourceLocation BuiltinLoc, 15967 SourceLocation TypeLoc, 15968 ParsedType ParsedArgTy, 15969 ArrayRef<OffsetOfComponent> Components, 15970 SourceLocation RParenLoc) { 15971 15972 TypeSourceInfo *ArgTInfo; 15973 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15974 if (ArgTy.isNull()) 15975 return ExprError(); 15976 15977 if (!ArgTInfo) 15978 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15979 15980 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15981 } 15982 15983 15984 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15985 Expr *CondExpr, 15986 Expr *LHSExpr, Expr *RHSExpr, 15987 SourceLocation RPLoc) { 15988 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15989 15990 ExprValueKind VK = VK_PRValue; 15991 ExprObjectKind OK = OK_Ordinary; 15992 QualType resType; 15993 bool CondIsTrue = false; 15994 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15995 resType = Context.DependentTy; 15996 } else { 15997 // The conditional expression is required to be a constant expression. 15998 llvm::APSInt condEval(32); 15999 ExprResult CondICE = VerifyIntegerConstantExpression( 16000 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 16001 if (CondICE.isInvalid()) 16002 return ExprError(); 16003 CondExpr = CondICE.get(); 16004 CondIsTrue = condEval.getZExtValue(); 16005 16006 // If the condition is > zero, then the AST type is the same as the LHSExpr. 16007 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 16008 16009 resType = ActiveExpr->getType(); 16010 VK = ActiveExpr->getValueKind(); 16011 OK = ActiveExpr->getObjectKind(); 16012 } 16013 16014 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 16015 resType, VK, OK, RPLoc, CondIsTrue); 16016 } 16017 16018 //===----------------------------------------------------------------------===// 16019 // Clang Extensions. 16020 //===----------------------------------------------------------------------===// 16021 16022 /// ActOnBlockStart - This callback is invoked when a block literal is started. 16023 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 16024 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 16025 16026 if (LangOpts.CPlusPlus) { 16027 MangleNumberingContext *MCtx; 16028 Decl *ManglingContextDecl; 16029 std::tie(MCtx, ManglingContextDecl) = 16030 getCurrentMangleNumberContext(Block->getDeclContext()); 16031 if (MCtx) { 16032 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 16033 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 16034 } 16035 } 16036 16037 PushBlockScope(CurScope, Block); 16038 CurContext->addDecl(Block); 16039 if (CurScope) 16040 PushDeclContext(CurScope, Block); 16041 else 16042 CurContext = Block; 16043 16044 getCurBlock()->HasImplicitReturnType = true; 16045 16046 // Enter a new evaluation context to insulate the block from any 16047 // cleanups from the enclosing full-expression. 16048 PushExpressionEvaluationContext( 16049 ExpressionEvaluationContext::PotentiallyEvaluated); 16050 } 16051 16052 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 16053 Scope *CurScope) { 16054 assert(ParamInfo.getIdentifier() == nullptr && 16055 "block-id should have no identifier!"); 16056 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 16057 BlockScopeInfo *CurBlock = getCurBlock(); 16058 16059 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 16060 QualType T = Sig->getType(); 16061 16062 // FIXME: We should allow unexpanded parameter packs here, but that would, 16063 // in turn, make the block expression contain unexpanded parameter packs. 16064 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 16065 // Drop the parameters. 16066 FunctionProtoType::ExtProtoInfo EPI; 16067 EPI.HasTrailingReturn = false; 16068 EPI.TypeQuals.addConst(); 16069 T = Context.getFunctionType(Context.DependentTy, None, EPI); 16070 Sig = Context.getTrivialTypeSourceInfo(T); 16071 } 16072 16073 // GetTypeForDeclarator always produces a function type for a block 16074 // literal signature. Furthermore, it is always a FunctionProtoType 16075 // unless the function was written with a typedef. 16076 assert(T->isFunctionType() && 16077 "GetTypeForDeclarator made a non-function block signature"); 16078 16079 // Look for an explicit signature in that function type. 16080 FunctionProtoTypeLoc ExplicitSignature; 16081 16082 if ((ExplicitSignature = Sig->getTypeLoc() 16083 .getAsAdjusted<FunctionProtoTypeLoc>())) { 16084 16085 // Check whether that explicit signature was synthesized by 16086 // GetTypeForDeclarator. If so, don't save that as part of the 16087 // written signature. 16088 if (ExplicitSignature.getLocalRangeBegin() == 16089 ExplicitSignature.getLocalRangeEnd()) { 16090 // This would be much cheaper if we stored TypeLocs instead of 16091 // TypeSourceInfos. 16092 TypeLoc Result = ExplicitSignature.getReturnLoc(); 16093 unsigned Size = Result.getFullDataSize(); 16094 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 16095 Sig->getTypeLoc().initializeFullCopy(Result, Size); 16096 16097 ExplicitSignature = FunctionProtoTypeLoc(); 16098 } 16099 } 16100 16101 CurBlock->TheDecl->setSignatureAsWritten(Sig); 16102 CurBlock->FunctionType = T; 16103 16104 const auto *Fn = T->castAs<FunctionType>(); 16105 QualType RetTy = Fn->getReturnType(); 16106 bool isVariadic = 16107 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 16108 16109 CurBlock->TheDecl->setIsVariadic(isVariadic); 16110 16111 // Context.DependentTy is used as a placeholder for a missing block 16112 // return type. TODO: what should we do with declarators like: 16113 // ^ * { ... } 16114 // If the answer is "apply template argument deduction".... 16115 if (RetTy != Context.DependentTy) { 16116 CurBlock->ReturnType = RetTy; 16117 CurBlock->TheDecl->setBlockMissingReturnType(false); 16118 CurBlock->HasImplicitReturnType = false; 16119 } 16120 16121 // Push block parameters from the declarator if we had them. 16122 SmallVector<ParmVarDecl*, 8> Params; 16123 if (ExplicitSignature) { 16124 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 16125 ParmVarDecl *Param = ExplicitSignature.getParam(I); 16126 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 16127 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 16128 // Diagnose this as an extension in C17 and earlier. 16129 if (!getLangOpts().C2x) 16130 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 16131 } 16132 Params.push_back(Param); 16133 } 16134 16135 // Fake up parameter variables if we have a typedef, like 16136 // ^ fntype { ... } 16137 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 16138 for (const auto &I : Fn->param_types()) { 16139 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 16140 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 16141 Params.push_back(Param); 16142 } 16143 } 16144 16145 // Set the parameters on the block decl. 16146 if (!Params.empty()) { 16147 CurBlock->TheDecl->setParams(Params); 16148 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 16149 /*CheckParameterNames=*/false); 16150 } 16151 16152 // Finally we can process decl attributes. 16153 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 16154 16155 // Put the parameter variables in scope. 16156 for (auto AI : CurBlock->TheDecl->parameters()) { 16157 AI->setOwningFunction(CurBlock->TheDecl); 16158 16159 // If this has an identifier, add it to the scope stack. 16160 if (AI->getIdentifier()) { 16161 CheckShadow(CurBlock->TheScope, AI); 16162 16163 PushOnScopeChains(AI, CurBlock->TheScope); 16164 } 16165 } 16166 } 16167 16168 /// ActOnBlockError - If there is an error parsing a block, this callback 16169 /// is invoked to pop the information about the block from the action impl. 16170 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 16171 // Leave the expression-evaluation context. 16172 DiscardCleanupsInEvaluationContext(); 16173 PopExpressionEvaluationContext(); 16174 16175 // Pop off CurBlock, handle nested blocks. 16176 PopDeclContext(); 16177 PopFunctionScopeInfo(); 16178 } 16179 16180 /// ActOnBlockStmtExpr - This is called when the body of a block statement 16181 /// literal was successfully completed. ^(int x){...} 16182 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 16183 Stmt *Body, Scope *CurScope) { 16184 // If blocks are disabled, emit an error. 16185 if (!LangOpts.Blocks) 16186 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 16187 16188 // Leave the expression-evaluation context. 16189 if (hasAnyUnrecoverableErrorsInThisFunction()) 16190 DiscardCleanupsInEvaluationContext(); 16191 assert(!Cleanup.exprNeedsCleanups() && 16192 "cleanups within block not correctly bound!"); 16193 PopExpressionEvaluationContext(); 16194 16195 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 16196 BlockDecl *BD = BSI->TheDecl; 16197 16198 if (BSI->HasImplicitReturnType) 16199 deduceClosureReturnType(*BSI); 16200 16201 QualType RetTy = Context.VoidTy; 16202 if (!BSI->ReturnType.isNull()) 16203 RetTy = BSI->ReturnType; 16204 16205 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 16206 QualType BlockTy; 16207 16208 // If the user wrote a function type in some form, try to use that. 16209 if (!BSI->FunctionType.isNull()) { 16210 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 16211 16212 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 16213 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 16214 16215 // Turn protoless block types into nullary block types. 16216 if (isa<FunctionNoProtoType>(FTy)) { 16217 FunctionProtoType::ExtProtoInfo EPI; 16218 EPI.ExtInfo = Ext; 16219 BlockTy = Context.getFunctionType(RetTy, None, EPI); 16220 16221 // Otherwise, if we don't need to change anything about the function type, 16222 // preserve its sugar structure. 16223 } else if (FTy->getReturnType() == RetTy && 16224 (!NoReturn || FTy->getNoReturnAttr())) { 16225 BlockTy = BSI->FunctionType; 16226 16227 // Otherwise, make the minimal modifications to the function type. 16228 } else { 16229 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 16230 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 16231 EPI.TypeQuals = Qualifiers(); 16232 EPI.ExtInfo = Ext; 16233 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 16234 } 16235 16236 // If we don't have a function type, just build one from nothing. 16237 } else { 16238 FunctionProtoType::ExtProtoInfo EPI; 16239 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 16240 BlockTy = Context.getFunctionType(RetTy, None, EPI); 16241 } 16242 16243 DiagnoseUnusedParameters(BD->parameters()); 16244 BlockTy = Context.getBlockPointerType(BlockTy); 16245 16246 // If needed, diagnose invalid gotos and switches in the block. 16247 if (getCurFunction()->NeedsScopeChecking() && 16248 !PP.isCodeCompletionEnabled()) 16249 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 16250 16251 BD->setBody(cast<CompoundStmt>(Body)); 16252 16253 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 16254 DiagnoseUnguardedAvailabilityViolations(BD); 16255 16256 // Try to apply the named return value optimization. We have to check again 16257 // if we can do this, though, because blocks keep return statements around 16258 // to deduce an implicit return type. 16259 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 16260 !BD->isDependentContext()) 16261 computeNRVO(Body, BSI); 16262 16263 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 16264 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 16265 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 16266 NTCUK_Destruct|NTCUK_Copy); 16267 16268 PopDeclContext(); 16269 16270 // Set the captured variables on the block. 16271 SmallVector<BlockDecl::Capture, 4> Captures; 16272 for (Capture &Cap : BSI->Captures) { 16273 if (Cap.isInvalid() || Cap.isThisCapture()) 16274 continue; 16275 16276 VarDecl *Var = Cap.getVariable(); 16277 Expr *CopyExpr = nullptr; 16278 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 16279 if (const RecordType *Record = 16280 Cap.getCaptureType()->getAs<RecordType>()) { 16281 // The capture logic needs the destructor, so make sure we mark it. 16282 // Usually this is unnecessary because most local variables have 16283 // their destructors marked at declaration time, but parameters are 16284 // an exception because it's technically only the call site that 16285 // actually requires the destructor. 16286 if (isa<ParmVarDecl>(Var)) 16287 FinalizeVarWithDestructor(Var, Record); 16288 16289 // Enter a separate potentially-evaluated context while building block 16290 // initializers to isolate their cleanups from those of the block 16291 // itself. 16292 // FIXME: Is this appropriate even when the block itself occurs in an 16293 // unevaluated operand? 16294 EnterExpressionEvaluationContext EvalContext( 16295 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 16296 16297 SourceLocation Loc = Cap.getLocation(); 16298 16299 ExprResult Result = BuildDeclarationNameExpr( 16300 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 16301 16302 // According to the blocks spec, the capture of a variable from 16303 // the stack requires a const copy constructor. This is not true 16304 // of the copy/move done to move a __block variable to the heap. 16305 if (!Result.isInvalid() && 16306 !Result.get()->getType().isConstQualified()) { 16307 Result = ImpCastExprToType(Result.get(), 16308 Result.get()->getType().withConst(), 16309 CK_NoOp, VK_LValue); 16310 } 16311 16312 if (!Result.isInvalid()) { 16313 Result = PerformCopyInitialization( 16314 InitializedEntity::InitializeBlock(Var->getLocation(), 16315 Cap.getCaptureType()), 16316 Loc, Result.get()); 16317 } 16318 16319 // Build a full-expression copy expression if initialization 16320 // succeeded and used a non-trivial constructor. Recover from 16321 // errors by pretending that the copy isn't necessary. 16322 if (!Result.isInvalid() && 16323 !cast<CXXConstructExpr>(Result.get())->getConstructor() 16324 ->isTrivial()) { 16325 Result = MaybeCreateExprWithCleanups(Result); 16326 CopyExpr = Result.get(); 16327 } 16328 } 16329 } 16330 16331 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 16332 CopyExpr); 16333 Captures.push_back(NewCap); 16334 } 16335 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 16336 16337 // Pop the block scope now but keep it alive to the end of this function. 16338 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 16339 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 16340 16341 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 16342 16343 // If the block isn't obviously global, i.e. it captures anything at 16344 // all, then we need to do a few things in the surrounding context: 16345 if (Result->getBlockDecl()->hasCaptures()) { 16346 // First, this expression has a new cleanup object. 16347 ExprCleanupObjects.push_back(Result->getBlockDecl()); 16348 Cleanup.setExprNeedsCleanups(true); 16349 16350 // It also gets a branch-protected scope if any of the captured 16351 // variables needs destruction. 16352 for (const auto &CI : Result->getBlockDecl()->captures()) { 16353 const VarDecl *var = CI.getVariable(); 16354 if (var->getType().isDestructedType() != QualType::DK_none) { 16355 setFunctionHasBranchProtectedScope(); 16356 break; 16357 } 16358 } 16359 } 16360 16361 if (getCurFunction()) 16362 getCurFunction()->addBlock(BD); 16363 16364 return Result; 16365 } 16366 16367 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 16368 SourceLocation RPLoc) { 16369 TypeSourceInfo *TInfo; 16370 GetTypeFromParser(Ty, &TInfo); 16371 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 16372 } 16373 16374 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 16375 Expr *E, TypeSourceInfo *TInfo, 16376 SourceLocation RPLoc) { 16377 Expr *OrigExpr = E; 16378 bool IsMS = false; 16379 16380 // CUDA device code does not support varargs. 16381 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 16382 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 16383 CUDAFunctionTarget T = IdentifyCUDATarget(F); 16384 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 16385 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 16386 } 16387 } 16388 16389 // NVPTX does not support va_arg expression. 16390 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 16391 Context.getTargetInfo().getTriple().isNVPTX()) 16392 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 16393 16394 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 16395 // as Microsoft ABI on an actual Microsoft platform, where 16396 // __builtin_ms_va_list and __builtin_va_list are the same.) 16397 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 16398 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 16399 QualType MSVaListType = Context.getBuiltinMSVaListType(); 16400 if (Context.hasSameType(MSVaListType, E->getType())) { 16401 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 16402 return ExprError(); 16403 IsMS = true; 16404 } 16405 } 16406 16407 // Get the va_list type 16408 QualType VaListType = Context.getBuiltinVaListType(); 16409 if (!IsMS) { 16410 if (VaListType->isArrayType()) { 16411 // Deal with implicit array decay; for example, on x86-64, 16412 // va_list is an array, but it's supposed to decay to 16413 // a pointer for va_arg. 16414 VaListType = Context.getArrayDecayedType(VaListType); 16415 // Make sure the input expression also decays appropriately. 16416 ExprResult Result = UsualUnaryConversions(E); 16417 if (Result.isInvalid()) 16418 return ExprError(); 16419 E = Result.get(); 16420 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 16421 // If va_list is a record type and we are compiling in C++ mode, 16422 // check the argument using reference binding. 16423 InitializedEntity Entity = InitializedEntity::InitializeParameter( 16424 Context, Context.getLValueReferenceType(VaListType), false); 16425 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 16426 if (Init.isInvalid()) 16427 return ExprError(); 16428 E = Init.getAs<Expr>(); 16429 } else { 16430 // Otherwise, the va_list argument must be an l-value because 16431 // it is modified by va_arg. 16432 if (!E->isTypeDependent() && 16433 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 16434 return ExprError(); 16435 } 16436 } 16437 16438 if (!IsMS && !E->isTypeDependent() && 16439 !Context.hasSameType(VaListType, E->getType())) 16440 return ExprError( 16441 Diag(E->getBeginLoc(), 16442 diag::err_first_argument_to_va_arg_not_of_type_va_list) 16443 << OrigExpr->getType() << E->getSourceRange()); 16444 16445 if (!TInfo->getType()->isDependentType()) { 16446 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 16447 diag::err_second_parameter_to_va_arg_incomplete, 16448 TInfo->getTypeLoc())) 16449 return ExprError(); 16450 16451 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 16452 TInfo->getType(), 16453 diag::err_second_parameter_to_va_arg_abstract, 16454 TInfo->getTypeLoc())) 16455 return ExprError(); 16456 16457 if (!TInfo->getType().isPODType(Context)) { 16458 Diag(TInfo->getTypeLoc().getBeginLoc(), 16459 TInfo->getType()->isObjCLifetimeType() 16460 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 16461 : diag::warn_second_parameter_to_va_arg_not_pod) 16462 << TInfo->getType() 16463 << TInfo->getTypeLoc().getSourceRange(); 16464 } 16465 16466 // Check for va_arg where arguments of the given type will be promoted 16467 // (i.e. this va_arg is guaranteed to have undefined behavior). 16468 QualType PromoteType; 16469 if (TInfo->getType()->isPromotableIntegerType()) { 16470 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 16471 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 16472 // and C2x 7.16.1.1p2 says, in part: 16473 // If type is not compatible with the type of the actual next argument 16474 // (as promoted according to the default argument promotions), the 16475 // behavior is undefined, except for the following cases: 16476 // - both types are pointers to qualified or unqualified versions of 16477 // compatible types; 16478 // - one type is a signed integer type, the other type is the 16479 // corresponding unsigned integer type, and the value is 16480 // representable in both types; 16481 // - one type is pointer to qualified or unqualified void and the 16482 // other is a pointer to a qualified or unqualified character type. 16483 // Given that type compatibility is the primary requirement (ignoring 16484 // qualifications), you would think we could call typesAreCompatible() 16485 // directly to test this. However, in C++, that checks for *same type*, 16486 // which causes false positives when passing an enumeration type to 16487 // va_arg. Instead, get the underlying type of the enumeration and pass 16488 // that. 16489 QualType UnderlyingType = TInfo->getType(); 16490 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 16491 UnderlyingType = ET->getDecl()->getIntegerType(); 16492 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 16493 /*CompareUnqualified*/ true)) 16494 PromoteType = QualType(); 16495 16496 // If the types are still not compatible, we need to test whether the 16497 // promoted type and the underlying type are the same except for 16498 // signedness. Ask the AST for the correctly corresponding type and see 16499 // if that's compatible. 16500 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() && 16501 PromoteType->isUnsignedIntegerType() != 16502 UnderlyingType->isUnsignedIntegerType()) { 16503 UnderlyingType = 16504 UnderlyingType->isUnsignedIntegerType() 16505 ? Context.getCorrespondingSignedType(UnderlyingType) 16506 : Context.getCorrespondingUnsignedType(UnderlyingType); 16507 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 16508 /*CompareUnqualified*/ true)) 16509 PromoteType = QualType(); 16510 } 16511 } 16512 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 16513 PromoteType = Context.DoubleTy; 16514 if (!PromoteType.isNull()) 16515 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 16516 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 16517 << TInfo->getType() 16518 << PromoteType 16519 << TInfo->getTypeLoc().getSourceRange()); 16520 } 16521 16522 QualType T = TInfo->getType().getNonLValueExprType(Context); 16523 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 16524 } 16525 16526 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 16527 // The type of __null will be int or long, depending on the size of 16528 // pointers on the target. 16529 QualType Ty; 16530 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 16531 if (pw == Context.getTargetInfo().getIntWidth()) 16532 Ty = Context.IntTy; 16533 else if (pw == Context.getTargetInfo().getLongWidth()) 16534 Ty = Context.LongTy; 16535 else if (pw == Context.getTargetInfo().getLongLongWidth()) 16536 Ty = Context.LongLongTy; 16537 else { 16538 llvm_unreachable("I don't know size of pointer!"); 16539 } 16540 16541 return new (Context) GNUNullExpr(Ty, TokenLoc); 16542 } 16543 16544 static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) { 16545 CXXRecordDecl *ImplDecl = nullptr; 16546 16547 // Fetch the std::source_location::__impl decl. 16548 if (NamespaceDecl *Std = S.getStdNamespace()) { 16549 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"), 16550 Loc, Sema::LookupOrdinaryName); 16551 if (S.LookupQualifiedName(ResultSL, Std)) { 16552 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) { 16553 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"), 16554 Loc, Sema::LookupOrdinaryName); 16555 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) && 16556 S.LookupQualifiedName(ResultImpl, SLDecl)) { 16557 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>(); 16558 } 16559 } 16560 } 16561 } 16562 16563 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) { 16564 S.Diag(Loc, diag::err_std_source_location_impl_not_found); 16565 return nullptr; 16566 } 16567 16568 // Verify that __impl is a trivial struct type, with no base classes, and with 16569 // only the four expected fields. 16570 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() || 16571 ImplDecl->getNumBases() != 0) { 16572 S.Diag(Loc, diag::err_std_source_location_impl_malformed); 16573 return nullptr; 16574 } 16575 16576 unsigned Count = 0; 16577 for (FieldDecl *F : ImplDecl->fields()) { 16578 StringRef Name = F->getName(); 16579 16580 if (Name == "_M_file_name") { 16581 if (F->getType() != 16582 S.Context.getPointerType(S.Context.CharTy.withConst())) 16583 break; 16584 Count++; 16585 } else if (Name == "_M_function_name") { 16586 if (F->getType() != 16587 S.Context.getPointerType(S.Context.CharTy.withConst())) 16588 break; 16589 Count++; 16590 } else if (Name == "_M_line") { 16591 if (!F->getType()->isIntegerType()) 16592 break; 16593 Count++; 16594 } else if (Name == "_M_column") { 16595 if (!F->getType()->isIntegerType()) 16596 break; 16597 Count++; 16598 } else { 16599 Count = 100; // invalid 16600 break; 16601 } 16602 } 16603 if (Count != 4) { 16604 S.Diag(Loc, diag::err_std_source_location_impl_malformed); 16605 return nullptr; 16606 } 16607 16608 return ImplDecl; 16609 } 16610 16611 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 16612 SourceLocation BuiltinLoc, 16613 SourceLocation RPLoc) { 16614 QualType ResultTy; 16615 switch (Kind) { 16616 case SourceLocExpr::File: 16617 case SourceLocExpr::Function: { 16618 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0); 16619 ResultTy = 16620 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType()); 16621 break; 16622 } 16623 case SourceLocExpr::Line: 16624 case SourceLocExpr::Column: 16625 ResultTy = Context.UnsignedIntTy; 16626 break; 16627 case SourceLocExpr::SourceLocStruct: 16628 if (!StdSourceLocationImplDecl) { 16629 StdSourceLocationImplDecl = 16630 LookupStdSourceLocationImpl(*this, BuiltinLoc); 16631 if (!StdSourceLocationImplDecl) 16632 return ExprError(); 16633 } 16634 ResultTy = Context.getPointerType( 16635 Context.getRecordType(StdSourceLocationImplDecl).withConst()); 16636 break; 16637 } 16638 16639 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext); 16640 } 16641 16642 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 16643 QualType ResultTy, 16644 SourceLocation BuiltinLoc, 16645 SourceLocation RPLoc, 16646 DeclContext *ParentContext) { 16647 return new (Context) 16648 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext); 16649 } 16650 16651 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 16652 bool Diagnose) { 16653 if (!getLangOpts().ObjC) 16654 return false; 16655 16656 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 16657 if (!PT) 16658 return false; 16659 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 16660 16661 // Ignore any parens, implicit casts (should only be 16662 // array-to-pointer decays), and not-so-opaque values. The last is 16663 // important for making this trigger for property assignments. 16664 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 16665 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 16666 if (OV->getSourceExpr()) 16667 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 16668 16669 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 16670 if (!PT->isObjCIdType() && 16671 !(ID && ID->getIdentifier()->isStr("NSString"))) 16672 return false; 16673 if (!SL->isAscii()) 16674 return false; 16675 16676 if (Diagnose) { 16677 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 16678 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 16679 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 16680 } 16681 return true; 16682 } 16683 16684 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 16685 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 16686 isa<CXXBoolLiteralExpr>(SrcExpr)) && 16687 !SrcExpr->isNullPointerConstant( 16688 getASTContext(), Expr::NPC_NeverValueDependent)) { 16689 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 16690 return false; 16691 if (Diagnose) { 16692 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 16693 << /*number*/1 16694 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 16695 Expr *NumLit = 16696 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 16697 if (NumLit) 16698 Exp = NumLit; 16699 } 16700 return true; 16701 } 16702 16703 return false; 16704 } 16705 16706 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 16707 const Expr *SrcExpr) { 16708 if (!DstType->isFunctionPointerType() || 16709 !SrcExpr->getType()->isFunctionType()) 16710 return false; 16711 16712 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 16713 if (!DRE) 16714 return false; 16715 16716 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 16717 if (!FD) 16718 return false; 16719 16720 return !S.checkAddressOfFunctionIsAvailable(FD, 16721 /*Complain=*/true, 16722 SrcExpr->getBeginLoc()); 16723 } 16724 16725 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 16726 SourceLocation Loc, 16727 QualType DstType, QualType SrcType, 16728 Expr *SrcExpr, AssignmentAction Action, 16729 bool *Complained) { 16730 if (Complained) 16731 *Complained = false; 16732 16733 // Decode the result (notice that AST's are still created for extensions). 16734 bool CheckInferredResultType = false; 16735 bool isInvalid = false; 16736 unsigned DiagKind = 0; 16737 ConversionFixItGenerator ConvHints; 16738 bool MayHaveConvFixit = false; 16739 bool MayHaveFunctionDiff = false; 16740 const ObjCInterfaceDecl *IFace = nullptr; 16741 const ObjCProtocolDecl *PDecl = nullptr; 16742 16743 switch (ConvTy) { 16744 case Compatible: 16745 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 16746 return false; 16747 16748 case PointerToInt: 16749 if (getLangOpts().CPlusPlus) { 16750 DiagKind = diag::err_typecheck_convert_pointer_int; 16751 isInvalid = true; 16752 } else { 16753 DiagKind = diag::ext_typecheck_convert_pointer_int; 16754 } 16755 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16756 MayHaveConvFixit = true; 16757 break; 16758 case IntToPointer: 16759 if (getLangOpts().CPlusPlus) { 16760 DiagKind = diag::err_typecheck_convert_int_pointer; 16761 isInvalid = true; 16762 } else { 16763 DiagKind = diag::ext_typecheck_convert_int_pointer; 16764 } 16765 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16766 MayHaveConvFixit = true; 16767 break; 16768 case IncompatibleFunctionPointer: 16769 if (getLangOpts().CPlusPlus) { 16770 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 16771 isInvalid = true; 16772 } else { 16773 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 16774 } 16775 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16776 MayHaveConvFixit = true; 16777 break; 16778 case IncompatiblePointer: 16779 if (Action == AA_Passing_CFAudited) { 16780 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 16781 } else if (getLangOpts().CPlusPlus) { 16782 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 16783 isInvalid = true; 16784 } else { 16785 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 16786 } 16787 CheckInferredResultType = DstType->isObjCObjectPointerType() && 16788 SrcType->isObjCObjectPointerType(); 16789 if (!CheckInferredResultType) { 16790 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16791 } else if (CheckInferredResultType) { 16792 SrcType = SrcType.getUnqualifiedType(); 16793 DstType = DstType.getUnqualifiedType(); 16794 } 16795 MayHaveConvFixit = true; 16796 break; 16797 case IncompatiblePointerSign: 16798 if (getLangOpts().CPlusPlus) { 16799 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 16800 isInvalid = true; 16801 } else { 16802 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 16803 } 16804 break; 16805 case FunctionVoidPointer: 16806 if (getLangOpts().CPlusPlus) { 16807 DiagKind = diag::err_typecheck_convert_pointer_void_func; 16808 isInvalid = true; 16809 } else { 16810 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 16811 } 16812 break; 16813 case IncompatiblePointerDiscardsQualifiers: { 16814 // Perform array-to-pointer decay if necessary. 16815 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 16816 16817 isInvalid = true; 16818 16819 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 16820 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 16821 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 16822 DiagKind = diag::err_typecheck_incompatible_address_space; 16823 break; 16824 16825 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 16826 DiagKind = diag::err_typecheck_incompatible_ownership; 16827 break; 16828 } 16829 16830 llvm_unreachable("unknown error case for discarding qualifiers!"); 16831 // fallthrough 16832 } 16833 case CompatiblePointerDiscardsQualifiers: 16834 // If the qualifiers lost were because we were applying the 16835 // (deprecated) C++ conversion from a string literal to a char* 16836 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 16837 // Ideally, this check would be performed in 16838 // checkPointerTypesForAssignment. However, that would require a 16839 // bit of refactoring (so that the second argument is an 16840 // expression, rather than a type), which should be done as part 16841 // of a larger effort to fix checkPointerTypesForAssignment for 16842 // C++ semantics. 16843 if (getLangOpts().CPlusPlus && 16844 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 16845 return false; 16846 if (getLangOpts().CPlusPlus) { 16847 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 16848 isInvalid = true; 16849 } else { 16850 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 16851 } 16852 16853 break; 16854 case IncompatibleNestedPointerQualifiers: 16855 if (getLangOpts().CPlusPlus) { 16856 isInvalid = true; 16857 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 16858 } else { 16859 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16860 } 16861 break; 16862 case IncompatibleNestedPointerAddressSpaceMismatch: 16863 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16864 isInvalid = true; 16865 break; 16866 case IntToBlockPointer: 16867 DiagKind = diag::err_int_to_block_pointer; 16868 isInvalid = true; 16869 break; 16870 case IncompatibleBlockPointer: 16871 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16872 isInvalid = true; 16873 break; 16874 case IncompatibleObjCQualifiedId: { 16875 if (SrcType->isObjCQualifiedIdType()) { 16876 const ObjCObjectPointerType *srcOPT = 16877 SrcType->castAs<ObjCObjectPointerType>(); 16878 for (auto *srcProto : srcOPT->quals()) { 16879 PDecl = srcProto; 16880 break; 16881 } 16882 if (const ObjCInterfaceType *IFaceT = 16883 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16884 IFace = IFaceT->getDecl(); 16885 } 16886 else if (DstType->isObjCQualifiedIdType()) { 16887 const ObjCObjectPointerType *dstOPT = 16888 DstType->castAs<ObjCObjectPointerType>(); 16889 for (auto *dstProto : dstOPT->quals()) { 16890 PDecl = dstProto; 16891 break; 16892 } 16893 if (const ObjCInterfaceType *IFaceT = 16894 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16895 IFace = IFaceT->getDecl(); 16896 } 16897 if (getLangOpts().CPlusPlus) { 16898 DiagKind = diag::err_incompatible_qualified_id; 16899 isInvalid = true; 16900 } else { 16901 DiagKind = diag::warn_incompatible_qualified_id; 16902 } 16903 break; 16904 } 16905 case IncompatibleVectors: 16906 if (getLangOpts().CPlusPlus) { 16907 DiagKind = diag::err_incompatible_vectors; 16908 isInvalid = true; 16909 } else { 16910 DiagKind = diag::warn_incompatible_vectors; 16911 } 16912 break; 16913 case IncompatibleObjCWeakRef: 16914 DiagKind = diag::err_arc_weak_unavailable_assign; 16915 isInvalid = true; 16916 break; 16917 case Incompatible: 16918 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16919 if (Complained) 16920 *Complained = true; 16921 return true; 16922 } 16923 16924 DiagKind = diag::err_typecheck_convert_incompatible; 16925 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16926 MayHaveConvFixit = true; 16927 isInvalid = true; 16928 MayHaveFunctionDiff = true; 16929 break; 16930 } 16931 16932 QualType FirstType, SecondType; 16933 switch (Action) { 16934 case AA_Assigning: 16935 case AA_Initializing: 16936 // The destination type comes first. 16937 FirstType = DstType; 16938 SecondType = SrcType; 16939 break; 16940 16941 case AA_Returning: 16942 case AA_Passing: 16943 case AA_Passing_CFAudited: 16944 case AA_Converting: 16945 case AA_Sending: 16946 case AA_Casting: 16947 // The source type comes first. 16948 FirstType = SrcType; 16949 SecondType = DstType; 16950 break; 16951 } 16952 16953 PartialDiagnostic FDiag = PDiag(DiagKind); 16954 AssignmentAction ActionForDiag = Action; 16955 if (Action == AA_Passing_CFAudited) 16956 ActionForDiag = AA_Passing; 16957 16958 FDiag << FirstType << SecondType << ActionForDiag 16959 << SrcExpr->getSourceRange(); 16960 16961 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16962 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16963 auto isPlainChar = [](const clang::Type *Type) { 16964 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16965 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16966 }; 16967 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16968 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16969 } 16970 16971 // If we can fix the conversion, suggest the FixIts. 16972 if (!ConvHints.isNull()) { 16973 for (FixItHint &H : ConvHints.Hints) 16974 FDiag << H; 16975 } 16976 16977 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16978 16979 if (MayHaveFunctionDiff) 16980 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16981 16982 Diag(Loc, FDiag); 16983 if ((DiagKind == diag::warn_incompatible_qualified_id || 16984 DiagKind == diag::err_incompatible_qualified_id) && 16985 PDecl && IFace && !IFace->hasDefinition()) 16986 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16987 << IFace << PDecl; 16988 16989 if (SecondType == Context.OverloadTy) 16990 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16991 FirstType, /*TakingAddress=*/true); 16992 16993 if (CheckInferredResultType) 16994 EmitRelatedResultTypeNote(SrcExpr); 16995 16996 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16997 EmitRelatedResultTypeNoteForReturn(DstType); 16998 16999 if (Complained) 17000 *Complained = true; 17001 return isInvalid; 17002 } 17003 17004 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 17005 llvm::APSInt *Result, 17006 AllowFoldKind CanFold) { 17007 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 17008 public: 17009 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 17010 QualType T) override { 17011 return S.Diag(Loc, diag::err_ice_not_integral) 17012 << T << S.LangOpts.CPlusPlus; 17013 } 17014 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 17015 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 17016 } 17017 } Diagnoser; 17018 17019 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 17020 } 17021 17022 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 17023 llvm::APSInt *Result, 17024 unsigned DiagID, 17025 AllowFoldKind CanFold) { 17026 class IDDiagnoser : public VerifyICEDiagnoser { 17027 unsigned DiagID; 17028 17029 public: 17030 IDDiagnoser(unsigned DiagID) 17031 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 17032 17033 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 17034 return S.Diag(Loc, DiagID); 17035 } 17036 } Diagnoser(DiagID); 17037 17038 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 17039 } 17040 17041 Sema::SemaDiagnosticBuilder 17042 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 17043 QualType T) { 17044 return diagnoseNotICE(S, Loc); 17045 } 17046 17047 Sema::SemaDiagnosticBuilder 17048 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 17049 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 17050 } 17051 17052 ExprResult 17053 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 17054 VerifyICEDiagnoser &Diagnoser, 17055 AllowFoldKind CanFold) { 17056 SourceLocation DiagLoc = E->getBeginLoc(); 17057 17058 if (getLangOpts().CPlusPlus11) { 17059 // C++11 [expr.const]p5: 17060 // If an expression of literal class type is used in a context where an 17061 // integral constant expression is required, then that class type shall 17062 // have a single non-explicit conversion function to an integral or 17063 // unscoped enumeration type 17064 ExprResult Converted; 17065 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 17066 VerifyICEDiagnoser &BaseDiagnoser; 17067 public: 17068 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 17069 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 17070 BaseDiagnoser.Suppress, true), 17071 BaseDiagnoser(BaseDiagnoser) {} 17072 17073 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 17074 QualType T) override { 17075 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 17076 } 17077 17078 SemaDiagnosticBuilder diagnoseIncomplete( 17079 Sema &S, SourceLocation Loc, QualType T) override { 17080 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 17081 } 17082 17083 SemaDiagnosticBuilder diagnoseExplicitConv( 17084 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 17085 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 17086 } 17087 17088 SemaDiagnosticBuilder noteExplicitConv( 17089 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 17090 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 17091 << ConvTy->isEnumeralType() << ConvTy; 17092 } 17093 17094 SemaDiagnosticBuilder diagnoseAmbiguous( 17095 Sema &S, SourceLocation Loc, QualType T) override { 17096 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 17097 } 17098 17099 SemaDiagnosticBuilder noteAmbiguous( 17100 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 17101 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 17102 << ConvTy->isEnumeralType() << ConvTy; 17103 } 17104 17105 SemaDiagnosticBuilder diagnoseConversion( 17106 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 17107 llvm_unreachable("conversion functions are permitted"); 17108 } 17109 } ConvertDiagnoser(Diagnoser); 17110 17111 Converted = PerformContextualImplicitConversion(DiagLoc, E, 17112 ConvertDiagnoser); 17113 if (Converted.isInvalid()) 17114 return Converted; 17115 E = Converted.get(); 17116 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 17117 return ExprError(); 17118 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 17119 // An ICE must be of integral or unscoped enumeration type. 17120 if (!Diagnoser.Suppress) 17121 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 17122 << E->getSourceRange(); 17123 return ExprError(); 17124 } 17125 17126 ExprResult RValueExpr = DefaultLvalueConversion(E); 17127 if (RValueExpr.isInvalid()) 17128 return ExprError(); 17129 17130 E = RValueExpr.get(); 17131 17132 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 17133 // in the non-ICE case. 17134 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 17135 if (Result) 17136 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 17137 if (!isa<ConstantExpr>(E)) 17138 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 17139 : ConstantExpr::Create(Context, E); 17140 return E; 17141 } 17142 17143 Expr::EvalResult EvalResult; 17144 SmallVector<PartialDiagnosticAt, 8> Notes; 17145 EvalResult.Diag = &Notes; 17146 17147 // Try to evaluate the expression, and produce diagnostics explaining why it's 17148 // not a constant expression as a side-effect. 17149 bool Folded = 17150 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 17151 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 17152 17153 if (!isa<ConstantExpr>(E)) 17154 E = ConstantExpr::Create(Context, E, EvalResult.Val); 17155 17156 // In C++11, we can rely on diagnostics being produced for any expression 17157 // which is not a constant expression. If no diagnostics were produced, then 17158 // this is a constant expression. 17159 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 17160 if (Result) 17161 *Result = EvalResult.Val.getInt(); 17162 return E; 17163 } 17164 17165 // If our only note is the usual "invalid subexpression" note, just point 17166 // the caret at its location rather than producing an essentially 17167 // redundant note. 17168 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 17169 diag::note_invalid_subexpr_in_const_expr) { 17170 DiagLoc = Notes[0].first; 17171 Notes.clear(); 17172 } 17173 17174 if (!Folded || !CanFold) { 17175 if (!Diagnoser.Suppress) { 17176 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 17177 for (const PartialDiagnosticAt &Note : Notes) 17178 Diag(Note.first, Note.second); 17179 } 17180 17181 return ExprError(); 17182 } 17183 17184 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 17185 for (const PartialDiagnosticAt &Note : Notes) 17186 Diag(Note.first, Note.second); 17187 17188 if (Result) 17189 *Result = EvalResult.Val.getInt(); 17190 return E; 17191 } 17192 17193 namespace { 17194 // Handle the case where we conclude a expression which we speculatively 17195 // considered to be unevaluated is actually evaluated. 17196 class TransformToPE : public TreeTransform<TransformToPE> { 17197 typedef TreeTransform<TransformToPE> BaseTransform; 17198 17199 public: 17200 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 17201 17202 // Make sure we redo semantic analysis 17203 bool AlwaysRebuild() { return true; } 17204 bool ReplacingOriginal() { return true; } 17205 17206 // We need to special-case DeclRefExprs referring to FieldDecls which 17207 // are not part of a member pointer formation; normal TreeTransforming 17208 // doesn't catch this case because of the way we represent them in the AST. 17209 // FIXME: This is a bit ugly; is it really the best way to handle this 17210 // case? 17211 // 17212 // Error on DeclRefExprs referring to FieldDecls. 17213 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 17214 if (isa<FieldDecl>(E->getDecl()) && 17215 !SemaRef.isUnevaluatedContext()) 17216 return SemaRef.Diag(E->getLocation(), 17217 diag::err_invalid_non_static_member_use) 17218 << E->getDecl() << E->getSourceRange(); 17219 17220 return BaseTransform::TransformDeclRefExpr(E); 17221 } 17222 17223 // Exception: filter out member pointer formation 17224 ExprResult TransformUnaryOperator(UnaryOperator *E) { 17225 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 17226 return E; 17227 17228 return BaseTransform::TransformUnaryOperator(E); 17229 } 17230 17231 // The body of a lambda-expression is in a separate expression evaluation 17232 // context so never needs to be transformed. 17233 // FIXME: Ideally we wouldn't transform the closure type either, and would 17234 // just recreate the capture expressions and lambda expression. 17235 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 17236 return SkipLambdaBody(E, Body); 17237 } 17238 }; 17239 } 17240 17241 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 17242 assert(isUnevaluatedContext() && 17243 "Should only transform unevaluated expressions"); 17244 ExprEvalContexts.back().Context = 17245 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 17246 if (isUnevaluatedContext()) 17247 return E; 17248 return TransformToPE(*this).TransformExpr(E); 17249 } 17250 17251 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) { 17252 assert(isUnevaluatedContext() && 17253 "Should only transform unevaluated expressions"); 17254 ExprEvalContexts.back().Context = 17255 ExprEvalContexts[ExprEvalContexts.size() - 2].Context; 17256 if (isUnevaluatedContext()) 17257 return TInfo; 17258 return TransformToPE(*this).TransformType(TInfo); 17259 } 17260 17261 void 17262 Sema::PushExpressionEvaluationContext( 17263 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 17264 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 17265 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 17266 LambdaContextDecl, ExprContext); 17267 17268 // Discarded statements and immediate contexts nested in other 17269 // discarded statements or immediate context are themselves 17270 // a discarded statement or an immediate context, respectively. 17271 ExprEvalContexts.back().InDiscardedStatement = 17272 ExprEvalContexts[ExprEvalContexts.size() - 2] 17273 .isDiscardedStatementContext(); 17274 ExprEvalContexts.back().InImmediateFunctionContext = 17275 ExprEvalContexts[ExprEvalContexts.size() - 2] 17276 .isImmediateFunctionContext(); 17277 17278 Cleanup.reset(); 17279 if (!MaybeODRUseExprs.empty()) 17280 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 17281 } 17282 17283 void 17284 Sema::PushExpressionEvaluationContext( 17285 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 17286 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 17287 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 17288 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 17289 } 17290 17291 namespace { 17292 17293 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 17294 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 17295 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 17296 if (E->getOpcode() == UO_Deref) 17297 return CheckPossibleDeref(S, E->getSubExpr()); 17298 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 17299 return CheckPossibleDeref(S, E->getBase()); 17300 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 17301 return CheckPossibleDeref(S, E->getBase()); 17302 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 17303 QualType Inner; 17304 QualType Ty = E->getType(); 17305 if (const auto *Ptr = Ty->getAs<PointerType>()) 17306 Inner = Ptr->getPointeeType(); 17307 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 17308 Inner = Arr->getElementType(); 17309 else 17310 return nullptr; 17311 17312 if (Inner->hasAttr(attr::NoDeref)) 17313 return E; 17314 } 17315 return nullptr; 17316 } 17317 17318 } // namespace 17319 17320 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 17321 for (const Expr *E : Rec.PossibleDerefs) { 17322 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 17323 if (DeclRef) { 17324 const ValueDecl *Decl = DeclRef->getDecl(); 17325 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 17326 << Decl->getName() << E->getSourceRange(); 17327 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 17328 } else { 17329 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 17330 << E->getSourceRange(); 17331 } 17332 } 17333 Rec.PossibleDerefs.clear(); 17334 } 17335 17336 /// Check whether E, which is either a discarded-value expression or an 17337 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 17338 /// and if so, remove it from the list of volatile-qualified assignments that 17339 /// we are going to warn are deprecated. 17340 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 17341 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 17342 return; 17343 17344 // Note: ignoring parens here is not justified by the standard rules, but 17345 // ignoring parentheses seems like a more reasonable approach, and this only 17346 // drives a deprecation warning so doesn't affect conformance. 17347 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 17348 if (BO->getOpcode() == BO_Assign) { 17349 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 17350 llvm::erase_value(LHSs, BO->getLHS()); 17351 } 17352 } 17353 } 17354 17355 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 17356 if (isUnevaluatedContext() || !E.isUsable() || !Decl || 17357 !Decl->isConsteval() || isConstantEvaluated() || 17358 RebuildingImmediateInvocation || isImmediateFunctionContext()) 17359 return E; 17360 17361 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 17362 /// It's OK if this fails; we'll also remove this in 17363 /// HandleImmediateInvocations, but catching it here allows us to avoid 17364 /// walking the AST looking for it in simple cases. 17365 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 17366 if (auto *DeclRef = 17367 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 17368 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 17369 17370 E = MaybeCreateExprWithCleanups(E); 17371 17372 ConstantExpr *Res = ConstantExpr::Create( 17373 getASTContext(), E.get(), 17374 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 17375 getASTContext()), 17376 /*IsImmediateInvocation*/ true); 17377 /// Value-dependent constant expressions should not be immediately 17378 /// evaluated until they are instantiated. 17379 if (!Res->isValueDependent()) 17380 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 17381 return Res; 17382 } 17383 17384 static void EvaluateAndDiagnoseImmediateInvocation( 17385 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 17386 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 17387 Expr::EvalResult Eval; 17388 Eval.Diag = &Notes; 17389 ConstantExpr *CE = Candidate.getPointer(); 17390 bool Result = CE->EvaluateAsConstantExpr( 17391 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 17392 if (!Result || !Notes.empty()) { 17393 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 17394 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 17395 InnerExpr = FunctionalCast->getSubExpr(); 17396 FunctionDecl *FD = nullptr; 17397 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 17398 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 17399 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 17400 FD = Call->getConstructor(); 17401 else 17402 llvm_unreachable("unhandled decl kind"); 17403 assert(FD->isConsteval()); 17404 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 17405 for (auto &Note : Notes) 17406 SemaRef.Diag(Note.first, Note.second); 17407 return; 17408 } 17409 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 17410 } 17411 17412 static void RemoveNestedImmediateInvocation( 17413 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 17414 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 17415 struct ComplexRemove : TreeTransform<ComplexRemove> { 17416 using Base = TreeTransform<ComplexRemove>; 17417 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 17418 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 17419 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 17420 CurrentII; 17421 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 17422 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 17423 SmallVector<Sema::ImmediateInvocationCandidate, 17424 4>::reverse_iterator Current) 17425 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 17426 void RemoveImmediateInvocation(ConstantExpr* E) { 17427 auto It = std::find_if(CurrentII, IISet.rend(), 17428 [E](Sema::ImmediateInvocationCandidate Elem) { 17429 return Elem.getPointer() == E; 17430 }); 17431 assert(It != IISet.rend() && 17432 "ConstantExpr marked IsImmediateInvocation should " 17433 "be present"); 17434 It->setInt(1); // Mark as deleted 17435 } 17436 ExprResult TransformConstantExpr(ConstantExpr *E) { 17437 if (!E->isImmediateInvocation()) 17438 return Base::TransformConstantExpr(E); 17439 RemoveImmediateInvocation(E); 17440 return Base::TransformExpr(E->getSubExpr()); 17441 } 17442 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 17443 /// we need to remove its DeclRefExpr from the DRSet. 17444 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 17445 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 17446 return Base::TransformCXXOperatorCallExpr(E); 17447 } 17448 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 17449 /// here. 17450 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 17451 if (!Init) 17452 return Init; 17453 /// ConstantExpr are the first layer of implicit node to be removed so if 17454 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 17455 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 17456 if (CE->isImmediateInvocation()) 17457 RemoveImmediateInvocation(CE); 17458 return Base::TransformInitializer(Init, NotCopyInit); 17459 } 17460 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 17461 DRSet.erase(E); 17462 return E; 17463 } 17464 bool AlwaysRebuild() { return false; } 17465 bool ReplacingOriginal() { return true; } 17466 bool AllowSkippingCXXConstructExpr() { 17467 bool Res = AllowSkippingFirstCXXConstructExpr; 17468 AllowSkippingFirstCXXConstructExpr = true; 17469 return Res; 17470 } 17471 bool AllowSkippingFirstCXXConstructExpr = true; 17472 } Transformer(SemaRef, Rec.ReferenceToConsteval, 17473 Rec.ImmediateInvocationCandidates, It); 17474 17475 /// CXXConstructExpr with a single argument are getting skipped by 17476 /// TreeTransform in some situtation because they could be implicit. This 17477 /// can only occur for the top-level CXXConstructExpr because it is used 17478 /// nowhere in the expression being transformed therefore will not be rebuilt. 17479 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 17480 /// skipping the first CXXConstructExpr. 17481 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 17482 Transformer.AllowSkippingFirstCXXConstructExpr = false; 17483 17484 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 17485 assert(Res.isUsable()); 17486 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 17487 It->getPointer()->setSubExpr(Res.get()); 17488 } 17489 17490 static void 17491 HandleImmediateInvocations(Sema &SemaRef, 17492 Sema::ExpressionEvaluationContextRecord &Rec) { 17493 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 17494 Rec.ReferenceToConsteval.size() == 0) || 17495 SemaRef.RebuildingImmediateInvocation) 17496 return; 17497 17498 /// When we have more then 1 ImmediateInvocationCandidates we need to check 17499 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 17500 /// need to remove ReferenceToConsteval in the immediate invocation. 17501 if (Rec.ImmediateInvocationCandidates.size() > 1) { 17502 17503 /// Prevent sema calls during the tree transform from adding pointers that 17504 /// are already in the sets. 17505 llvm::SaveAndRestore<bool> DisableIITracking( 17506 SemaRef.RebuildingImmediateInvocation, true); 17507 17508 /// Prevent diagnostic during tree transfrom as they are duplicates 17509 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 17510 17511 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 17512 It != Rec.ImmediateInvocationCandidates.rend(); It++) 17513 if (!It->getInt()) 17514 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 17515 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 17516 Rec.ReferenceToConsteval.size()) { 17517 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 17518 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 17519 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 17520 bool VisitDeclRefExpr(DeclRefExpr *E) { 17521 DRSet.erase(E); 17522 return DRSet.size(); 17523 } 17524 } Visitor(Rec.ReferenceToConsteval); 17525 Visitor.TraverseStmt( 17526 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 17527 } 17528 for (auto CE : Rec.ImmediateInvocationCandidates) 17529 if (!CE.getInt()) 17530 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 17531 for (auto DR : Rec.ReferenceToConsteval) { 17532 auto *FD = cast<FunctionDecl>(DR->getDecl()); 17533 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 17534 << FD; 17535 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 17536 } 17537 } 17538 17539 void Sema::PopExpressionEvaluationContext() { 17540 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 17541 unsigned NumTypos = Rec.NumTypos; 17542 17543 if (!Rec.Lambdas.empty()) { 17544 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 17545 if (!getLangOpts().CPlusPlus20 && 17546 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 17547 Rec.isUnevaluated() || 17548 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 17549 unsigned D; 17550 if (Rec.isUnevaluated()) { 17551 // C++11 [expr.prim.lambda]p2: 17552 // A lambda-expression shall not appear in an unevaluated operand 17553 // (Clause 5). 17554 D = diag::err_lambda_unevaluated_operand; 17555 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 17556 // C++1y [expr.const]p2: 17557 // A conditional-expression e is a core constant expression unless the 17558 // evaluation of e, following the rules of the abstract machine, would 17559 // evaluate [...] a lambda-expression. 17560 D = diag::err_lambda_in_constant_expression; 17561 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 17562 // C++17 [expr.prim.lamda]p2: 17563 // A lambda-expression shall not appear [...] in a template-argument. 17564 D = diag::err_lambda_in_invalid_context; 17565 } else 17566 llvm_unreachable("Couldn't infer lambda error message."); 17567 17568 for (const auto *L : Rec.Lambdas) 17569 Diag(L->getBeginLoc(), D); 17570 } 17571 } 17572 17573 WarnOnPendingNoDerefs(Rec); 17574 HandleImmediateInvocations(*this, Rec); 17575 17576 // Warn on any volatile-qualified simple-assignments that are not discarded- 17577 // value expressions nor unevaluated operands (those cases get removed from 17578 // this list by CheckUnusedVolatileAssignment). 17579 for (auto *BO : Rec.VolatileAssignmentLHSs) 17580 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 17581 << BO->getType(); 17582 17583 // When are coming out of an unevaluated context, clear out any 17584 // temporaries that we may have created as part of the evaluation of 17585 // the expression in that context: they aren't relevant because they 17586 // will never be constructed. 17587 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 17588 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 17589 ExprCleanupObjects.end()); 17590 Cleanup = Rec.ParentCleanup; 17591 CleanupVarDeclMarking(); 17592 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 17593 // Otherwise, merge the contexts together. 17594 } else { 17595 Cleanup.mergeFrom(Rec.ParentCleanup); 17596 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 17597 Rec.SavedMaybeODRUseExprs.end()); 17598 } 17599 17600 // Pop the current expression evaluation context off the stack. 17601 ExprEvalContexts.pop_back(); 17602 17603 // The global expression evaluation context record is never popped. 17604 ExprEvalContexts.back().NumTypos += NumTypos; 17605 } 17606 17607 void Sema::DiscardCleanupsInEvaluationContext() { 17608 ExprCleanupObjects.erase( 17609 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 17610 ExprCleanupObjects.end()); 17611 Cleanup.reset(); 17612 MaybeODRUseExprs.clear(); 17613 } 17614 17615 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 17616 ExprResult Result = CheckPlaceholderExpr(E); 17617 if (Result.isInvalid()) 17618 return ExprError(); 17619 E = Result.get(); 17620 if (!E->getType()->isVariablyModifiedType()) 17621 return E; 17622 return TransformToPotentiallyEvaluated(E); 17623 } 17624 17625 /// Are we in a context that is potentially constant evaluated per C++20 17626 /// [expr.const]p12? 17627 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 17628 /// C++2a [expr.const]p12: 17629 // An expression or conversion is potentially constant evaluated if it is 17630 switch (SemaRef.ExprEvalContexts.back().Context) { 17631 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17632 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 17633 17634 // -- a manifestly constant-evaluated expression, 17635 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17636 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17637 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17638 // -- a potentially-evaluated expression, 17639 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17640 // -- an immediate subexpression of a braced-init-list, 17641 17642 // -- [FIXME] an expression of the form & cast-expression that occurs 17643 // within a templated entity 17644 // -- a subexpression of one of the above that is not a subexpression of 17645 // a nested unevaluated operand. 17646 return true; 17647 17648 case Sema::ExpressionEvaluationContext::Unevaluated: 17649 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17650 // Expressions in this context are never evaluated. 17651 return false; 17652 } 17653 llvm_unreachable("Invalid context"); 17654 } 17655 17656 /// Return true if this function has a calling convention that requires mangling 17657 /// in the size of the parameter pack. 17658 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 17659 // These manglings don't do anything on non-Windows or non-x86 platforms, so 17660 // we don't need parameter type sizes. 17661 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 17662 if (!TT.isOSWindows() || !TT.isX86()) 17663 return false; 17664 17665 // If this is C++ and this isn't an extern "C" function, parameters do not 17666 // need to be complete. In this case, C++ mangling will apply, which doesn't 17667 // use the size of the parameters. 17668 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 17669 return false; 17670 17671 // Stdcall, fastcall, and vectorcall need this special treatment. 17672 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 17673 switch (CC) { 17674 case CC_X86StdCall: 17675 case CC_X86FastCall: 17676 case CC_X86VectorCall: 17677 return true; 17678 default: 17679 break; 17680 } 17681 return false; 17682 } 17683 17684 /// Require that all of the parameter types of function be complete. Normally, 17685 /// parameter types are only required to be complete when a function is called 17686 /// or defined, but to mangle functions with certain calling conventions, the 17687 /// mangler needs to know the size of the parameter list. In this situation, 17688 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 17689 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 17690 /// result in a linker error. Clang doesn't implement this behavior, and instead 17691 /// attempts to error at compile time. 17692 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 17693 SourceLocation Loc) { 17694 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 17695 FunctionDecl *FD; 17696 ParmVarDecl *Param; 17697 17698 public: 17699 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 17700 : FD(FD), Param(Param) {} 17701 17702 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17703 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 17704 StringRef CCName; 17705 switch (CC) { 17706 case CC_X86StdCall: 17707 CCName = "stdcall"; 17708 break; 17709 case CC_X86FastCall: 17710 CCName = "fastcall"; 17711 break; 17712 case CC_X86VectorCall: 17713 CCName = "vectorcall"; 17714 break; 17715 default: 17716 llvm_unreachable("CC does not need mangling"); 17717 } 17718 17719 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 17720 << Param->getDeclName() << FD->getDeclName() << CCName; 17721 } 17722 }; 17723 17724 for (ParmVarDecl *Param : FD->parameters()) { 17725 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 17726 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 17727 } 17728 } 17729 17730 namespace { 17731 enum class OdrUseContext { 17732 /// Declarations in this context are not odr-used. 17733 None, 17734 /// Declarations in this context are formally odr-used, but this is a 17735 /// dependent context. 17736 Dependent, 17737 /// Declarations in this context are odr-used but not actually used (yet). 17738 FormallyOdrUsed, 17739 /// Declarations in this context are used. 17740 Used 17741 }; 17742 } 17743 17744 /// Are we within a context in which references to resolved functions or to 17745 /// variables result in odr-use? 17746 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 17747 OdrUseContext Result; 17748 17749 switch (SemaRef.ExprEvalContexts.back().Context) { 17750 case Sema::ExpressionEvaluationContext::Unevaluated: 17751 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17752 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17753 return OdrUseContext::None; 17754 17755 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17756 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 17757 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17758 Result = OdrUseContext::Used; 17759 break; 17760 17761 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17762 Result = OdrUseContext::FormallyOdrUsed; 17763 break; 17764 17765 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17766 // A default argument formally results in odr-use, but doesn't actually 17767 // result in a use in any real sense until it itself is used. 17768 Result = OdrUseContext::FormallyOdrUsed; 17769 break; 17770 } 17771 17772 if (SemaRef.CurContext->isDependentContext()) 17773 return OdrUseContext::Dependent; 17774 17775 return Result; 17776 } 17777 17778 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 17779 if (!Func->isConstexpr()) 17780 return false; 17781 17782 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 17783 return true; 17784 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 17785 return CCD && CCD->getInheritedConstructor(); 17786 } 17787 17788 /// Mark a function referenced, and check whether it is odr-used 17789 /// (C++ [basic.def.odr]p2, C99 6.9p3) 17790 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 17791 bool MightBeOdrUse) { 17792 assert(Func && "No function?"); 17793 17794 Func->setReferenced(); 17795 17796 // Recursive functions aren't really used until they're used from some other 17797 // context. 17798 bool IsRecursiveCall = CurContext == Func; 17799 17800 // C++11 [basic.def.odr]p3: 17801 // A function whose name appears as a potentially-evaluated expression is 17802 // odr-used if it is the unique lookup result or the selected member of a 17803 // set of overloaded functions [...]. 17804 // 17805 // We (incorrectly) mark overload resolution as an unevaluated context, so we 17806 // can just check that here. 17807 OdrUseContext OdrUse = 17808 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 17809 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 17810 OdrUse = OdrUseContext::FormallyOdrUsed; 17811 17812 // Trivial default constructors and destructors are never actually used. 17813 // FIXME: What about other special members? 17814 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 17815 OdrUse == OdrUseContext::Used) { 17816 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 17817 if (Constructor->isDefaultConstructor()) 17818 OdrUse = OdrUseContext::FormallyOdrUsed; 17819 if (isa<CXXDestructorDecl>(Func)) 17820 OdrUse = OdrUseContext::FormallyOdrUsed; 17821 } 17822 17823 // C++20 [expr.const]p12: 17824 // A function [...] is needed for constant evaluation if it is [...] a 17825 // constexpr function that is named by an expression that is potentially 17826 // constant evaluated 17827 bool NeededForConstantEvaluation = 17828 isPotentiallyConstantEvaluatedContext(*this) && 17829 isImplicitlyDefinableConstexprFunction(Func); 17830 17831 // Determine whether we require a function definition to exist, per 17832 // C++11 [temp.inst]p3: 17833 // Unless a function template specialization has been explicitly 17834 // instantiated or explicitly specialized, the function template 17835 // specialization is implicitly instantiated when the specialization is 17836 // referenced in a context that requires a function definition to exist. 17837 // C++20 [temp.inst]p7: 17838 // The existence of a definition of a [...] function is considered to 17839 // affect the semantics of the program if the [...] function is needed for 17840 // constant evaluation by an expression 17841 // C++20 [basic.def.odr]p10: 17842 // Every program shall contain exactly one definition of every non-inline 17843 // function or variable that is odr-used in that program outside of a 17844 // discarded statement 17845 // C++20 [special]p1: 17846 // The implementation will implicitly define [defaulted special members] 17847 // if they are odr-used or needed for constant evaluation. 17848 // 17849 // Note that we skip the implicit instantiation of templates that are only 17850 // used in unused default arguments or by recursive calls to themselves. 17851 // This is formally non-conforming, but seems reasonable in practice. 17852 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 17853 NeededForConstantEvaluation); 17854 17855 // C++14 [temp.expl.spec]p6: 17856 // If a template [...] is explicitly specialized then that specialization 17857 // shall be declared before the first use of that specialization that would 17858 // cause an implicit instantiation to take place, in every translation unit 17859 // in which such a use occurs 17860 if (NeedDefinition && 17861 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 17862 Func->getMemberSpecializationInfo())) 17863 checkSpecializationVisibility(Loc, Func); 17864 17865 if (getLangOpts().CUDA) 17866 CheckCUDACall(Loc, Func); 17867 17868 if (getLangOpts().SYCLIsDevice) 17869 checkSYCLDeviceFunction(Loc, Func); 17870 17871 // If we need a definition, try to create one. 17872 if (NeedDefinition && !Func->getBody()) { 17873 runWithSufficientStackSpace(Loc, [&] { 17874 if (CXXConstructorDecl *Constructor = 17875 dyn_cast<CXXConstructorDecl>(Func)) { 17876 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 17877 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 17878 if (Constructor->isDefaultConstructor()) { 17879 if (Constructor->isTrivial() && 17880 !Constructor->hasAttr<DLLExportAttr>()) 17881 return; 17882 DefineImplicitDefaultConstructor(Loc, Constructor); 17883 } else if (Constructor->isCopyConstructor()) { 17884 DefineImplicitCopyConstructor(Loc, Constructor); 17885 } else if (Constructor->isMoveConstructor()) { 17886 DefineImplicitMoveConstructor(Loc, Constructor); 17887 } 17888 } else if (Constructor->getInheritedConstructor()) { 17889 DefineInheritingConstructor(Loc, Constructor); 17890 } 17891 } else if (CXXDestructorDecl *Destructor = 17892 dyn_cast<CXXDestructorDecl>(Func)) { 17893 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17894 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17895 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17896 return; 17897 DefineImplicitDestructor(Loc, Destructor); 17898 } 17899 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17900 MarkVTableUsed(Loc, Destructor->getParent()); 17901 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17902 if (MethodDecl->isOverloadedOperator() && 17903 MethodDecl->getOverloadedOperator() == OO_Equal) { 17904 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17905 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17906 if (MethodDecl->isCopyAssignmentOperator()) 17907 DefineImplicitCopyAssignment(Loc, MethodDecl); 17908 else if (MethodDecl->isMoveAssignmentOperator()) 17909 DefineImplicitMoveAssignment(Loc, MethodDecl); 17910 } 17911 } else if (isa<CXXConversionDecl>(MethodDecl) && 17912 MethodDecl->getParent()->isLambda()) { 17913 CXXConversionDecl *Conversion = 17914 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17915 if (Conversion->isLambdaToBlockPointerConversion()) 17916 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17917 else 17918 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17919 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17920 MarkVTableUsed(Loc, MethodDecl->getParent()); 17921 } 17922 17923 if (Func->isDefaulted() && !Func->isDeleted()) { 17924 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17925 if (DCK != DefaultedComparisonKind::None) 17926 DefineDefaultedComparison(Loc, Func, DCK); 17927 } 17928 17929 // Implicit instantiation of function templates and member functions of 17930 // class templates. 17931 if (Func->isImplicitlyInstantiable()) { 17932 TemplateSpecializationKind TSK = 17933 Func->getTemplateSpecializationKindForInstantiation(); 17934 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17935 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17936 if (FirstInstantiation) { 17937 PointOfInstantiation = Loc; 17938 if (auto *MSI = Func->getMemberSpecializationInfo()) 17939 MSI->setPointOfInstantiation(Loc); 17940 // FIXME: Notify listener. 17941 else 17942 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17943 } else if (TSK != TSK_ImplicitInstantiation) { 17944 // Use the point of use as the point of instantiation, instead of the 17945 // point of explicit instantiation (which we track as the actual point 17946 // of instantiation). This gives better backtraces in diagnostics. 17947 PointOfInstantiation = Loc; 17948 } 17949 17950 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17951 Func->isConstexpr()) { 17952 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17953 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17954 CodeSynthesisContexts.size()) 17955 PendingLocalImplicitInstantiations.push_back( 17956 std::make_pair(Func, PointOfInstantiation)); 17957 else if (Func->isConstexpr()) 17958 // Do not defer instantiations of constexpr functions, to avoid the 17959 // expression evaluator needing to call back into Sema if it sees a 17960 // call to such a function. 17961 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17962 else { 17963 Func->setInstantiationIsPending(true); 17964 PendingInstantiations.push_back( 17965 std::make_pair(Func, PointOfInstantiation)); 17966 // Notify the consumer that a function was implicitly instantiated. 17967 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17968 } 17969 } 17970 } else { 17971 // Walk redefinitions, as some of them may be instantiable. 17972 for (auto i : Func->redecls()) { 17973 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17974 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17975 } 17976 } 17977 }); 17978 } 17979 17980 // C++14 [except.spec]p17: 17981 // An exception-specification is considered to be needed when: 17982 // - the function is odr-used or, if it appears in an unevaluated operand, 17983 // would be odr-used if the expression were potentially-evaluated; 17984 // 17985 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17986 // function is a pure virtual function we're calling, and in that case the 17987 // function was selected by overload resolution and we need to resolve its 17988 // exception specification for a different reason. 17989 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17990 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17991 ResolveExceptionSpec(Loc, FPT); 17992 17993 // If this is the first "real" use, act on that. 17994 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17995 // Keep track of used but undefined functions. 17996 if (!Func->isDefined()) { 17997 if (mightHaveNonExternalLinkage(Func)) 17998 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17999 else if (Func->getMostRecentDecl()->isInlined() && 18000 !LangOpts.GNUInline && 18001 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 18002 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 18003 else if (isExternalWithNoLinkageType(Func)) 18004 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 18005 } 18006 18007 // Some x86 Windows calling conventions mangle the size of the parameter 18008 // pack into the name. Computing the size of the parameters requires the 18009 // parameter types to be complete. Check that now. 18010 if (funcHasParameterSizeMangling(*this, Func)) 18011 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 18012 18013 // In the MS C++ ABI, the compiler emits destructor variants where they are 18014 // used. If the destructor is used here but defined elsewhere, mark the 18015 // virtual base destructors referenced. If those virtual base destructors 18016 // are inline, this will ensure they are defined when emitting the complete 18017 // destructor variant. This checking may be redundant if the destructor is 18018 // provided later in this TU. 18019 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 18020 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 18021 CXXRecordDecl *Parent = Dtor->getParent(); 18022 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 18023 CheckCompleteDestructorVariant(Loc, Dtor); 18024 } 18025 } 18026 18027 Func->markUsed(Context); 18028 } 18029 } 18030 18031 /// Directly mark a variable odr-used. Given a choice, prefer to use 18032 /// MarkVariableReferenced since it does additional checks and then 18033 /// calls MarkVarDeclODRUsed. 18034 /// If the variable must be captured: 18035 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 18036 /// - else capture it in the DeclContext that maps to the 18037 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 18038 static void 18039 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 18040 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 18041 // Keep track of used but undefined variables. 18042 // FIXME: We shouldn't suppress this warning for static data members. 18043 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 18044 (!Var->isExternallyVisible() || Var->isInline() || 18045 SemaRef.isExternalWithNoLinkageType(Var)) && 18046 !(Var->isStaticDataMember() && Var->hasInit())) { 18047 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 18048 if (old.isInvalid()) 18049 old = Loc; 18050 } 18051 QualType CaptureType, DeclRefType; 18052 if (SemaRef.LangOpts.OpenMP) 18053 SemaRef.tryCaptureOpenMPLambdas(Var); 18054 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 18055 /*EllipsisLoc*/ SourceLocation(), 18056 /*BuildAndDiagnose*/ true, 18057 CaptureType, DeclRefType, 18058 FunctionScopeIndexToStopAt); 18059 18060 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) { 18061 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 18062 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 18063 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 18064 if (VarTarget == Sema::CVT_Host && 18065 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 18066 UserTarget == Sema::CFT_Global)) { 18067 // Diagnose ODR-use of host global variables in device functions. 18068 // Reference of device global variables in host functions is allowed 18069 // through shadow variables therefore it is not diagnosed. 18070 if (SemaRef.LangOpts.CUDAIsDevice) { 18071 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 18072 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 18073 SemaRef.targetDiag(Var->getLocation(), 18074 Var->getType().isConstQualified() 18075 ? diag::note_cuda_const_var_unpromoted 18076 : diag::note_cuda_host_var); 18077 } 18078 } else if (VarTarget == Sema::CVT_Device && 18079 (UserTarget == Sema::CFT_Host || 18080 UserTarget == Sema::CFT_HostDevice)) { 18081 // Record a CUDA/HIP device side variable if it is ODR-used 18082 // by host code. This is done conservatively, when the variable is 18083 // referenced in any of the following contexts: 18084 // - a non-function context 18085 // - a host function 18086 // - a host device function 18087 // This makes the ODR-use of the device side variable by host code to 18088 // be visible in the device compilation for the compiler to be able to 18089 // emit template variables instantiated by host code only and to 18090 // externalize the static device side variable ODR-used by host code. 18091 if (!Var->hasExternalStorage()) 18092 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 18093 else if (SemaRef.LangOpts.GPURelocatableDeviceCode) 18094 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var); 18095 } 18096 } 18097 18098 Var->markUsed(SemaRef.Context); 18099 } 18100 18101 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 18102 SourceLocation Loc, 18103 unsigned CapturingScopeIndex) { 18104 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 18105 } 18106 18107 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 18108 ValueDecl *var) { 18109 DeclContext *VarDC = var->getDeclContext(); 18110 18111 // If the parameter still belongs to the translation unit, then 18112 // we're actually just using one parameter in the declaration of 18113 // the next. 18114 if (isa<ParmVarDecl>(var) && 18115 isa<TranslationUnitDecl>(VarDC)) 18116 return; 18117 18118 // For C code, don't diagnose about capture if we're not actually in code 18119 // right now; it's impossible to write a non-constant expression outside of 18120 // function context, so we'll get other (more useful) diagnostics later. 18121 // 18122 // For C++, things get a bit more nasty... it would be nice to suppress this 18123 // diagnostic for certain cases like using a local variable in an array bound 18124 // for a member of a local class, but the correct predicate is not obvious. 18125 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 18126 return; 18127 18128 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 18129 unsigned ContextKind = 3; // unknown 18130 if (isa<CXXMethodDecl>(VarDC) && 18131 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 18132 ContextKind = 2; 18133 } else if (isa<FunctionDecl>(VarDC)) { 18134 ContextKind = 0; 18135 } else if (isa<BlockDecl>(VarDC)) { 18136 ContextKind = 1; 18137 } 18138 18139 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 18140 << var << ValueKind << ContextKind << VarDC; 18141 S.Diag(var->getLocation(), diag::note_entity_declared_at) 18142 << var; 18143 18144 // FIXME: Add additional diagnostic info about class etc. which prevents 18145 // capture. 18146 } 18147 18148 18149 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 18150 bool &SubCapturesAreNested, 18151 QualType &CaptureType, 18152 QualType &DeclRefType) { 18153 // Check whether we've already captured it. 18154 if (CSI->CaptureMap.count(Var)) { 18155 // If we found a capture, any subcaptures are nested. 18156 SubCapturesAreNested = true; 18157 18158 // Retrieve the capture type for this variable. 18159 CaptureType = CSI->getCapture(Var).getCaptureType(); 18160 18161 // Compute the type of an expression that refers to this variable. 18162 DeclRefType = CaptureType.getNonReferenceType(); 18163 18164 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 18165 // are mutable in the sense that user can change their value - they are 18166 // private instances of the captured declarations. 18167 const Capture &Cap = CSI->getCapture(Var); 18168 if (Cap.isCopyCapture() && 18169 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 18170 !(isa<CapturedRegionScopeInfo>(CSI) && 18171 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 18172 DeclRefType.addConst(); 18173 return true; 18174 } 18175 return false; 18176 } 18177 18178 // Only block literals, captured statements, and lambda expressions can 18179 // capture; other scopes don't work. 18180 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 18181 SourceLocation Loc, 18182 const bool Diagnose, Sema &S) { 18183 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 18184 return getLambdaAwareParentOfDeclContext(DC); 18185 else if (Var->hasLocalStorage()) { 18186 if (Diagnose) 18187 diagnoseUncapturableValueReference(S, Loc, Var); 18188 } 18189 return nullptr; 18190 } 18191 18192 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18193 // certain types of variables (unnamed, variably modified types etc.) 18194 // so check for eligibility. 18195 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 18196 SourceLocation Loc, 18197 const bool Diagnose, Sema &S) { 18198 18199 bool IsBlock = isa<BlockScopeInfo>(CSI); 18200 bool IsLambda = isa<LambdaScopeInfo>(CSI); 18201 18202 // Lambdas are not allowed to capture unnamed variables 18203 // (e.g. anonymous unions). 18204 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 18205 // assuming that's the intent. 18206 if (IsLambda && !Var->getDeclName()) { 18207 if (Diagnose) { 18208 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 18209 S.Diag(Var->getLocation(), diag::note_declared_at); 18210 } 18211 return false; 18212 } 18213 18214 // Prohibit variably-modified types in blocks; they're difficult to deal with. 18215 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 18216 if (Diagnose) { 18217 S.Diag(Loc, diag::err_ref_vm_type); 18218 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18219 } 18220 return false; 18221 } 18222 // Prohibit structs with flexible array members too. 18223 // We cannot capture what is in the tail end of the struct. 18224 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 18225 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 18226 if (Diagnose) { 18227 if (IsBlock) 18228 S.Diag(Loc, diag::err_ref_flexarray_type); 18229 else 18230 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 18231 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18232 } 18233 return false; 18234 } 18235 } 18236 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 18237 // Lambdas and captured statements are not allowed to capture __block 18238 // variables; they don't support the expected semantics. 18239 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 18240 if (Diagnose) { 18241 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 18242 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18243 } 18244 return false; 18245 } 18246 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 18247 if (S.getLangOpts().OpenCL && IsBlock && 18248 Var->getType()->isBlockPointerType()) { 18249 if (Diagnose) 18250 S.Diag(Loc, diag::err_opencl_block_ref_block); 18251 return false; 18252 } 18253 18254 return true; 18255 } 18256 18257 // Returns true if the capture by block was successful. 18258 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 18259 SourceLocation Loc, 18260 const bool BuildAndDiagnose, 18261 QualType &CaptureType, 18262 QualType &DeclRefType, 18263 const bool Nested, 18264 Sema &S, bool Invalid) { 18265 bool ByRef = false; 18266 18267 // Blocks are not allowed to capture arrays, excepting OpenCL. 18268 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 18269 // (decayed to pointers). 18270 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 18271 if (BuildAndDiagnose) { 18272 S.Diag(Loc, diag::err_ref_array_type); 18273 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18274 Invalid = true; 18275 } else { 18276 return false; 18277 } 18278 } 18279 18280 // Forbid the block-capture of autoreleasing variables. 18281 if (!Invalid && 18282 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 18283 if (BuildAndDiagnose) { 18284 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 18285 << /*block*/ 0; 18286 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18287 Invalid = true; 18288 } else { 18289 return false; 18290 } 18291 } 18292 18293 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 18294 if (const auto *PT = CaptureType->getAs<PointerType>()) { 18295 QualType PointeeTy = PT->getPointeeType(); 18296 18297 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 18298 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 18299 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 18300 if (BuildAndDiagnose) { 18301 SourceLocation VarLoc = Var->getLocation(); 18302 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 18303 S.Diag(VarLoc, diag::note_declare_parameter_strong); 18304 } 18305 } 18306 } 18307 18308 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 18309 if (HasBlocksAttr || CaptureType->isReferenceType() || 18310 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 18311 // Block capture by reference does not change the capture or 18312 // declaration reference types. 18313 ByRef = true; 18314 } else { 18315 // Block capture by copy introduces 'const'. 18316 CaptureType = CaptureType.getNonReferenceType().withConst(); 18317 DeclRefType = CaptureType; 18318 } 18319 18320 // Actually capture the variable. 18321 if (BuildAndDiagnose) 18322 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 18323 CaptureType, Invalid); 18324 18325 return !Invalid; 18326 } 18327 18328 18329 /// Capture the given variable in the captured region. 18330 static bool captureInCapturedRegion( 18331 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 18332 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 18333 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 18334 bool IsTopScope, Sema &S, bool Invalid) { 18335 // By default, capture variables by reference. 18336 bool ByRef = true; 18337 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 18338 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 18339 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 18340 // Using an LValue reference type is consistent with Lambdas (see below). 18341 if (S.isOpenMPCapturedDecl(Var)) { 18342 bool HasConst = DeclRefType.isConstQualified(); 18343 DeclRefType = DeclRefType.getUnqualifiedType(); 18344 // Don't lose diagnostics about assignments to const. 18345 if (HasConst) 18346 DeclRefType.addConst(); 18347 } 18348 // Do not capture firstprivates in tasks. 18349 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 18350 OMPC_unknown) 18351 return true; 18352 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 18353 RSI->OpenMPCaptureLevel); 18354 } 18355 18356 if (ByRef) 18357 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 18358 else 18359 CaptureType = DeclRefType; 18360 18361 // Actually capture the variable. 18362 if (BuildAndDiagnose) 18363 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 18364 Loc, SourceLocation(), CaptureType, Invalid); 18365 18366 return !Invalid; 18367 } 18368 18369 /// Capture the given variable in the lambda. 18370 static bool captureInLambda(LambdaScopeInfo *LSI, 18371 VarDecl *Var, 18372 SourceLocation Loc, 18373 const bool BuildAndDiagnose, 18374 QualType &CaptureType, 18375 QualType &DeclRefType, 18376 const bool RefersToCapturedVariable, 18377 const Sema::TryCaptureKind Kind, 18378 SourceLocation EllipsisLoc, 18379 const bool IsTopScope, 18380 Sema &S, bool Invalid) { 18381 // Determine whether we are capturing by reference or by value. 18382 bool ByRef = false; 18383 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 18384 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 18385 } else { 18386 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 18387 } 18388 18389 // Compute the type of the field that will capture this variable. 18390 if (ByRef) { 18391 // C++11 [expr.prim.lambda]p15: 18392 // An entity is captured by reference if it is implicitly or 18393 // explicitly captured but not captured by copy. It is 18394 // unspecified whether additional unnamed non-static data 18395 // members are declared in the closure type for entities 18396 // captured by reference. 18397 // 18398 // FIXME: It is not clear whether we want to build an lvalue reference 18399 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 18400 // to do the former, while EDG does the latter. Core issue 1249 will 18401 // clarify, but for now we follow GCC because it's a more permissive and 18402 // easily defensible position. 18403 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 18404 } else { 18405 // C++11 [expr.prim.lambda]p14: 18406 // For each entity captured by copy, an unnamed non-static 18407 // data member is declared in the closure type. The 18408 // declaration order of these members is unspecified. The type 18409 // of such a data member is the type of the corresponding 18410 // captured entity if the entity is not a reference to an 18411 // object, or the referenced type otherwise. [Note: If the 18412 // captured entity is a reference to a function, the 18413 // corresponding data member is also a reference to a 18414 // function. - end note ] 18415 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 18416 if (!RefType->getPointeeType()->isFunctionType()) 18417 CaptureType = RefType->getPointeeType(); 18418 } 18419 18420 // Forbid the lambda copy-capture of autoreleasing variables. 18421 if (!Invalid && 18422 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 18423 if (BuildAndDiagnose) { 18424 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 18425 S.Diag(Var->getLocation(), diag::note_previous_decl) 18426 << Var->getDeclName(); 18427 Invalid = true; 18428 } else { 18429 return false; 18430 } 18431 } 18432 18433 // Make sure that by-copy captures are of a complete and non-abstract type. 18434 if (!Invalid && BuildAndDiagnose) { 18435 if (!CaptureType->isDependentType() && 18436 S.RequireCompleteSizedType( 18437 Loc, CaptureType, 18438 diag::err_capture_of_incomplete_or_sizeless_type, 18439 Var->getDeclName())) 18440 Invalid = true; 18441 else if (S.RequireNonAbstractType(Loc, CaptureType, 18442 diag::err_capture_of_abstract_type)) 18443 Invalid = true; 18444 } 18445 } 18446 18447 // Compute the type of a reference to this captured variable. 18448 if (ByRef) 18449 DeclRefType = CaptureType.getNonReferenceType(); 18450 else { 18451 // C++ [expr.prim.lambda]p5: 18452 // The closure type for a lambda-expression has a public inline 18453 // function call operator [...]. This function call operator is 18454 // declared const (9.3.1) if and only if the lambda-expression's 18455 // parameter-declaration-clause is not followed by mutable. 18456 DeclRefType = CaptureType.getNonReferenceType(); 18457 if (!LSI->Mutable && !CaptureType->isReferenceType()) 18458 DeclRefType.addConst(); 18459 } 18460 18461 // Add the capture. 18462 if (BuildAndDiagnose) 18463 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 18464 Loc, EllipsisLoc, CaptureType, Invalid); 18465 18466 return !Invalid; 18467 } 18468 18469 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 18470 // Offer a Copy fix even if the type is dependent. 18471 if (Var->getType()->isDependentType()) 18472 return true; 18473 QualType T = Var->getType().getNonReferenceType(); 18474 if (T.isTriviallyCopyableType(Context)) 18475 return true; 18476 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 18477 18478 if (!(RD = RD->getDefinition())) 18479 return false; 18480 if (RD->hasSimpleCopyConstructor()) 18481 return true; 18482 if (RD->hasUserDeclaredCopyConstructor()) 18483 for (CXXConstructorDecl *Ctor : RD->ctors()) 18484 if (Ctor->isCopyConstructor()) 18485 return !Ctor->isDeleted(); 18486 } 18487 return false; 18488 } 18489 18490 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 18491 /// default capture. Fixes may be omitted if they aren't allowed by the 18492 /// standard, for example we can't emit a default copy capture fix-it if we 18493 /// already explicitly copy capture capture another variable. 18494 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 18495 VarDecl *Var) { 18496 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 18497 // Don't offer Capture by copy of default capture by copy fixes if Var is 18498 // known not to be copy constructible. 18499 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 18500 18501 SmallString<32> FixBuffer; 18502 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 18503 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 18504 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 18505 if (ShouldOfferCopyFix) { 18506 // Offer fixes to insert an explicit capture for the variable. 18507 // [] -> [VarName] 18508 // [OtherCapture] -> [OtherCapture, VarName] 18509 FixBuffer.assign({Separator, Var->getName()}); 18510 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 18511 << Var << /*value*/ 0 18512 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 18513 } 18514 // As above but capture by reference. 18515 FixBuffer.assign({Separator, "&", Var->getName()}); 18516 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 18517 << Var << /*reference*/ 1 18518 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 18519 } 18520 18521 // Only try to offer default capture if there are no captures excluding this 18522 // and init captures. 18523 // [this]: OK. 18524 // [X = Y]: OK. 18525 // [&A, &B]: Don't offer. 18526 // [A, B]: Don't offer. 18527 if (llvm::any_of(LSI->Captures, [](Capture &C) { 18528 return !C.isThisCapture() && !C.isInitCapture(); 18529 })) 18530 return; 18531 18532 // The default capture specifiers, '=' or '&', must appear first in the 18533 // capture body. 18534 SourceLocation DefaultInsertLoc = 18535 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 18536 18537 if (ShouldOfferCopyFix) { 18538 bool CanDefaultCopyCapture = true; 18539 // [=, *this] OK since c++17 18540 // [=, this] OK since c++20 18541 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 18542 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 18543 ? LSI->getCXXThisCapture().isCopyCapture() 18544 : false; 18545 // We can't use default capture by copy if any captures already specified 18546 // capture by copy. 18547 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 18548 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 18549 })) { 18550 FixBuffer.assign({"=", Separator}); 18551 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 18552 << /*value*/ 0 18553 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 18554 } 18555 } 18556 18557 // We can't use default capture by reference if any captures already specified 18558 // capture by reference. 18559 if (llvm::none_of(LSI->Captures, [](Capture &C) { 18560 return !C.isInitCapture() && C.isReferenceCapture() && 18561 !C.isThisCapture(); 18562 })) { 18563 FixBuffer.assign({"&", Separator}); 18564 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 18565 << /*reference*/ 1 18566 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 18567 } 18568 } 18569 18570 bool Sema::tryCaptureVariable( 18571 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 18572 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 18573 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 18574 // An init-capture is notionally from the context surrounding its 18575 // declaration, but its parent DC is the lambda class. 18576 DeclContext *VarDC = Var->getDeclContext(); 18577 if (Var->isInitCapture()) 18578 VarDC = VarDC->getParent(); 18579 18580 DeclContext *DC = CurContext; 18581 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 18582 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 18583 // We need to sync up the Declaration Context with the 18584 // FunctionScopeIndexToStopAt 18585 if (FunctionScopeIndexToStopAt) { 18586 unsigned FSIndex = FunctionScopes.size() - 1; 18587 while (FSIndex != MaxFunctionScopesIndex) { 18588 DC = getLambdaAwareParentOfDeclContext(DC); 18589 --FSIndex; 18590 } 18591 } 18592 18593 18594 // If the variable is declared in the current context, there is no need to 18595 // capture it. 18596 if (VarDC == DC) return true; 18597 18598 // Capture global variables if it is required to use private copy of this 18599 // variable. 18600 bool IsGlobal = !Var->hasLocalStorage(); 18601 if (IsGlobal && 18602 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 18603 MaxFunctionScopesIndex))) 18604 return true; 18605 Var = Var->getCanonicalDecl(); 18606 18607 // Walk up the stack to determine whether we can capture the variable, 18608 // performing the "simple" checks that don't depend on type. We stop when 18609 // we've either hit the declared scope of the variable or find an existing 18610 // capture of that variable. We start from the innermost capturing-entity 18611 // (the DC) and ensure that all intervening capturing-entities 18612 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 18613 // declcontext can either capture the variable or have already captured 18614 // the variable. 18615 CaptureType = Var->getType(); 18616 DeclRefType = CaptureType.getNonReferenceType(); 18617 bool Nested = false; 18618 bool Explicit = (Kind != TryCapture_Implicit); 18619 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 18620 do { 18621 // Only block literals, captured statements, and lambda expressions can 18622 // capture; other scopes don't work. 18623 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 18624 ExprLoc, 18625 BuildAndDiagnose, 18626 *this); 18627 // We need to check for the parent *first* because, if we *have* 18628 // private-captured a global variable, we need to recursively capture it in 18629 // intermediate blocks, lambdas, etc. 18630 if (!ParentDC) { 18631 if (IsGlobal) { 18632 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 18633 break; 18634 } 18635 return true; 18636 } 18637 18638 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 18639 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 18640 18641 18642 // Check whether we've already captured it. 18643 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 18644 DeclRefType)) { 18645 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 18646 break; 18647 } 18648 // If we are instantiating a generic lambda call operator body, 18649 // we do not want to capture new variables. What was captured 18650 // during either a lambdas transformation or initial parsing 18651 // should be used. 18652 if (isGenericLambdaCallOperatorSpecialization(DC)) { 18653 if (BuildAndDiagnose) { 18654 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18655 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 18656 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18657 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18658 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18659 buildLambdaCaptureFixit(*this, LSI, Var); 18660 } else 18661 diagnoseUncapturableValueReference(*this, ExprLoc, Var); 18662 } 18663 return true; 18664 } 18665 18666 // Try to capture variable-length arrays types. 18667 if (Var->getType()->isVariablyModifiedType()) { 18668 // We're going to walk down into the type and look for VLA 18669 // expressions. 18670 QualType QTy = Var->getType(); 18671 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 18672 QTy = PVD->getOriginalType(); 18673 captureVariablyModifiedType(Context, QTy, CSI); 18674 } 18675 18676 if (getLangOpts().OpenMP) { 18677 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18678 // OpenMP private variables should not be captured in outer scope, so 18679 // just break here. Similarly, global variables that are captured in a 18680 // target region should not be captured outside the scope of the region. 18681 if (RSI->CapRegionKind == CR_OpenMP) { 18682 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 18683 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 18684 // If the variable is private (i.e. not captured) and has variably 18685 // modified type, we still need to capture the type for correct 18686 // codegen in all regions, associated with the construct. Currently, 18687 // it is captured in the innermost captured region only. 18688 if (IsOpenMPPrivateDecl != OMPC_unknown && 18689 Var->getType()->isVariablyModifiedType()) { 18690 QualType QTy = Var->getType(); 18691 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 18692 QTy = PVD->getOriginalType(); 18693 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 18694 I < E; ++I) { 18695 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 18696 FunctionScopes[FunctionScopesIndex - I]); 18697 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 18698 "Wrong number of captured regions associated with the " 18699 "OpenMP construct."); 18700 captureVariablyModifiedType(Context, QTy, OuterRSI); 18701 } 18702 } 18703 bool IsTargetCap = 18704 IsOpenMPPrivateDecl != OMPC_private && 18705 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 18706 RSI->OpenMPCaptureLevel); 18707 // Do not capture global if it is not privatized in outer regions. 18708 bool IsGlobalCap = 18709 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 18710 RSI->OpenMPCaptureLevel); 18711 18712 // When we detect target captures we are looking from inside the 18713 // target region, therefore we need to propagate the capture from the 18714 // enclosing region. Therefore, the capture is not initially nested. 18715 if (IsTargetCap) 18716 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 18717 18718 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 18719 (IsGlobal && !IsGlobalCap)) { 18720 Nested = !IsTargetCap; 18721 bool HasConst = DeclRefType.isConstQualified(); 18722 DeclRefType = DeclRefType.getUnqualifiedType(); 18723 // Don't lose diagnostics about assignments to const. 18724 if (HasConst) 18725 DeclRefType.addConst(); 18726 CaptureType = Context.getLValueReferenceType(DeclRefType); 18727 break; 18728 } 18729 } 18730 } 18731 } 18732 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 18733 // No capture-default, and this is not an explicit capture 18734 // so cannot capture this variable. 18735 if (BuildAndDiagnose) { 18736 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18737 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18738 auto *LSI = cast<LambdaScopeInfo>(CSI); 18739 if (LSI->Lambda) { 18740 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18741 buildLambdaCaptureFixit(*this, LSI, Var); 18742 } 18743 // FIXME: If we error out because an outer lambda can not implicitly 18744 // capture a variable that an inner lambda explicitly captures, we 18745 // should have the inner lambda do the explicit capture - because 18746 // it makes for cleaner diagnostics later. This would purely be done 18747 // so that the diagnostic does not misleadingly claim that a variable 18748 // can not be captured by a lambda implicitly even though it is captured 18749 // explicitly. Suggestion: 18750 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 18751 // at the function head 18752 // - cache the StartingDeclContext - this must be a lambda 18753 // - captureInLambda in the innermost lambda the variable. 18754 } 18755 return true; 18756 } 18757 18758 FunctionScopesIndex--; 18759 DC = ParentDC; 18760 Explicit = false; 18761 } while (!VarDC->Equals(DC)); 18762 18763 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 18764 // computing the type of the capture at each step, checking type-specific 18765 // requirements, and adding captures if requested. 18766 // If the variable had already been captured previously, we start capturing 18767 // at the lambda nested within that one. 18768 bool Invalid = false; 18769 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 18770 ++I) { 18771 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 18772 18773 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18774 // certain types of variables (unnamed, variably modified types etc.) 18775 // so check for eligibility. 18776 if (!Invalid) 18777 Invalid = 18778 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 18779 18780 // After encountering an error, if we're actually supposed to capture, keep 18781 // capturing in nested contexts to suppress any follow-on diagnostics. 18782 if (Invalid && !BuildAndDiagnose) 18783 return true; 18784 18785 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 18786 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18787 DeclRefType, Nested, *this, Invalid); 18788 Nested = true; 18789 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18790 Invalid = !captureInCapturedRegion( 18791 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 18792 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 18793 Nested = true; 18794 } else { 18795 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18796 Invalid = 18797 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18798 DeclRefType, Nested, Kind, EllipsisLoc, 18799 /*IsTopScope*/ I == N - 1, *this, Invalid); 18800 Nested = true; 18801 } 18802 18803 if (Invalid && !BuildAndDiagnose) 18804 return true; 18805 } 18806 return Invalid; 18807 } 18808 18809 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 18810 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 18811 QualType CaptureType; 18812 QualType DeclRefType; 18813 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 18814 /*BuildAndDiagnose=*/true, CaptureType, 18815 DeclRefType, nullptr); 18816 } 18817 18818 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 18819 QualType CaptureType; 18820 QualType DeclRefType; 18821 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18822 /*BuildAndDiagnose=*/false, CaptureType, 18823 DeclRefType, nullptr); 18824 } 18825 18826 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 18827 QualType CaptureType; 18828 QualType DeclRefType; 18829 18830 // Determine whether we can capture this variable. 18831 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18832 /*BuildAndDiagnose=*/false, CaptureType, 18833 DeclRefType, nullptr)) 18834 return QualType(); 18835 18836 return DeclRefType; 18837 } 18838 18839 namespace { 18840 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 18841 // The produced TemplateArgumentListInfo* points to data stored within this 18842 // object, so should only be used in contexts where the pointer will not be 18843 // used after the CopiedTemplateArgs object is destroyed. 18844 class CopiedTemplateArgs { 18845 bool HasArgs; 18846 TemplateArgumentListInfo TemplateArgStorage; 18847 public: 18848 template<typename RefExpr> 18849 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 18850 if (HasArgs) 18851 E->copyTemplateArgumentsInto(TemplateArgStorage); 18852 } 18853 operator TemplateArgumentListInfo*() 18854 #ifdef __has_cpp_attribute 18855 #if __has_cpp_attribute(clang::lifetimebound) 18856 [[clang::lifetimebound]] 18857 #endif 18858 #endif 18859 { 18860 return HasArgs ? &TemplateArgStorage : nullptr; 18861 } 18862 }; 18863 } 18864 18865 /// Walk the set of potential results of an expression and mark them all as 18866 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 18867 /// 18868 /// \return A new expression if we found any potential results, ExprEmpty() if 18869 /// not, and ExprError() if we diagnosed an error. 18870 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 18871 NonOdrUseReason NOUR) { 18872 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 18873 // an object that satisfies the requirements for appearing in a 18874 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 18875 // is immediately applied." This function handles the lvalue-to-rvalue 18876 // conversion part. 18877 // 18878 // If we encounter a node that claims to be an odr-use but shouldn't be, we 18879 // transform it into the relevant kind of non-odr-use node and rebuild the 18880 // tree of nodes leading to it. 18881 // 18882 // This is a mini-TreeTransform that only transforms a restricted subset of 18883 // nodes (and only certain operands of them). 18884 18885 // Rebuild a subexpression. 18886 auto Rebuild = [&](Expr *Sub) { 18887 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 18888 }; 18889 18890 // Check whether a potential result satisfies the requirements of NOUR. 18891 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 18892 // Any entity other than a VarDecl is always odr-used whenever it's named 18893 // in a potentially-evaluated expression. 18894 auto *VD = dyn_cast<VarDecl>(D); 18895 if (!VD) 18896 return true; 18897 18898 // C++2a [basic.def.odr]p4: 18899 // A variable x whose name appears as a potentially-evalauted expression 18900 // e is odr-used by e unless 18901 // -- x is a reference that is usable in constant expressions, or 18902 // -- x is a variable of non-reference type that is usable in constant 18903 // expressions and has no mutable subobjects, and e is an element of 18904 // the set of potential results of an expression of 18905 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18906 // conversion is applied, or 18907 // -- x is a variable of non-reference type, and e is an element of the 18908 // set of potential results of a discarded-value expression to which 18909 // the lvalue-to-rvalue conversion is not applied 18910 // 18911 // We check the first bullet and the "potentially-evaluated" condition in 18912 // BuildDeclRefExpr. We check the type requirements in the second bullet 18913 // in CheckLValueToRValueConversionOperand below. 18914 switch (NOUR) { 18915 case NOUR_None: 18916 case NOUR_Unevaluated: 18917 llvm_unreachable("unexpected non-odr-use-reason"); 18918 18919 case NOUR_Constant: 18920 // Constant references were handled when they were built. 18921 if (VD->getType()->isReferenceType()) 18922 return true; 18923 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18924 if (RD->hasMutableFields()) 18925 return true; 18926 if (!VD->isUsableInConstantExpressions(S.Context)) 18927 return true; 18928 break; 18929 18930 case NOUR_Discarded: 18931 if (VD->getType()->isReferenceType()) 18932 return true; 18933 break; 18934 } 18935 return false; 18936 }; 18937 18938 // Mark that this expression does not constitute an odr-use. 18939 auto MarkNotOdrUsed = [&] { 18940 S.MaybeODRUseExprs.remove(E); 18941 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18942 LSI->markVariableExprAsNonODRUsed(E); 18943 }; 18944 18945 // C++2a [basic.def.odr]p2: 18946 // The set of potential results of an expression e is defined as follows: 18947 switch (E->getStmtClass()) { 18948 // -- If e is an id-expression, ... 18949 case Expr::DeclRefExprClass: { 18950 auto *DRE = cast<DeclRefExpr>(E); 18951 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18952 break; 18953 18954 // Rebuild as a non-odr-use DeclRefExpr. 18955 MarkNotOdrUsed(); 18956 return DeclRefExpr::Create( 18957 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18958 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18959 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18960 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18961 } 18962 18963 case Expr::FunctionParmPackExprClass: { 18964 auto *FPPE = cast<FunctionParmPackExpr>(E); 18965 // If any of the declarations in the pack is odr-used, then the expression 18966 // as a whole constitutes an odr-use. 18967 for (VarDecl *D : *FPPE) 18968 if (IsPotentialResultOdrUsed(D)) 18969 return ExprEmpty(); 18970 18971 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18972 // nothing cares about whether we marked this as an odr-use, but it might 18973 // be useful for non-compiler tools. 18974 MarkNotOdrUsed(); 18975 break; 18976 } 18977 18978 // -- If e is a subscripting operation with an array operand... 18979 case Expr::ArraySubscriptExprClass: { 18980 auto *ASE = cast<ArraySubscriptExpr>(E); 18981 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18982 if (!OldBase->getType()->isArrayType()) 18983 break; 18984 ExprResult Base = Rebuild(OldBase); 18985 if (!Base.isUsable()) 18986 return Base; 18987 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18988 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18989 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18990 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18991 ASE->getRBracketLoc()); 18992 } 18993 18994 case Expr::MemberExprClass: { 18995 auto *ME = cast<MemberExpr>(E); 18996 // -- If e is a class member access expression [...] naming a non-static 18997 // data member... 18998 if (isa<FieldDecl>(ME->getMemberDecl())) { 18999 ExprResult Base = Rebuild(ME->getBase()); 19000 if (!Base.isUsable()) 19001 return Base; 19002 return MemberExpr::Create( 19003 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 19004 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 19005 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 19006 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 19007 ME->getObjectKind(), ME->isNonOdrUse()); 19008 } 19009 19010 if (ME->getMemberDecl()->isCXXInstanceMember()) 19011 break; 19012 19013 // -- If e is a class member access expression naming a static data member, 19014 // ... 19015 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 19016 break; 19017 19018 // Rebuild as a non-odr-use MemberExpr. 19019 MarkNotOdrUsed(); 19020 return MemberExpr::Create( 19021 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 19022 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 19023 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 19024 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 19025 } 19026 19027 case Expr::BinaryOperatorClass: { 19028 auto *BO = cast<BinaryOperator>(E); 19029 Expr *LHS = BO->getLHS(); 19030 Expr *RHS = BO->getRHS(); 19031 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 19032 if (BO->getOpcode() == BO_PtrMemD) { 19033 ExprResult Sub = Rebuild(LHS); 19034 if (!Sub.isUsable()) 19035 return Sub; 19036 LHS = Sub.get(); 19037 // -- If e is a comma expression, ... 19038 } else if (BO->getOpcode() == BO_Comma) { 19039 ExprResult Sub = Rebuild(RHS); 19040 if (!Sub.isUsable()) 19041 return Sub; 19042 RHS = Sub.get(); 19043 } else { 19044 break; 19045 } 19046 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 19047 LHS, RHS); 19048 } 19049 19050 // -- If e has the form (e1)... 19051 case Expr::ParenExprClass: { 19052 auto *PE = cast<ParenExpr>(E); 19053 ExprResult Sub = Rebuild(PE->getSubExpr()); 19054 if (!Sub.isUsable()) 19055 return Sub; 19056 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 19057 } 19058 19059 // -- If e is a glvalue conditional expression, ... 19060 // We don't apply this to a binary conditional operator. FIXME: Should we? 19061 case Expr::ConditionalOperatorClass: { 19062 auto *CO = cast<ConditionalOperator>(E); 19063 ExprResult LHS = Rebuild(CO->getLHS()); 19064 if (LHS.isInvalid()) 19065 return ExprError(); 19066 ExprResult RHS = Rebuild(CO->getRHS()); 19067 if (RHS.isInvalid()) 19068 return ExprError(); 19069 if (!LHS.isUsable() && !RHS.isUsable()) 19070 return ExprEmpty(); 19071 if (!LHS.isUsable()) 19072 LHS = CO->getLHS(); 19073 if (!RHS.isUsable()) 19074 RHS = CO->getRHS(); 19075 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 19076 CO->getCond(), LHS.get(), RHS.get()); 19077 } 19078 19079 // [Clang extension] 19080 // -- If e has the form __extension__ e1... 19081 case Expr::UnaryOperatorClass: { 19082 auto *UO = cast<UnaryOperator>(E); 19083 if (UO->getOpcode() != UO_Extension) 19084 break; 19085 ExprResult Sub = Rebuild(UO->getSubExpr()); 19086 if (!Sub.isUsable()) 19087 return Sub; 19088 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 19089 Sub.get()); 19090 } 19091 19092 // [Clang extension] 19093 // -- If e has the form _Generic(...), the set of potential results is the 19094 // union of the sets of potential results of the associated expressions. 19095 case Expr::GenericSelectionExprClass: { 19096 auto *GSE = cast<GenericSelectionExpr>(E); 19097 19098 SmallVector<Expr *, 4> AssocExprs; 19099 bool AnyChanged = false; 19100 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 19101 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 19102 if (AssocExpr.isInvalid()) 19103 return ExprError(); 19104 if (AssocExpr.isUsable()) { 19105 AssocExprs.push_back(AssocExpr.get()); 19106 AnyChanged = true; 19107 } else { 19108 AssocExprs.push_back(OrigAssocExpr); 19109 } 19110 } 19111 19112 return AnyChanged ? S.CreateGenericSelectionExpr( 19113 GSE->getGenericLoc(), GSE->getDefaultLoc(), 19114 GSE->getRParenLoc(), GSE->getControllingExpr(), 19115 GSE->getAssocTypeSourceInfos(), AssocExprs) 19116 : ExprEmpty(); 19117 } 19118 19119 // [Clang extension] 19120 // -- If e has the form __builtin_choose_expr(...), the set of potential 19121 // results is the union of the sets of potential results of the 19122 // second and third subexpressions. 19123 case Expr::ChooseExprClass: { 19124 auto *CE = cast<ChooseExpr>(E); 19125 19126 ExprResult LHS = Rebuild(CE->getLHS()); 19127 if (LHS.isInvalid()) 19128 return ExprError(); 19129 19130 ExprResult RHS = Rebuild(CE->getLHS()); 19131 if (RHS.isInvalid()) 19132 return ExprError(); 19133 19134 if (!LHS.get() && !RHS.get()) 19135 return ExprEmpty(); 19136 if (!LHS.isUsable()) 19137 LHS = CE->getLHS(); 19138 if (!RHS.isUsable()) 19139 RHS = CE->getRHS(); 19140 19141 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 19142 RHS.get(), CE->getRParenLoc()); 19143 } 19144 19145 // Step through non-syntactic nodes. 19146 case Expr::ConstantExprClass: { 19147 auto *CE = cast<ConstantExpr>(E); 19148 ExprResult Sub = Rebuild(CE->getSubExpr()); 19149 if (!Sub.isUsable()) 19150 return Sub; 19151 return ConstantExpr::Create(S.Context, Sub.get()); 19152 } 19153 19154 // We could mostly rely on the recursive rebuilding to rebuild implicit 19155 // casts, but not at the top level, so rebuild them here. 19156 case Expr::ImplicitCastExprClass: { 19157 auto *ICE = cast<ImplicitCastExpr>(E); 19158 // Only step through the narrow set of cast kinds we expect to encounter. 19159 // Anything else suggests we've left the region in which potential results 19160 // can be found. 19161 switch (ICE->getCastKind()) { 19162 case CK_NoOp: 19163 case CK_DerivedToBase: 19164 case CK_UncheckedDerivedToBase: { 19165 ExprResult Sub = Rebuild(ICE->getSubExpr()); 19166 if (!Sub.isUsable()) 19167 return Sub; 19168 CXXCastPath Path(ICE->path()); 19169 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 19170 ICE->getValueKind(), &Path); 19171 } 19172 19173 default: 19174 break; 19175 } 19176 break; 19177 } 19178 19179 default: 19180 break; 19181 } 19182 19183 // Can't traverse through this node. Nothing to do. 19184 return ExprEmpty(); 19185 } 19186 19187 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 19188 // Check whether the operand is or contains an object of non-trivial C union 19189 // type. 19190 if (E->getType().isVolatileQualified() && 19191 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 19192 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 19193 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 19194 Sema::NTCUC_LValueToRValueVolatile, 19195 NTCUK_Destruct|NTCUK_Copy); 19196 19197 // C++2a [basic.def.odr]p4: 19198 // [...] an expression of non-volatile-qualified non-class type to which 19199 // the lvalue-to-rvalue conversion is applied [...] 19200 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 19201 return E; 19202 19203 ExprResult Result = 19204 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 19205 if (Result.isInvalid()) 19206 return ExprError(); 19207 return Result.get() ? Result : E; 19208 } 19209 19210 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 19211 Res = CorrectDelayedTyposInExpr(Res); 19212 19213 if (!Res.isUsable()) 19214 return Res; 19215 19216 // If a constant-expression is a reference to a variable where we delay 19217 // deciding whether it is an odr-use, just assume we will apply the 19218 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 19219 // (a non-type template argument), we have special handling anyway. 19220 return CheckLValueToRValueConversionOperand(Res.get()); 19221 } 19222 19223 void Sema::CleanupVarDeclMarking() { 19224 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 19225 // call. 19226 MaybeODRUseExprSet LocalMaybeODRUseExprs; 19227 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 19228 19229 for (Expr *E : LocalMaybeODRUseExprs) { 19230 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 19231 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 19232 DRE->getLocation(), *this); 19233 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 19234 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 19235 *this); 19236 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 19237 for (VarDecl *VD : *FP) 19238 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 19239 } else { 19240 llvm_unreachable("Unexpected expression"); 19241 } 19242 } 19243 19244 assert(MaybeODRUseExprs.empty() && 19245 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 19246 } 19247 19248 static void DoMarkVarDeclReferenced( 19249 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 19250 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 19251 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 19252 isa<FunctionParmPackExpr>(E)) && 19253 "Invalid Expr argument to DoMarkVarDeclReferenced"); 19254 Var->setReferenced(); 19255 19256 if (Var->isInvalidDecl()) 19257 return; 19258 19259 auto *MSI = Var->getMemberSpecializationInfo(); 19260 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 19261 : Var->getTemplateSpecializationKind(); 19262 19263 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 19264 bool UsableInConstantExpr = 19265 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 19266 19267 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 19268 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 19269 } 19270 19271 // C++20 [expr.const]p12: 19272 // A variable [...] is needed for constant evaluation if it is [...] a 19273 // variable whose name appears as a potentially constant evaluated 19274 // expression that is either a contexpr variable or is of non-volatile 19275 // const-qualified integral type or of reference type 19276 bool NeededForConstantEvaluation = 19277 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 19278 19279 bool NeedDefinition = 19280 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 19281 19282 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 19283 "Can't instantiate a partial template specialization."); 19284 19285 // If this might be a member specialization of a static data member, check 19286 // the specialization is visible. We already did the checks for variable 19287 // template specializations when we created them. 19288 if (NeedDefinition && TSK != TSK_Undeclared && 19289 !isa<VarTemplateSpecializationDecl>(Var)) 19290 SemaRef.checkSpecializationVisibility(Loc, Var); 19291 19292 // Perform implicit instantiation of static data members, static data member 19293 // templates of class templates, and variable template specializations. Delay 19294 // instantiations of variable templates, except for those that could be used 19295 // in a constant expression. 19296 if (NeedDefinition && isTemplateInstantiation(TSK)) { 19297 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 19298 // instantiation declaration if a variable is usable in a constant 19299 // expression (among other cases). 19300 bool TryInstantiating = 19301 TSK == TSK_ImplicitInstantiation || 19302 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 19303 19304 if (TryInstantiating) { 19305 SourceLocation PointOfInstantiation = 19306 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 19307 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 19308 if (FirstInstantiation) { 19309 PointOfInstantiation = Loc; 19310 if (MSI) 19311 MSI->setPointOfInstantiation(PointOfInstantiation); 19312 // FIXME: Notify listener. 19313 else 19314 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 19315 } 19316 19317 if (UsableInConstantExpr) { 19318 // Do not defer instantiations of variables that could be used in a 19319 // constant expression. 19320 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 19321 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 19322 }); 19323 19324 // Re-set the member to trigger a recomputation of the dependence bits 19325 // for the expression. 19326 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 19327 DRE->setDecl(DRE->getDecl()); 19328 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 19329 ME->setMemberDecl(ME->getMemberDecl()); 19330 } else if (FirstInstantiation || 19331 isa<VarTemplateSpecializationDecl>(Var)) { 19332 // FIXME: For a specialization of a variable template, we don't 19333 // distinguish between "declaration and type implicitly instantiated" 19334 // and "implicit instantiation of definition requested", so we have 19335 // no direct way to avoid enqueueing the pending instantiation 19336 // multiple times. 19337 SemaRef.PendingInstantiations 19338 .push_back(std::make_pair(Var, PointOfInstantiation)); 19339 } 19340 } 19341 } 19342 19343 // C++2a [basic.def.odr]p4: 19344 // A variable x whose name appears as a potentially-evaluated expression e 19345 // is odr-used by e unless 19346 // -- x is a reference that is usable in constant expressions 19347 // -- x is a variable of non-reference type that is usable in constant 19348 // expressions and has no mutable subobjects [FIXME], and e is an 19349 // element of the set of potential results of an expression of 19350 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 19351 // conversion is applied 19352 // -- x is a variable of non-reference type, and e is an element of the set 19353 // of potential results of a discarded-value expression to which the 19354 // lvalue-to-rvalue conversion is not applied [FIXME] 19355 // 19356 // We check the first part of the second bullet here, and 19357 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 19358 // FIXME: To get the third bullet right, we need to delay this even for 19359 // variables that are not usable in constant expressions. 19360 19361 // If we already know this isn't an odr-use, there's nothing more to do. 19362 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 19363 if (DRE->isNonOdrUse()) 19364 return; 19365 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 19366 if (ME->isNonOdrUse()) 19367 return; 19368 19369 switch (OdrUse) { 19370 case OdrUseContext::None: 19371 assert((!E || isa<FunctionParmPackExpr>(E)) && 19372 "missing non-odr-use marking for unevaluated decl ref"); 19373 break; 19374 19375 case OdrUseContext::FormallyOdrUsed: 19376 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 19377 // behavior. 19378 break; 19379 19380 case OdrUseContext::Used: 19381 // If we might later find that this expression isn't actually an odr-use, 19382 // delay the marking. 19383 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 19384 SemaRef.MaybeODRUseExprs.insert(E); 19385 else 19386 MarkVarDeclODRUsed(Var, Loc, SemaRef); 19387 break; 19388 19389 case OdrUseContext::Dependent: 19390 // If this is a dependent context, we don't need to mark variables as 19391 // odr-used, but we may still need to track them for lambda capture. 19392 // FIXME: Do we also need to do this inside dependent typeid expressions 19393 // (which are modeled as unevaluated at this point)? 19394 const bool RefersToEnclosingScope = 19395 (SemaRef.CurContext != Var->getDeclContext() && 19396 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 19397 if (RefersToEnclosingScope) { 19398 LambdaScopeInfo *const LSI = 19399 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 19400 if (LSI && (!LSI->CallOperator || 19401 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 19402 // If a variable could potentially be odr-used, defer marking it so 19403 // until we finish analyzing the full expression for any 19404 // lvalue-to-rvalue 19405 // or discarded value conversions that would obviate odr-use. 19406 // Add it to the list of potential captures that will be analyzed 19407 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 19408 // unless the variable is a reference that was initialized by a constant 19409 // expression (this will never need to be captured or odr-used). 19410 // 19411 // FIXME: We can simplify this a lot after implementing P0588R1. 19412 assert(E && "Capture variable should be used in an expression."); 19413 if (!Var->getType()->isReferenceType() || 19414 !Var->isUsableInConstantExpressions(SemaRef.Context)) 19415 LSI->addPotentialCapture(E->IgnoreParens()); 19416 } 19417 } 19418 break; 19419 } 19420 } 19421 19422 /// Mark a variable referenced, and check whether it is odr-used 19423 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 19424 /// used directly for normal expressions referring to VarDecl. 19425 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 19426 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 19427 } 19428 19429 static void 19430 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 19431 bool MightBeOdrUse, 19432 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 19433 if (SemaRef.isInOpenMPDeclareTargetContext()) 19434 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 19435 19436 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 19437 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 19438 return; 19439 } 19440 19441 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 19442 19443 // If this is a call to a method via a cast, also mark the method in the 19444 // derived class used in case codegen can devirtualize the call. 19445 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 19446 if (!ME) 19447 return; 19448 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 19449 if (!MD) 19450 return; 19451 // Only attempt to devirtualize if this is truly a virtual call. 19452 bool IsVirtualCall = MD->isVirtual() && 19453 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 19454 if (!IsVirtualCall) 19455 return; 19456 19457 // If it's possible to devirtualize the call, mark the called function 19458 // referenced. 19459 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 19460 ME->getBase(), SemaRef.getLangOpts().AppleKext); 19461 if (DM) 19462 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 19463 } 19464 19465 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 19466 /// 19467 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 19468 /// handled with care if the DeclRefExpr is not newly-created. 19469 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 19470 // TODO: update this with DR# once a defect report is filed. 19471 // C++11 defect. The address of a pure member should not be an ODR use, even 19472 // if it's a qualified reference. 19473 bool OdrUse = true; 19474 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 19475 if (Method->isVirtual() && 19476 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 19477 OdrUse = false; 19478 19479 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 19480 if (!isUnevaluatedContext() && !isConstantEvaluated() && 19481 FD->isConsteval() && !RebuildingImmediateInvocation) 19482 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 19483 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 19484 RefsMinusAssignments); 19485 } 19486 19487 /// Perform reference-marking and odr-use handling for a MemberExpr. 19488 void Sema::MarkMemberReferenced(MemberExpr *E) { 19489 // C++11 [basic.def.odr]p2: 19490 // A non-overloaded function whose name appears as a potentially-evaluated 19491 // expression or a member of a set of candidate functions, if selected by 19492 // overload resolution when referred to from a potentially-evaluated 19493 // expression, is odr-used, unless it is a pure virtual function and its 19494 // name is not explicitly qualified. 19495 bool MightBeOdrUse = true; 19496 if (E->performsVirtualDispatch(getLangOpts())) { 19497 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 19498 if (Method->isPure()) 19499 MightBeOdrUse = false; 19500 } 19501 SourceLocation Loc = 19502 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 19503 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 19504 RefsMinusAssignments); 19505 } 19506 19507 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 19508 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 19509 for (VarDecl *VD : *E) 19510 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 19511 RefsMinusAssignments); 19512 } 19513 19514 /// Perform marking for a reference to an arbitrary declaration. It 19515 /// marks the declaration referenced, and performs odr-use checking for 19516 /// functions and variables. This method should not be used when building a 19517 /// normal expression which refers to a variable. 19518 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 19519 bool MightBeOdrUse) { 19520 if (MightBeOdrUse) { 19521 if (auto *VD = dyn_cast<VarDecl>(D)) { 19522 MarkVariableReferenced(Loc, VD); 19523 return; 19524 } 19525 } 19526 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 19527 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 19528 return; 19529 } 19530 D->setReferenced(); 19531 } 19532 19533 namespace { 19534 // Mark all of the declarations used by a type as referenced. 19535 // FIXME: Not fully implemented yet! We need to have a better understanding 19536 // of when we're entering a context we should not recurse into. 19537 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 19538 // TreeTransforms rebuilding the type in a new context. Rather than 19539 // duplicating the TreeTransform logic, we should consider reusing it here. 19540 // Currently that causes problems when rebuilding LambdaExprs. 19541 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 19542 Sema &S; 19543 SourceLocation Loc; 19544 19545 public: 19546 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 19547 19548 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 19549 19550 bool TraverseTemplateArgument(const TemplateArgument &Arg); 19551 }; 19552 } 19553 19554 bool MarkReferencedDecls::TraverseTemplateArgument( 19555 const TemplateArgument &Arg) { 19556 { 19557 // A non-type template argument is a constant-evaluated context. 19558 EnterExpressionEvaluationContext Evaluated( 19559 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 19560 if (Arg.getKind() == TemplateArgument::Declaration) { 19561 if (Decl *D = Arg.getAsDecl()) 19562 S.MarkAnyDeclReferenced(Loc, D, true); 19563 } else if (Arg.getKind() == TemplateArgument::Expression) { 19564 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 19565 } 19566 } 19567 19568 return Inherited::TraverseTemplateArgument(Arg); 19569 } 19570 19571 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 19572 MarkReferencedDecls Marker(*this, Loc); 19573 Marker.TraverseType(T); 19574 } 19575 19576 namespace { 19577 /// Helper class that marks all of the declarations referenced by 19578 /// potentially-evaluated subexpressions as "referenced". 19579 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 19580 public: 19581 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 19582 bool SkipLocalVariables; 19583 ArrayRef<const Expr *> StopAt; 19584 19585 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables, 19586 ArrayRef<const Expr *> StopAt) 19587 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {} 19588 19589 void visitUsedDecl(SourceLocation Loc, Decl *D) { 19590 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 19591 } 19592 19593 void Visit(Expr *E) { 19594 if (std::find(StopAt.begin(), StopAt.end(), E) != StopAt.end()) 19595 return; 19596 Inherited::Visit(E); 19597 } 19598 19599 void VisitDeclRefExpr(DeclRefExpr *E) { 19600 // If we were asked not to visit local variables, don't. 19601 if (SkipLocalVariables) { 19602 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 19603 if (VD->hasLocalStorage()) 19604 return; 19605 } 19606 19607 // FIXME: This can trigger the instantiation of the initializer of a 19608 // variable, which can cause the expression to become value-dependent 19609 // or error-dependent. Do we need to propagate the new dependence bits? 19610 S.MarkDeclRefReferenced(E); 19611 } 19612 19613 void VisitMemberExpr(MemberExpr *E) { 19614 S.MarkMemberReferenced(E); 19615 Visit(E->getBase()); 19616 } 19617 }; 19618 } // namespace 19619 19620 /// Mark any declarations that appear within this expression or any 19621 /// potentially-evaluated subexpressions as "referenced". 19622 /// 19623 /// \param SkipLocalVariables If true, don't mark local variables as 19624 /// 'referenced'. 19625 /// \param StopAt Subexpressions that we shouldn't recurse into. 19626 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 19627 bool SkipLocalVariables, 19628 ArrayRef<const Expr*> StopAt) { 19629 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E); 19630 } 19631 19632 /// Emit a diagnostic when statements are reachable. 19633 /// FIXME: check for reachability even in expressions for which we don't build a 19634 /// CFG (eg, in the initializer of a global or in a constant expression). 19635 /// For example, 19636 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; } 19637 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, 19638 const PartialDiagnostic &PD) { 19639 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 19640 if (!FunctionScopes.empty()) 19641 FunctionScopes.back()->PossiblyUnreachableDiags.push_back( 19642 sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 19643 return true; 19644 } 19645 19646 // The initializer of a constexpr variable or of the first declaration of a 19647 // static data member is not syntactically a constant evaluated constant, 19648 // but nonetheless is always required to be a constant expression, so we 19649 // can skip diagnosing. 19650 // FIXME: Using the mangling context here is a hack. 19651 if (auto *VD = dyn_cast_or_null<VarDecl>( 19652 ExprEvalContexts.back().ManglingContextDecl)) { 19653 if (VD->isConstexpr() || 19654 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 19655 return false; 19656 // FIXME: For any other kind of variable, we should build a CFG for its 19657 // initializer and check whether the context in question is reachable. 19658 } 19659 19660 Diag(Loc, PD); 19661 return true; 19662 } 19663 19664 /// Emit a diagnostic that describes an effect on the run-time behavior 19665 /// of the program being compiled. 19666 /// 19667 /// This routine emits the given diagnostic when the code currently being 19668 /// type-checked is "potentially evaluated", meaning that there is a 19669 /// possibility that the code will actually be executable. Code in sizeof() 19670 /// expressions, code used only during overload resolution, etc., are not 19671 /// potentially evaluated. This routine will suppress such diagnostics or, 19672 /// in the absolutely nutty case of potentially potentially evaluated 19673 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 19674 /// later. 19675 /// 19676 /// This routine should be used for all diagnostics that describe the run-time 19677 /// behavior of a program, such as passing a non-POD value through an ellipsis. 19678 /// Failure to do so will likely result in spurious diagnostics or failures 19679 /// during overload resolution or within sizeof/alignof/typeof/typeid. 19680 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 19681 const PartialDiagnostic &PD) { 19682 19683 if (ExprEvalContexts.back().isDiscardedStatementContext()) 19684 return false; 19685 19686 switch (ExprEvalContexts.back().Context) { 19687 case ExpressionEvaluationContext::Unevaluated: 19688 case ExpressionEvaluationContext::UnevaluatedList: 19689 case ExpressionEvaluationContext::UnevaluatedAbstract: 19690 case ExpressionEvaluationContext::DiscardedStatement: 19691 // The argument will never be evaluated, so don't complain. 19692 break; 19693 19694 case ExpressionEvaluationContext::ConstantEvaluated: 19695 case ExpressionEvaluationContext::ImmediateFunctionContext: 19696 // Relevant diagnostics should be produced by constant evaluation. 19697 break; 19698 19699 case ExpressionEvaluationContext::PotentiallyEvaluated: 19700 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 19701 return DiagIfReachable(Loc, Stmts, PD); 19702 } 19703 19704 return false; 19705 } 19706 19707 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 19708 const PartialDiagnostic &PD) { 19709 return DiagRuntimeBehavior( 19710 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 19711 } 19712 19713 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 19714 CallExpr *CE, FunctionDecl *FD) { 19715 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 19716 return false; 19717 19718 // If we're inside a decltype's expression, don't check for a valid return 19719 // type or construct temporaries until we know whether this is the last call. 19720 if (ExprEvalContexts.back().ExprContext == 19721 ExpressionEvaluationContextRecord::EK_Decltype) { 19722 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 19723 return false; 19724 } 19725 19726 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 19727 FunctionDecl *FD; 19728 CallExpr *CE; 19729 19730 public: 19731 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 19732 : FD(FD), CE(CE) { } 19733 19734 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 19735 if (!FD) { 19736 S.Diag(Loc, diag::err_call_incomplete_return) 19737 << T << CE->getSourceRange(); 19738 return; 19739 } 19740 19741 S.Diag(Loc, diag::err_call_function_incomplete_return) 19742 << CE->getSourceRange() << FD << T; 19743 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 19744 << FD->getDeclName(); 19745 } 19746 } Diagnoser(FD, CE); 19747 19748 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 19749 return true; 19750 19751 return false; 19752 } 19753 19754 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 19755 // will prevent this condition from triggering, which is what we want. 19756 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 19757 SourceLocation Loc; 19758 19759 unsigned diagnostic = diag::warn_condition_is_assignment; 19760 bool IsOrAssign = false; 19761 19762 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 19763 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 19764 return; 19765 19766 IsOrAssign = Op->getOpcode() == BO_OrAssign; 19767 19768 // Greylist some idioms by putting them into a warning subcategory. 19769 if (ObjCMessageExpr *ME 19770 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 19771 Selector Sel = ME->getSelector(); 19772 19773 // self = [<foo> init...] 19774 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 19775 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19776 19777 // <foo> = [<bar> nextObject] 19778 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 19779 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19780 } 19781 19782 Loc = Op->getOperatorLoc(); 19783 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 19784 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 19785 return; 19786 19787 IsOrAssign = Op->getOperator() == OO_PipeEqual; 19788 Loc = Op->getOperatorLoc(); 19789 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 19790 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 19791 else { 19792 // Not an assignment. 19793 return; 19794 } 19795 19796 Diag(Loc, diagnostic) << E->getSourceRange(); 19797 19798 SourceLocation Open = E->getBeginLoc(); 19799 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 19800 Diag(Loc, diag::note_condition_assign_silence) 19801 << FixItHint::CreateInsertion(Open, "(") 19802 << FixItHint::CreateInsertion(Close, ")"); 19803 19804 if (IsOrAssign) 19805 Diag(Loc, diag::note_condition_or_assign_to_comparison) 19806 << FixItHint::CreateReplacement(Loc, "!="); 19807 else 19808 Diag(Loc, diag::note_condition_assign_to_comparison) 19809 << FixItHint::CreateReplacement(Loc, "=="); 19810 } 19811 19812 /// Redundant parentheses over an equality comparison can indicate 19813 /// that the user intended an assignment used as condition. 19814 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 19815 // Don't warn if the parens came from a macro. 19816 SourceLocation parenLoc = ParenE->getBeginLoc(); 19817 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 19818 return; 19819 // Don't warn for dependent expressions. 19820 if (ParenE->isTypeDependent()) 19821 return; 19822 19823 Expr *E = ParenE->IgnoreParens(); 19824 19825 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 19826 if (opE->getOpcode() == BO_EQ && 19827 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 19828 == Expr::MLV_Valid) { 19829 SourceLocation Loc = opE->getOperatorLoc(); 19830 19831 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 19832 SourceRange ParenERange = ParenE->getSourceRange(); 19833 Diag(Loc, diag::note_equality_comparison_silence) 19834 << FixItHint::CreateRemoval(ParenERange.getBegin()) 19835 << FixItHint::CreateRemoval(ParenERange.getEnd()); 19836 Diag(Loc, diag::note_equality_comparison_to_assign) 19837 << FixItHint::CreateReplacement(Loc, "="); 19838 } 19839 } 19840 19841 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 19842 bool IsConstexpr) { 19843 DiagnoseAssignmentAsCondition(E); 19844 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 19845 DiagnoseEqualityWithExtraParens(parenE); 19846 19847 ExprResult result = CheckPlaceholderExpr(E); 19848 if (result.isInvalid()) return ExprError(); 19849 E = result.get(); 19850 19851 if (!E->isTypeDependent()) { 19852 if (getLangOpts().CPlusPlus) 19853 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 19854 19855 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 19856 if (ERes.isInvalid()) 19857 return ExprError(); 19858 E = ERes.get(); 19859 19860 QualType T = E->getType(); 19861 if (!T->isScalarType()) { // C99 6.8.4.1p1 19862 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 19863 << T << E->getSourceRange(); 19864 return ExprError(); 19865 } 19866 CheckBoolLikeConversion(E, Loc); 19867 } 19868 19869 return E; 19870 } 19871 19872 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 19873 Expr *SubExpr, ConditionKind CK, 19874 bool MissingOK) { 19875 // MissingOK indicates whether having no condition expression is valid 19876 // (for loop) or invalid (e.g. while loop). 19877 if (!SubExpr) 19878 return MissingOK ? ConditionResult() : ConditionError(); 19879 19880 ExprResult Cond; 19881 switch (CK) { 19882 case ConditionKind::Boolean: 19883 Cond = CheckBooleanCondition(Loc, SubExpr); 19884 break; 19885 19886 case ConditionKind::ConstexprIf: 19887 Cond = CheckBooleanCondition(Loc, SubExpr, true); 19888 break; 19889 19890 case ConditionKind::Switch: 19891 Cond = CheckSwitchCondition(Loc, SubExpr); 19892 break; 19893 } 19894 if (Cond.isInvalid()) { 19895 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 19896 {SubExpr}, PreferredConditionType(CK)); 19897 if (!Cond.get()) 19898 return ConditionError(); 19899 } 19900 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 19901 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 19902 if (!FullExpr.get()) 19903 return ConditionError(); 19904 19905 return ConditionResult(*this, nullptr, FullExpr, 19906 CK == ConditionKind::ConstexprIf); 19907 } 19908 19909 namespace { 19910 /// A visitor for rebuilding a call to an __unknown_any expression 19911 /// to have an appropriate type. 19912 struct RebuildUnknownAnyFunction 19913 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 19914 19915 Sema &S; 19916 19917 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 19918 19919 ExprResult VisitStmt(Stmt *S) { 19920 llvm_unreachable("unexpected statement!"); 19921 } 19922 19923 ExprResult VisitExpr(Expr *E) { 19924 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 19925 << E->getSourceRange(); 19926 return ExprError(); 19927 } 19928 19929 /// Rebuild an expression which simply semantically wraps another 19930 /// expression which it shares the type and value kind of. 19931 template <class T> ExprResult rebuildSugarExpr(T *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(SubExpr->getType()); 19938 E->setValueKind(SubExpr->getValueKind()); 19939 assert(E->getObjectKind() == OK_Ordinary); 19940 return E; 19941 } 19942 19943 ExprResult VisitParenExpr(ParenExpr *E) { 19944 return rebuildSugarExpr(E); 19945 } 19946 19947 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19948 return rebuildSugarExpr(E); 19949 } 19950 19951 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19952 ExprResult SubResult = Visit(E->getSubExpr()); 19953 if (SubResult.isInvalid()) return ExprError(); 19954 19955 Expr *SubExpr = SubResult.get(); 19956 E->setSubExpr(SubExpr); 19957 E->setType(S.Context.getPointerType(SubExpr->getType())); 19958 assert(E->isPRValue()); 19959 assert(E->getObjectKind() == OK_Ordinary); 19960 return E; 19961 } 19962 19963 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19964 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19965 19966 E->setType(VD->getType()); 19967 19968 assert(E->isPRValue()); 19969 if (S.getLangOpts().CPlusPlus && 19970 !(isa<CXXMethodDecl>(VD) && 19971 cast<CXXMethodDecl>(VD)->isInstance())) 19972 E->setValueKind(VK_LValue); 19973 19974 return E; 19975 } 19976 19977 ExprResult VisitMemberExpr(MemberExpr *E) { 19978 return resolveDecl(E, E->getMemberDecl()); 19979 } 19980 19981 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19982 return resolveDecl(E, E->getDecl()); 19983 } 19984 }; 19985 } 19986 19987 /// Given a function expression of unknown-any type, try to rebuild it 19988 /// to have a function type. 19989 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19990 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19991 if (Result.isInvalid()) return ExprError(); 19992 return S.DefaultFunctionArrayConversion(Result.get()); 19993 } 19994 19995 namespace { 19996 /// A visitor for rebuilding an expression of type __unknown_anytype 19997 /// into one which resolves the type directly on the referring 19998 /// expression. Strict preservation of the original source 19999 /// structure is not a goal. 20000 struct RebuildUnknownAnyExpr 20001 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 20002 20003 Sema &S; 20004 20005 /// The current destination type. 20006 QualType DestType; 20007 20008 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 20009 : S(S), DestType(CastType) {} 20010 20011 ExprResult VisitStmt(Stmt *S) { 20012 llvm_unreachable("unexpected statement!"); 20013 } 20014 20015 ExprResult VisitExpr(Expr *E) { 20016 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 20017 << E->getSourceRange(); 20018 return ExprError(); 20019 } 20020 20021 ExprResult VisitCallExpr(CallExpr *E); 20022 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 20023 20024 /// Rebuild an expression which simply semantically wraps another 20025 /// expression which it shares the type and value kind of. 20026 template <class T> ExprResult rebuildSugarExpr(T *E) { 20027 ExprResult SubResult = Visit(E->getSubExpr()); 20028 if (SubResult.isInvalid()) return ExprError(); 20029 Expr *SubExpr = SubResult.get(); 20030 E->setSubExpr(SubExpr); 20031 E->setType(SubExpr->getType()); 20032 E->setValueKind(SubExpr->getValueKind()); 20033 assert(E->getObjectKind() == OK_Ordinary); 20034 return E; 20035 } 20036 20037 ExprResult VisitParenExpr(ParenExpr *E) { 20038 return rebuildSugarExpr(E); 20039 } 20040 20041 ExprResult VisitUnaryExtension(UnaryOperator *E) { 20042 return rebuildSugarExpr(E); 20043 } 20044 20045 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 20046 const PointerType *Ptr = DestType->getAs<PointerType>(); 20047 if (!Ptr) { 20048 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 20049 << E->getSourceRange(); 20050 return ExprError(); 20051 } 20052 20053 if (isa<CallExpr>(E->getSubExpr())) { 20054 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 20055 << E->getSourceRange(); 20056 return ExprError(); 20057 } 20058 20059 assert(E->isPRValue()); 20060 assert(E->getObjectKind() == OK_Ordinary); 20061 E->setType(DestType); 20062 20063 // Build the sub-expression as if it were an object of the pointee type. 20064 DestType = Ptr->getPointeeType(); 20065 ExprResult SubResult = Visit(E->getSubExpr()); 20066 if (SubResult.isInvalid()) return ExprError(); 20067 E->setSubExpr(SubResult.get()); 20068 return E; 20069 } 20070 20071 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 20072 20073 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 20074 20075 ExprResult VisitMemberExpr(MemberExpr *E) { 20076 return resolveDecl(E, E->getMemberDecl()); 20077 } 20078 20079 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 20080 return resolveDecl(E, E->getDecl()); 20081 } 20082 }; 20083 } 20084 20085 /// Rebuilds a call expression which yielded __unknown_anytype. 20086 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 20087 Expr *CalleeExpr = E->getCallee(); 20088 20089 enum FnKind { 20090 FK_MemberFunction, 20091 FK_FunctionPointer, 20092 FK_BlockPointer 20093 }; 20094 20095 FnKind Kind; 20096 QualType CalleeType = CalleeExpr->getType(); 20097 if (CalleeType == S.Context.BoundMemberTy) { 20098 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 20099 Kind = FK_MemberFunction; 20100 CalleeType = Expr::findBoundMemberType(CalleeExpr); 20101 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 20102 CalleeType = Ptr->getPointeeType(); 20103 Kind = FK_FunctionPointer; 20104 } else { 20105 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 20106 Kind = FK_BlockPointer; 20107 } 20108 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 20109 20110 // Verify that this is a legal result type of a function. 20111 if (DestType->isArrayType() || DestType->isFunctionType()) { 20112 unsigned diagID = diag::err_func_returning_array_function; 20113 if (Kind == FK_BlockPointer) 20114 diagID = diag::err_block_returning_array_function; 20115 20116 S.Diag(E->getExprLoc(), diagID) 20117 << DestType->isFunctionType() << DestType; 20118 return ExprError(); 20119 } 20120 20121 // Otherwise, go ahead and set DestType as the call's result. 20122 E->setType(DestType.getNonLValueExprType(S.Context)); 20123 E->setValueKind(Expr::getValueKindForType(DestType)); 20124 assert(E->getObjectKind() == OK_Ordinary); 20125 20126 // Rebuild the function type, replacing the result type with DestType. 20127 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 20128 if (Proto) { 20129 // __unknown_anytype(...) is a special case used by the debugger when 20130 // it has no idea what a function's signature is. 20131 // 20132 // We want to build this call essentially under the K&R 20133 // unprototyped rules, but making a FunctionNoProtoType in C++ 20134 // would foul up all sorts of assumptions. However, we cannot 20135 // simply pass all arguments as variadic arguments, nor can we 20136 // portably just call the function under a non-variadic type; see 20137 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 20138 // However, it turns out that in practice it is generally safe to 20139 // call a function declared as "A foo(B,C,D);" under the prototype 20140 // "A foo(B,C,D,...);". The only known exception is with the 20141 // Windows ABI, where any variadic function is implicitly cdecl 20142 // regardless of its normal CC. Therefore we change the parameter 20143 // types to match the types of the arguments. 20144 // 20145 // This is a hack, but it is far superior to moving the 20146 // corresponding target-specific code from IR-gen to Sema/AST. 20147 20148 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 20149 SmallVector<QualType, 8> ArgTypes; 20150 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 20151 ArgTypes.reserve(E->getNumArgs()); 20152 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 20153 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); 20154 } 20155 ParamTypes = ArgTypes; 20156 } 20157 DestType = S.Context.getFunctionType(DestType, ParamTypes, 20158 Proto->getExtProtoInfo()); 20159 } else { 20160 DestType = S.Context.getFunctionNoProtoType(DestType, 20161 FnType->getExtInfo()); 20162 } 20163 20164 // Rebuild the appropriate pointer-to-function type. 20165 switch (Kind) { 20166 case FK_MemberFunction: 20167 // Nothing to do. 20168 break; 20169 20170 case FK_FunctionPointer: 20171 DestType = S.Context.getPointerType(DestType); 20172 break; 20173 20174 case FK_BlockPointer: 20175 DestType = S.Context.getBlockPointerType(DestType); 20176 break; 20177 } 20178 20179 // Finally, we can recurse. 20180 ExprResult CalleeResult = Visit(CalleeExpr); 20181 if (!CalleeResult.isUsable()) return ExprError(); 20182 E->setCallee(CalleeResult.get()); 20183 20184 // Bind a temporary if necessary. 20185 return S.MaybeBindToTemporary(E); 20186 } 20187 20188 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 20189 // Verify that this is a legal result type of a call. 20190 if (DestType->isArrayType() || DestType->isFunctionType()) { 20191 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 20192 << DestType->isFunctionType() << DestType; 20193 return ExprError(); 20194 } 20195 20196 // Rewrite the method result type if available. 20197 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 20198 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 20199 Method->setReturnType(DestType); 20200 } 20201 20202 // Change the type of the message. 20203 E->setType(DestType.getNonReferenceType()); 20204 E->setValueKind(Expr::getValueKindForType(DestType)); 20205 20206 return S.MaybeBindToTemporary(E); 20207 } 20208 20209 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 20210 // The only case we should ever see here is a function-to-pointer decay. 20211 if (E->getCastKind() == CK_FunctionToPointerDecay) { 20212 assert(E->isPRValue()); 20213 assert(E->getObjectKind() == OK_Ordinary); 20214 20215 E->setType(DestType); 20216 20217 // Rebuild the sub-expression as the pointee (function) type. 20218 DestType = DestType->castAs<PointerType>()->getPointeeType(); 20219 20220 ExprResult Result = Visit(E->getSubExpr()); 20221 if (!Result.isUsable()) return ExprError(); 20222 20223 E->setSubExpr(Result.get()); 20224 return E; 20225 } else if (E->getCastKind() == CK_LValueToRValue) { 20226 assert(E->isPRValue()); 20227 assert(E->getObjectKind() == OK_Ordinary); 20228 20229 assert(isa<BlockPointerType>(E->getType())); 20230 20231 E->setType(DestType); 20232 20233 // The sub-expression has to be a lvalue reference, so rebuild it as such. 20234 DestType = S.Context.getLValueReferenceType(DestType); 20235 20236 ExprResult Result = Visit(E->getSubExpr()); 20237 if (!Result.isUsable()) return ExprError(); 20238 20239 E->setSubExpr(Result.get()); 20240 return E; 20241 } else { 20242 llvm_unreachable("Unhandled cast type!"); 20243 } 20244 } 20245 20246 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 20247 ExprValueKind ValueKind = VK_LValue; 20248 QualType Type = DestType; 20249 20250 // We know how to make this work for certain kinds of decls: 20251 20252 // - functions 20253 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 20254 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 20255 DestType = Ptr->getPointeeType(); 20256 ExprResult Result = resolveDecl(E, VD); 20257 if (Result.isInvalid()) return ExprError(); 20258 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 20259 VK_PRValue); 20260 } 20261 20262 if (!Type->isFunctionType()) { 20263 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 20264 << VD << E->getSourceRange(); 20265 return ExprError(); 20266 } 20267 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 20268 // We must match the FunctionDecl's type to the hack introduced in 20269 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 20270 // type. See the lengthy commentary in that routine. 20271 QualType FDT = FD->getType(); 20272 const FunctionType *FnType = FDT->castAs<FunctionType>(); 20273 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 20274 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 20275 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 20276 SourceLocation Loc = FD->getLocation(); 20277 FunctionDecl *NewFD = FunctionDecl::Create( 20278 S.Context, FD->getDeclContext(), Loc, Loc, 20279 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 20280 SC_None, S.getCurFPFeatures().isFPConstrained(), 20281 false /*isInlineSpecified*/, FD->hasPrototype(), 20282 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 20283 20284 if (FD->getQualifier()) 20285 NewFD->setQualifierInfo(FD->getQualifierLoc()); 20286 20287 SmallVector<ParmVarDecl*, 16> Params; 20288 for (const auto &AI : FT->param_types()) { 20289 ParmVarDecl *Param = 20290 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 20291 Param->setScopeInfo(0, Params.size()); 20292 Params.push_back(Param); 20293 } 20294 NewFD->setParams(Params); 20295 DRE->setDecl(NewFD); 20296 VD = DRE->getDecl(); 20297 } 20298 } 20299 20300 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 20301 if (MD->isInstance()) { 20302 ValueKind = VK_PRValue; 20303 Type = S.Context.BoundMemberTy; 20304 } 20305 20306 // Function references aren't l-values in C. 20307 if (!S.getLangOpts().CPlusPlus) 20308 ValueKind = VK_PRValue; 20309 20310 // - variables 20311 } else if (isa<VarDecl>(VD)) { 20312 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 20313 Type = RefTy->getPointeeType(); 20314 } else if (Type->isFunctionType()) { 20315 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 20316 << VD << E->getSourceRange(); 20317 return ExprError(); 20318 } 20319 20320 // - nothing else 20321 } else { 20322 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 20323 << VD << E->getSourceRange(); 20324 return ExprError(); 20325 } 20326 20327 // Modifying the declaration like this is friendly to IR-gen but 20328 // also really dangerous. 20329 VD->setType(DestType); 20330 E->setType(Type); 20331 E->setValueKind(ValueKind); 20332 return E; 20333 } 20334 20335 /// Check a cast of an unknown-any type. We intentionally only 20336 /// trigger this for C-style casts. 20337 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 20338 Expr *CastExpr, CastKind &CastKind, 20339 ExprValueKind &VK, CXXCastPath &Path) { 20340 // The type we're casting to must be either void or complete. 20341 if (!CastType->isVoidType() && 20342 RequireCompleteType(TypeRange.getBegin(), CastType, 20343 diag::err_typecheck_cast_to_incomplete)) 20344 return ExprError(); 20345 20346 // Rewrite the casted expression from scratch. 20347 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 20348 if (!result.isUsable()) return ExprError(); 20349 20350 CastExpr = result.get(); 20351 VK = CastExpr->getValueKind(); 20352 CastKind = CK_NoOp; 20353 20354 return CastExpr; 20355 } 20356 20357 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 20358 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 20359 } 20360 20361 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 20362 Expr *arg, QualType ¶mType) { 20363 // If the syntactic form of the argument is not an explicit cast of 20364 // any sort, just do default argument promotion. 20365 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 20366 if (!castArg) { 20367 ExprResult result = DefaultArgumentPromotion(arg); 20368 if (result.isInvalid()) return ExprError(); 20369 paramType = result.get()->getType(); 20370 return result; 20371 } 20372 20373 // Otherwise, use the type that was written in the explicit cast. 20374 assert(!arg->hasPlaceholderType()); 20375 paramType = castArg->getTypeAsWritten(); 20376 20377 // Copy-initialize a parameter of that type. 20378 InitializedEntity entity = 20379 InitializedEntity::InitializeParameter(Context, paramType, 20380 /*consumed*/ false); 20381 return PerformCopyInitialization(entity, callLoc, arg); 20382 } 20383 20384 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 20385 Expr *orig = E; 20386 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 20387 while (true) { 20388 E = E->IgnoreParenImpCasts(); 20389 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 20390 E = call->getCallee(); 20391 diagID = diag::err_uncasted_call_of_unknown_any; 20392 } else { 20393 break; 20394 } 20395 } 20396 20397 SourceLocation loc; 20398 NamedDecl *d; 20399 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 20400 loc = ref->getLocation(); 20401 d = ref->getDecl(); 20402 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 20403 loc = mem->getMemberLoc(); 20404 d = mem->getMemberDecl(); 20405 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 20406 diagID = diag::err_uncasted_call_of_unknown_any; 20407 loc = msg->getSelectorStartLoc(); 20408 d = msg->getMethodDecl(); 20409 if (!d) { 20410 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 20411 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 20412 << orig->getSourceRange(); 20413 return ExprError(); 20414 } 20415 } else { 20416 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 20417 << E->getSourceRange(); 20418 return ExprError(); 20419 } 20420 20421 S.Diag(loc, diagID) << d << orig->getSourceRange(); 20422 20423 // Never recoverable. 20424 return ExprError(); 20425 } 20426 20427 /// Check for operands with placeholder types and complain if found. 20428 /// Returns ExprError() if there was an error and no recovery was possible. 20429 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 20430 if (!Context.isDependenceAllowed()) { 20431 // C cannot handle TypoExpr nodes on either side of a binop because it 20432 // doesn't handle dependent types properly, so make sure any TypoExprs have 20433 // been dealt with before checking the operands. 20434 ExprResult Result = CorrectDelayedTyposInExpr(E); 20435 if (!Result.isUsable()) return ExprError(); 20436 E = Result.get(); 20437 } 20438 20439 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 20440 if (!placeholderType) return E; 20441 20442 switch (placeholderType->getKind()) { 20443 20444 // Overloaded expressions. 20445 case BuiltinType::Overload: { 20446 // Try to resolve a single function template specialization. 20447 // This is obligatory. 20448 ExprResult Result = E; 20449 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 20450 return Result; 20451 20452 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 20453 // leaves Result unchanged on failure. 20454 Result = E; 20455 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 20456 return Result; 20457 20458 // If that failed, try to recover with a call. 20459 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 20460 /*complain*/ true); 20461 return Result; 20462 } 20463 20464 // Bound member functions. 20465 case BuiltinType::BoundMember: { 20466 ExprResult result = E; 20467 const Expr *BME = E->IgnoreParens(); 20468 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 20469 // Try to give a nicer diagnostic if it is a bound member that we recognize. 20470 if (isa<CXXPseudoDestructorExpr>(BME)) { 20471 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 20472 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 20473 if (ME->getMemberNameInfo().getName().getNameKind() == 20474 DeclarationName::CXXDestructorName) 20475 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 20476 } 20477 tryToRecoverWithCall(result, PD, 20478 /*complain*/ true); 20479 return result; 20480 } 20481 20482 // ARC unbridged casts. 20483 case BuiltinType::ARCUnbridgedCast: { 20484 Expr *realCast = stripARCUnbridgedCast(E); 20485 diagnoseARCUnbridgedCast(realCast); 20486 return realCast; 20487 } 20488 20489 // Expressions of unknown type. 20490 case BuiltinType::UnknownAny: 20491 return diagnoseUnknownAnyExpr(*this, E); 20492 20493 // Pseudo-objects. 20494 case BuiltinType::PseudoObject: 20495 return checkPseudoObjectRValue(E); 20496 20497 case BuiltinType::BuiltinFn: { 20498 // Accept __noop without parens by implicitly converting it to a call expr. 20499 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 20500 if (DRE) { 20501 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 20502 unsigned BuiltinID = FD->getBuiltinID(); 20503 if (BuiltinID == Builtin::BI__noop) { 20504 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 20505 CK_BuiltinFnToFnPtr) 20506 .get(); 20507 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 20508 VK_PRValue, SourceLocation(), 20509 FPOptionsOverride()); 20510 } 20511 20512 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) { 20513 // Any use of these other than a direct call is ill-formed as of C++20, 20514 // because they are not addressable functions. In earlier language 20515 // modes, warn and force an instantiation of the real body. 20516 Diag(E->getBeginLoc(), 20517 getLangOpts().CPlusPlus20 20518 ? diag::err_use_of_unaddressable_function 20519 : diag::warn_cxx20_compat_use_of_unaddressable_function); 20520 if (FD->isImplicitlyInstantiable()) { 20521 // Require a definition here because a normal attempt at 20522 // instantiation for a builtin will be ignored, and we won't try 20523 // again later. We assume that the definition of the template 20524 // precedes this use. 20525 InstantiateFunctionDefinition(E->getBeginLoc(), FD, 20526 /*Recursive=*/false, 20527 /*DefinitionRequired=*/true, 20528 /*AtEndOfTU=*/false); 20529 } 20530 // Produce a properly-typed reference to the function. 20531 CXXScopeSpec SS; 20532 SS.Adopt(DRE->getQualifierLoc()); 20533 TemplateArgumentListInfo TemplateArgs; 20534 DRE->copyTemplateArgumentsInto(TemplateArgs); 20535 return BuildDeclRefExpr( 20536 FD, FD->getType(), VK_LValue, DRE->getNameInfo(), 20537 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(), 20538 DRE->getTemplateKeywordLoc(), 20539 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr); 20540 } 20541 } 20542 20543 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 20544 return ExprError(); 20545 } 20546 20547 case BuiltinType::IncompleteMatrixIdx: 20548 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 20549 ->getRowIdx() 20550 ->getBeginLoc(), 20551 diag::err_matrix_incomplete_index); 20552 return ExprError(); 20553 20554 // Expressions of unknown type. 20555 case BuiltinType::OMPArraySection: 20556 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 20557 return ExprError(); 20558 20559 // Expressions of unknown type. 20560 case BuiltinType::OMPArrayShaping: 20561 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 20562 20563 case BuiltinType::OMPIterator: 20564 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 20565 20566 // Everything else should be impossible. 20567 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 20568 case BuiltinType::Id: 20569 #include "clang/Basic/OpenCLImageTypes.def" 20570 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 20571 case BuiltinType::Id: 20572 #include "clang/Basic/OpenCLExtensionTypes.def" 20573 #define SVE_TYPE(Name, Id, SingletonId) \ 20574 case BuiltinType::Id: 20575 #include "clang/Basic/AArch64SVEACLETypes.def" 20576 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 20577 case BuiltinType::Id: 20578 #include "clang/Basic/PPCTypes.def" 20579 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 20580 #include "clang/Basic/RISCVVTypes.def" 20581 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 20582 #define PLACEHOLDER_TYPE(Id, SingletonId) 20583 #include "clang/AST/BuiltinTypes.def" 20584 break; 20585 } 20586 20587 llvm_unreachable("invalid placeholder type!"); 20588 } 20589 20590 bool Sema::CheckCaseExpression(Expr *E) { 20591 if (E->isTypeDependent()) 20592 return true; 20593 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 20594 return E->getType()->isIntegralOrEnumerationType(); 20595 return false; 20596 } 20597 20598 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 20599 ExprResult 20600 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 20601 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 20602 "Unknown Objective-C Boolean value!"); 20603 QualType BoolT = Context.ObjCBuiltinBoolTy; 20604 if (!Context.getBOOLDecl()) { 20605 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 20606 Sema::LookupOrdinaryName); 20607 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 20608 NamedDecl *ND = Result.getFoundDecl(); 20609 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 20610 Context.setBOOLDecl(TD); 20611 } 20612 } 20613 if (Context.getBOOLDecl()) 20614 BoolT = Context.getBOOLType(); 20615 return new (Context) 20616 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 20617 } 20618 20619 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 20620 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 20621 SourceLocation RParen) { 20622 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { 20623 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 20624 return Spec.getPlatform() == Platform; 20625 }); 20626 // Transcribe the "ios" availability check to "maccatalyst" when compiling 20627 // for "maccatalyst" if "maccatalyst" is not specified. 20628 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { 20629 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 20630 return Spec.getPlatform() == "ios"; 20631 }); 20632 } 20633 if (Spec == AvailSpecs.end()) 20634 return None; 20635 return Spec->getVersion(); 20636 }; 20637 20638 VersionTuple Version; 20639 if (auto MaybeVersion = 20640 FindSpecVersion(Context.getTargetInfo().getPlatformName())) 20641 Version = *MaybeVersion; 20642 20643 // The use of `@available` in the enclosing context should be analyzed to 20644 // warn when it's used inappropriately (i.e. not if(@available)). 20645 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 20646 Context->HasPotentialAvailabilityViolations = true; 20647 20648 return new (Context) 20649 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 20650 } 20651 20652 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 20653 ArrayRef<Expr *> SubExprs, QualType T) { 20654 if (!Context.getLangOpts().RecoveryAST) 20655 return ExprError(); 20656 20657 if (isSFINAEContext()) 20658 return ExprError(); 20659 20660 if (T.isNull() || T->isUndeducedType() || 20661 !Context.getLangOpts().RecoveryASTType) 20662 // We don't know the concrete type, fallback to dependent type. 20663 T = Context.DependentTy; 20664 20665 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 20666 } 20667