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/TypeLoc.h" 31 #include "clang/Basic/Builtins.h" 32 #include "clang/Basic/DiagnosticSema.h" 33 #include "clang/Basic/PartialDiagnostic.h" 34 #include "clang/Basic/SourceManager.h" 35 #include "clang/Basic/TargetInfo.h" 36 #include "clang/Lex/LiteralSupport.h" 37 #include "clang/Lex/Preprocessor.h" 38 #include "clang/Sema/AnalysisBasedWarnings.h" 39 #include "clang/Sema/DeclSpec.h" 40 #include "clang/Sema/DelayedDiagnostic.h" 41 #include "clang/Sema/Designator.h" 42 #include "clang/Sema/Initialization.h" 43 #include "clang/Sema/Lookup.h" 44 #include "clang/Sema/Overload.h" 45 #include "clang/Sema/ParsedTemplate.h" 46 #include "clang/Sema/Scope.h" 47 #include "clang/Sema/ScopeInfo.h" 48 #include "clang/Sema/SemaFixItUtils.h" 49 #include "clang/Sema/SemaInternal.h" 50 #include "clang/Sema/Template.h" 51 #include "llvm/ADT/STLExtras.h" 52 #include "llvm/ADT/StringExtras.h" 53 #include "llvm/Support/ConvertUTF.h" 54 #include "llvm/Support/SaveAndRestore.h" 55 56 using namespace clang; 57 using namespace sema; 58 using llvm::RoundingMode; 59 60 /// Determine whether the use of this declaration is valid, without 61 /// emitting diagnostics. 62 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 63 // See if this is an auto-typed variable whose initializer we are parsing. 64 if (ParsingInitForAutoVars.count(D)) 65 return false; 66 67 // See if this is a deleted function. 68 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 69 if (FD->isDeleted()) 70 return false; 71 72 // If the function has a deduced return type, and we can't deduce it, 73 // then we can't use it either. 74 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 75 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 76 return false; 77 78 // See if this is an aligned allocation/deallocation function that is 79 // unavailable. 80 if (TreatUnavailableAsInvalid && 81 isUnavailableAlignedAllocationFunction(*FD)) 82 return false; 83 } 84 85 // See if this function is unavailable. 86 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 87 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 88 return false; 89 90 if (isa<UnresolvedUsingIfExistsDecl>(D)) 91 return false; 92 93 return true; 94 } 95 96 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 97 // Warn if this is used but marked unused. 98 if (const auto *A = D->getAttr<UnusedAttr>()) { 99 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 100 // should diagnose them. 101 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 102 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 103 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 104 if (DC && !DC->hasAttr<UnusedAttr>()) 105 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 106 } 107 } 108 } 109 110 /// Emit a note explaining that this function is deleted. 111 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 112 assert(Decl && Decl->isDeleted()); 113 114 if (Decl->isDefaulted()) { 115 // If the method was explicitly defaulted, point at that declaration. 116 if (!Decl->isImplicit()) 117 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 118 119 // Try to diagnose why this special member function was implicitly 120 // deleted. This might fail, if that reason no longer applies. 121 DiagnoseDeletedDefaultedFunction(Decl); 122 return; 123 } 124 125 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 126 if (Ctor && Ctor->isInheritingConstructor()) 127 return NoteDeletedInheritingConstructor(Ctor); 128 129 Diag(Decl->getLocation(), diag::note_availability_specified_here) 130 << Decl << 1; 131 } 132 133 /// Determine whether a FunctionDecl was ever declared with an 134 /// explicit storage class. 135 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 136 for (auto I : D->redecls()) { 137 if (I->getStorageClass() != SC_None) 138 return true; 139 } 140 return false; 141 } 142 143 /// Check whether we're in an extern inline function and referring to a 144 /// variable or function with internal linkage (C11 6.7.4p3). 145 /// 146 /// This is only a warning because we used to silently accept this code, but 147 /// in many cases it will not behave correctly. This is not enabled in C++ mode 148 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 149 /// and so while there may still be user mistakes, most of the time we can't 150 /// prove that there are errors. 151 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 152 const NamedDecl *D, 153 SourceLocation Loc) { 154 // This is disabled under C++; there are too many ways for this to fire in 155 // contexts where the warning is a false positive, or where it is technically 156 // correct but benign. 157 if (S.getLangOpts().CPlusPlus) 158 return; 159 160 // Check if this is an inlined function or method. 161 FunctionDecl *Current = S.getCurFunctionDecl(); 162 if (!Current) 163 return; 164 if (!Current->isInlined()) 165 return; 166 if (!Current->isExternallyVisible()) 167 return; 168 169 // Check if the decl has internal linkage. 170 if (D->getFormalLinkage() != InternalLinkage) 171 return; 172 173 // Downgrade from ExtWarn to Extension if 174 // (1) the supposedly external inline function is in the main file, 175 // and probably won't be included anywhere else. 176 // (2) the thing we're referencing is a pure function. 177 // (3) the thing we're referencing is another inline function. 178 // This last can give us false negatives, but it's better than warning on 179 // wrappers for simple C library functions. 180 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 181 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 182 if (!DowngradeWarning && UsedFn) 183 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 184 185 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 186 : diag::ext_internal_in_extern_inline) 187 << /*IsVar=*/!UsedFn << D; 188 189 S.MaybeSuggestAddingStaticToDecl(Current); 190 191 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 192 << D; 193 } 194 195 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 196 const FunctionDecl *First = Cur->getFirstDecl(); 197 198 // Suggest "static" on the function, if possible. 199 if (!hasAnyExplicitStorageClass(First)) { 200 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 201 Diag(DeclBegin, diag::note_convert_inline_to_static) 202 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 203 } 204 } 205 206 /// Determine whether the use of this declaration is valid, and 207 /// emit any corresponding diagnostics. 208 /// 209 /// This routine diagnoses various problems with referencing 210 /// declarations that can occur when using a declaration. For example, 211 /// it might warn if a deprecated or unavailable declaration is being 212 /// used, or produce an error (and return true) if a C++0x deleted 213 /// function is being used. 214 /// 215 /// \returns true if there was an error (this declaration cannot be 216 /// referenced), false otherwise. 217 /// 218 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 219 const ObjCInterfaceDecl *UnknownObjCClass, 220 bool ObjCPropertyAccess, 221 bool AvoidPartialAvailabilityChecks, 222 ObjCInterfaceDecl *ClassReceiver) { 223 SourceLocation Loc = Locs.front(); 224 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 225 // If there were any diagnostics suppressed by template argument deduction, 226 // emit them now. 227 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 228 if (Pos != SuppressedDiagnostics.end()) { 229 for (const PartialDiagnosticAt &Suppressed : Pos->second) 230 Diag(Suppressed.first, Suppressed.second); 231 232 // Clear out the list of suppressed diagnostics, so that we don't emit 233 // them again for this specialization. However, we don't obsolete this 234 // entry from the table, because we want to avoid ever emitting these 235 // diagnostics again. 236 Pos->second.clear(); 237 } 238 239 // C++ [basic.start.main]p3: 240 // The function 'main' shall not be used within a program. 241 if (cast<FunctionDecl>(D)->isMain()) 242 Diag(Loc, diag::ext_main_used); 243 244 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 245 } 246 247 // See if this is an auto-typed variable whose initializer we are parsing. 248 if (ParsingInitForAutoVars.count(D)) { 249 if (isa<BindingDecl>(D)) { 250 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 251 << D->getDeclName(); 252 } else { 253 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 254 << D->getDeclName() << cast<VarDecl>(D)->getType(); 255 } 256 return true; 257 } 258 259 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 260 // See if this is a deleted function. 261 if (FD->isDeleted()) { 262 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 263 if (Ctor && Ctor->isInheritingConstructor()) 264 Diag(Loc, diag::err_deleted_inherited_ctor_use) 265 << Ctor->getParent() 266 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 267 else 268 Diag(Loc, diag::err_deleted_function_use); 269 NoteDeletedFunction(FD); 270 return true; 271 } 272 273 // [expr.prim.id]p4 274 // A program that refers explicitly or implicitly to a function with a 275 // trailing requires-clause whose constraint-expression is not satisfied, 276 // other than to declare it, is ill-formed. [...] 277 // 278 // See if this is a function with constraints that need to be satisfied. 279 // Check this before deducing the return type, as it might instantiate the 280 // definition. 281 if (FD->getTrailingRequiresClause()) { 282 ConstraintSatisfaction Satisfaction; 283 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 284 // A diagnostic will have already been generated (non-constant 285 // constraint expression, for example) 286 return true; 287 if (!Satisfaction.IsSatisfied) { 288 Diag(Loc, 289 diag::err_reference_to_function_with_unsatisfied_constraints) 290 << D; 291 DiagnoseUnsatisfiedConstraint(Satisfaction); 292 return true; 293 } 294 } 295 296 // If the function has a deduced return type, and we can't deduce it, 297 // then we can't use it either. 298 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 299 DeduceReturnType(FD, Loc)) 300 return true; 301 302 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 303 return true; 304 305 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 306 return true; 307 } 308 309 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 310 // Lambdas are only default-constructible or assignable in C++2a onwards. 311 if (MD->getParent()->isLambda() && 312 ((isa<CXXConstructorDecl>(MD) && 313 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 314 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 315 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 316 << !isa<CXXConstructorDecl>(MD); 317 } 318 } 319 320 auto getReferencedObjCProp = [](const NamedDecl *D) -> 321 const ObjCPropertyDecl * { 322 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 323 return MD->findPropertyDecl(); 324 return nullptr; 325 }; 326 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 327 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 328 return true; 329 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 330 return true; 331 } 332 333 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 334 // Only the variables omp_in and omp_out are allowed in the combiner. 335 // Only the variables omp_priv and omp_orig are allowed in the 336 // initializer-clause. 337 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 338 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 339 isa<VarDecl>(D)) { 340 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 341 << getCurFunction()->HasOMPDeclareReductionCombiner; 342 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 343 return true; 344 } 345 346 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 347 // List-items in map clauses on this construct may only refer to the declared 348 // variable var and entities that could be referenced by a procedure defined 349 // at the same location 350 if (LangOpts.OpenMP && isa<VarDecl>(D) && 351 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 352 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 353 << getOpenMPDeclareMapperVarName(); 354 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 355 return true; 356 } 357 358 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) { 359 Diag(Loc, diag::err_use_of_empty_using_if_exists); 360 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); 361 return true; 362 } 363 364 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 365 AvoidPartialAvailabilityChecks, ClassReceiver); 366 367 DiagnoseUnusedOfDecl(*this, D, Loc); 368 369 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 370 371 if (auto *VD = dyn_cast<ValueDecl>(D)) 372 checkTypeSupport(VD->getType(), Loc, VD); 373 374 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 375 if (!Context.getTargetInfo().isTLSSupported()) 376 if (const auto *VD = dyn_cast<VarDecl>(D)) 377 if (VD->getTLSKind() != VarDecl::TLS_None) 378 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 379 } 380 381 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 382 !isUnevaluatedContext()) { 383 // C++ [expr.prim.req.nested] p3 384 // A local parameter shall only appear as an unevaluated operand 385 // (Clause 8) within the constraint-expression. 386 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 387 << D; 388 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 389 return true; 390 } 391 392 return false; 393 } 394 395 /// DiagnoseSentinelCalls - This routine checks whether a call or 396 /// message-send is to a declaration with the sentinel attribute, and 397 /// if so, it checks that the requirements of the sentinel are 398 /// satisfied. 399 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 400 ArrayRef<Expr *> Args) { 401 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 402 if (!attr) 403 return; 404 405 // The number of formal parameters of the declaration. 406 unsigned numFormalParams; 407 408 // The kind of declaration. This is also an index into a %select in 409 // the diagnostic. 410 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 411 412 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 413 numFormalParams = MD->param_size(); 414 calleeType = CT_Method; 415 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 416 numFormalParams = FD->param_size(); 417 calleeType = CT_Function; 418 } else if (isa<VarDecl>(D)) { 419 QualType type = cast<ValueDecl>(D)->getType(); 420 const FunctionType *fn = nullptr; 421 if (const PointerType *ptr = type->getAs<PointerType>()) { 422 fn = ptr->getPointeeType()->getAs<FunctionType>(); 423 if (!fn) return; 424 calleeType = CT_Function; 425 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 426 fn = ptr->getPointeeType()->castAs<FunctionType>(); 427 calleeType = CT_Block; 428 } else { 429 return; 430 } 431 432 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 433 numFormalParams = proto->getNumParams(); 434 } else { 435 numFormalParams = 0; 436 } 437 } else { 438 return; 439 } 440 441 // "nullPos" is the number of formal parameters at the end which 442 // effectively count as part of the variadic arguments. This is 443 // useful if you would prefer to not have *any* formal parameters, 444 // but the language forces you to have at least one. 445 unsigned nullPos = attr->getNullPos(); 446 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 447 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 448 449 // The number of arguments which should follow the sentinel. 450 unsigned numArgsAfterSentinel = attr->getSentinel(); 451 452 // If there aren't enough arguments for all the formal parameters, 453 // the sentinel, and the args after the sentinel, complain. 454 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 455 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 456 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 457 return; 458 } 459 460 // Otherwise, find the sentinel expression. 461 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 462 if (!sentinelExpr) return; 463 if (sentinelExpr->isValueDependent()) return; 464 if (Context.isSentinelNullExpr(sentinelExpr)) return; 465 466 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 467 // or 'NULL' if those are actually defined in the context. Only use 468 // 'nil' for ObjC methods, where it's much more likely that the 469 // variadic arguments form a list of object pointers. 470 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 471 std::string NullValue; 472 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 473 NullValue = "nil"; 474 else if (getLangOpts().CPlusPlus11) 475 NullValue = "nullptr"; 476 else if (PP.isMacroDefined("NULL")) 477 NullValue = "NULL"; 478 else 479 NullValue = "(void*) 0"; 480 481 if (MissingNilLoc.isInvalid()) 482 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 483 else 484 Diag(MissingNilLoc, diag::warn_missing_sentinel) 485 << int(calleeType) 486 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 487 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 488 } 489 490 SourceRange Sema::getExprRange(Expr *E) const { 491 return E ? E->getSourceRange() : SourceRange(); 492 } 493 494 //===----------------------------------------------------------------------===// 495 // Standard Promotions and Conversions 496 //===----------------------------------------------------------------------===// 497 498 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 499 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 500 // Handle any placeholder expressions which made it here. 501 if (E->getType()->isPlaceholderType()) { 502 ExprResult result = CheckPlaceholderExpr(E); 503 if (result.isInvalid()) return ExprError(); 504 E = result.get(); 505 } 506 507 QualType Ty = E->getType(); 508 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 509 510 if (Ty->isFunctionType()) { 511 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 512 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 513 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 514 return ExprError(); 515 516 E = ImpCastExprToType(E, Context.getPointerType(Ty), 517 CK_FunctionToPointerDecay).get(); 518 } else if (Ty->isArrayType()) { 519 // In C90 mode, arrays only promote to pointers if the array expression is 520 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 521 // type 'array of type' is converted to an expression that has type 'pointer 522 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 523 // that has type 'array of type' ...". The relevant change is "an lvalue" 524 // (C90) to "an expression" (C99). 525 // 526 // C++ 4.2p1: 527 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 528 // T" can be converted to an rvalue of type "pointer to T". 529 // 530 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { 531 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 532 CK_ArrayToPointerDecay); 533 if (Res.isInvalid()) 534 return ExprError(); 535 E = Res.get(); 536 } 537 } 538 return E; 539 } 540 541 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 542 // Check to see if we are dereferencing a null pointer. If so, 543 // and if not volatile-qualified, this is undefined behavior that the 544 // optimizer will delete, so warn about it. People sometimes try to use this 545 // to get a deterministic trap and are surprised by clang's behavior. This 546 // only handles the pattern "*null", which is a very syntactic check. 547 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 548 if (UO && UO->getOpcode() == UO_Deref && 549 UO->getSubExpr()->getType()->isPointerType()) { 550 const LangAS AS = 551 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 552 if ((!isTargetAddressSpace(AS) || 553 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 554 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 555 S.Context, Expr::NPC_ValueDependentIsNotNull) && 556 !UO->getType().isVolatileQualified()) { 557 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 558 S.PDiag(diag::warn_indirection_through_null) 559 << UO->getSubExpr()->getSourceRange()); 560 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 561 S.PDiag(diag::note_indirection_through_null)); 562 } 563 } 564 } 565 566 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 567 SourceLocation AssignLoc, 568 const Expr* RHS) { 569 const ObjCIvarDecl *IV = OIRE->getDecl(); 570 if (!IV) 571 return; 572 573 DeclarationName MemberName = IV->getDeclName(); 574 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 575 if (!Member || !Member->isStr("isa")) 576 return; 577 578 const Expr *Base = OIRE->getBase(); 579 QualType BaseType = Base->getType(); 580 if (OIRE->isArrow()) 581 BaseType = BaseType->getPointeeType(); 582 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 583 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 584 ObjCInterfaceDecl *ClassDeclared = nullptr; 585 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 586 if (!ClassDeclared->getSuperClass() 587 && (*ClassDeclared->ivar_begin()) == IV) { 588 if (RHS) { 589 NamedDecl *ObjectSetClass = 590 S.LookupSingleName(S.TUScope, 591 &S.Context.Idents.get("object_setClass"), 592 SourceLocation(), S.LookupOrdinaryName); 593 if (ObjectSetClass) { 594 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 595 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 596 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 597 "object_setClass(") 598 << FixItHint::CreateReplacement( 599 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 600 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 601 } 602 else 603 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 604 } else { 605 NamedDecl *ObjectGetClass = 606 S.LookupSingleName(S.TUScope, 607 &S.Context.Idents.get("object_getClass"), 608 SourceLocation(), S.LookupOrdinaryName); 609 if (ObjectGetClass) 610 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 611 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 612 "object_getClass(") 613 << FixItHint::CreateReplacement( 614 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 615 else 616 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 617 } 618 S.Diag(IV->getLocation(), diag::note_ivar_decl); 619 } 620 } 621 } 622 623 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 624 // Handle any placeholder expressions which made it here. 625 if (E->getType()->isPlaceholderType()) { 626 ExprResult result = CheckPlaceholderExpr(E); 627 if (result.isInvalid()) return ExprError(); 628 E = result.get(); 629 } 630 631 // C++ [conv.lval]p1: 632 // A glvalue of a non-function, non-array type T can be 633 // converted to a prvalue. 634 if (!E->isGLValue()) return E; 635 636 QualType T = E->getType(); 637 assert(!T.isNull() && "r-value conversion on typeless expression?"); 638 639 // lvalue-to-rvalue conversion cannot be applied to function or array types. 640 if (T->isFunctionType() || T->isArrayType()) 641 return E; 642 643 // We don't want to throw lvalue-to-rvalue casts on top of 644 // expressions of certain types in C++. 645 if (getLangOpts().CPlusPlus && 646 (E->getType() == Context.OverloadTy || 647 T->isDependentType() || 648 T->isRecordType())) 649 return E; 650 651 // The C standard is actually really unclear on this point, and 652 // DR106 tells us what the result should be but not why. It's 653 // generally best to say that void types just doesn't undergo 654 // lvalue-to-rvalue at all. Note that expressions of unqualified 655 // 'void' type are never l-values, but qualified void can be. 656 if (T->isVoidType()) 657 return E; 658 659 // OpenCL usually rejects direct accesses to values of 'half' type. 660 if (getLangOpts().OpenCL && 661 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 662 T->isHalfType()) { 663 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 664 << 0 << T; 665 return ExprError(); 666 } 667 668 CheckForNullPointerDereference(*this, E); 669 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 670 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 671 &Context.Idents.get("object_getClass"), 672 SourceLocation(), LookupOrdinaryName); 673 if (ObjectGetClass) 674 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 675 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 676 << FixItHint::CreateReplacement( 677 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 678 else 679 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 680 } 681 else if (const ObjCIvarRefExpr *OIRE = 682 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 683 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 684 685 // C++ [conv.lval]p1: 686 // [...] If T is a non-class type, the type of the prvalue is the 687 // cv-unqualified version of T. Otherwise, the type of the 688 // rvalue is T. 689 // 690 // C99 6.3.2.1p2: 691 // If the lvalue has qualified type, the value has the unqualified 692 // version of the type of the lvalue; otherwise, the value has the 693 // type of the lvalue. 694 if (T.hasQualifiers()) 695 T = T.getUnqualifiedType(); 696 697 // Under the MS ABI, lock down the inheritance model now. 698 if (T->isMemberPointerType() && 699 Context.getTargetInfo().getCXXABI().isMicrosoft()) 700 (void)isCompleteType(E->getExprLoc(), T); 701 702 ExprResult Res = CheckLValueToRValueConversionOperand(E); 703 if (Res.isInvalid()) 704 return Res; 705 E = Res.get(); 706 707 // Loading a __weak object implicitly retains the value, so we need a cleanup to 708 // balance that. 709 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 710 Cleanup.setExprNeedsCleanups(true); 711 712 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 713 Cleanup.setExprNeedsCleanups(true); 714 715 // C++ [conv.lval]p3: 716 // If T is cv std::nullptr_t, the result is a null pointer constant. 717 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 718 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, 719 CurFPFeatureOverrides()); 720 721 // C11 6.3.2.1p2: 722 // ... if the lvalue has atomic type, the value has the non-atomic version 723 // of the type of the lvalue ... 724 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 725 T = Atomic->getValueType().getUnqualifiedType(); 726 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 727 nullptr, VK_PRValue, FPOptionsOverride()); 728 } 729 730 return Res; 731 } 732 733 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 734 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 735 if (Res.isInvalid()) 736 return ExprError(); 737 Res = DefaultLvalueConversion(Res.get()); 738 if (Res.isInvalid()) 739 return ExprError(); 740 return Res; 741 } 742 743 /// CallExprUnaryConversions - a special case of an unary conversion 744 /// performed on a function designator of a call expression. 745 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 746 QualType Ty = E->getType(); 747 ExprResult Res = E; 748 // Only do implicit cast for a function type, but not for a pointer 749 // to function type. 750 if (Ty->isFunctionType()) { 751 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 752 CK_FunctionToPointerDecay); 753 if (Res.isInvalid()) 754 return ExprError(); 755 } 756 Res = DefaultLvalueConversion(Res.get()); 757 if (Res.isInvalid()) 758 return ExprError(); 759 return Res.get(); 760 } 761 762 /// UsualUnaryConversions - Performs various conversions that are common to most 763 /// operators (C99 6.3). The conversions of array and function types are 764 /// sometimes suppressed. For example, the array->pointer conversion doesn't 765 /// apply if the array is an argument to the sizeof or address (&) operators. 766 /// In these instances, this routine should *not* be called. 767 ExprResult Sema::UsualUnaryConversions(Expr *E) { 768 // First, convert to an r-value. 769 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 770 if (Res.isInvalid()) 771 return ExprError(); 772 E = Res.get(); 773 774 QualType Ty = E->getType(); 775 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 776 777 // Half FP have to be promoted to float unless it is natively supported 778 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 779 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 780 781 // Try to perform integral promotions if the object has a theoretically 782 // promotable type. 783 if (Ty->isIntegralOrUnscopedEnumerationType()) { 784 // C99 6.3.1.1p2: 785 // 786 // The following may be used in an expression wherever an int or 787 // unsigned int may be used: 788 // - an object or expression with an integer type whose integer 789 // conversion rank is less than or equal to the rank of int 790 // and unsigned int. 791 // - A bit-field of type _Bool, int, signed int, or unsigned int. 792 // 793 // If an int can represent all values of the original type, the 794 // value is converted to an int; otherwise, it is converted to an 795 // unsigned int. These are called the integer promotions. All 796 // other types are unchanged by the integer promotions. 797 798 QualType PTy = Context.isPromotableBitField(E); 799 if (!PTy.isNull()) { 800 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 801 return E; 802 } 803 if (Ty->isPromotableIntegerType()) { 804 QualType PT = Context.getPromotedIntegerType(Ty); 805 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 806 return E; 807 } 808 } 809 return E; 810 } 811 812 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 813 /// do not have a prototype. Arguments that have type float or __fp16 814 /// are promoted to double. All other argument types are converted by 815 /// UsualUnaryConversions(). 816 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 817 QualType Ty = E->getType(); 818 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 819 820 ExprResult Res = UsualUnaryConversions(E); 821 if (Res.isInvalid()) 822 return ExprError(); 823 E = Res.get(); 824 825 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 826 // promote to double. 827 // Note that default argument promotion applies only to float (and 828 // half/fp16); it does not apply to _Float16. 829 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 830 if (BTy && (BTy->getKind() == BuiltinType::Half || 831 BTy->getKind() == BuiltinType::Float)) { 832 if (getLangOpts().OpenCL && 833 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 834 if (BTy->getKind() == BuiltinType::Half) { 835 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 836 } 837 } else { 838 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 839 } 840 } 841 if (BTy && 842 getLangOpts().getExtendIntArgs() == 843 LangOptions::ExtendArgsKind::ExtendTo64 && 844 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && 845 Context.getTypeSizeInChars(BTy) < 846 Context.getTypeSizeInChars(Context.LongLongTy)) { 847 E = (Ty->isUnsignedIntegerType()) 848 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) 849 .get() 850 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); 851 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && 852 "Unexpected typesize for LongLongTy"); 853 } 854 855 // C++ performs lvalue-to-rvalue conversion as a default argument 856 // promotion, even on class types, but note: 857 // C++11 [conv.lval]p2: 858 // When an lvalue-to-rvalue conversion occurs in an unevaluated 859 // operand or a subexpression thereof the value contained in the 860 // referenced object is not accessed. Otherwise, if the glvalue 861 // has a class type, the conversion copy-initializes a temporary 862 // of type T from the glvalue and the result of the conversion 863 // is a prvalue for the temporary. 864 // FIXME: add some way to gate this entire thing for correctness in 865 // potentially potentially evaluated contexts. 866 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 867 ExprResult Temp = PerformCopyInitialization( 868 InitializedEntity::InitializeTemporary(E->getType()), 869 E->getExprLoc(), E); 870 if (Temp.isInvalid()) 871 return ExprError(); 872 E = Temp.get(); 873 } 874 875 return E; 876 } 877 878 /// Determine the degree of POD-ness for an expression. 879 /// Incomplete types are considered POD, since this check can be performed 880 /// when we're in an unevaluated context. 881 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 882 if (Ty->isIncompleteType()) { 883 // C++11 [expr.call]p7: 884 // After these conversions, if the argument does not have arithmetic, 885 // enumeration, pointer, pointer to member, or class type, the program 886 // is ill-formed. 887 // 888 // Since we've already performed array-to-pointer and function-to-pointer 889 // decay, the only such type in C++ is cv void. This also handles 890 // initializer lists as variadic arguments. 891 if (Ty->isVoidType()) 892 return VAK_Invalid; 893 894 if (Ty->isObjCObjectType()) 895 return VAK_Invalid; 896 return VAK_Valid; 897 } 898 899 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 900 return VAK_Invalid; 901 902 if (Ty.isCXX98PODType(Context)) 903 return VAK_Valid; 904 905 // C++11 [expr.call]p7: 906 // Passing a potentially-evaluated argument of class type (Clause 9) 907 // having a non-trivial copy constructor, a non-trivial move constructor, 908 // or a non-trivial destructor, with no corresponding parameter, 909 // is conditionally-supported with implementation-defined semantics. 910 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 911 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 912 if (!Record->hasNonTrivialCopyConstructor() && 913 !Record->hasNonTrivialMoveConstructor() && 914 !Record->hasNonTrivialDestructor()) 915 return VAK_ValidInCXX11; 916 917 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 918 return VAK_Valid; 919 920 if (Ty->isObjCObjectType()) 921 return VAK_Invalid; 922 923 if (getLangOpts().MSVCCompat) 924 return VAK_MSVCUndefined; 925 926 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 927 // permitted to reject them. We should consider doing so. 928 return VAK_Undefined; 929 } 930 931 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 932 // Don't allow one to pass an Objective-C interface to a vararg. 933 const QualType &Ty = E->getType(); 934 VarArgKind VAK = isValidVarArgType(Ty); 935 936 // Complain about passing non-POD types through varargs. 937 switch (VAK) { 938 case VAK_ValidInCXX11: 939 DiagRuntimeBehavior( 940 E->getBeginLoc(), nullptr, 941 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 942 LLVM_FALLTHROUGH; 943 case VAK_Valid: 944 if (Ty->isRecordType()) { 945 // This is unlikely to be what the user intended. If the class has a 946 // 'c_str' member function, the user probably meant to call that. 947 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 948 PDiag(diag::warn_pass_class_arg_to_vararg) 949 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 950 } 951 break; 952 953 case VAK_Undefined: 954 case VAK_MSVCUndefined: 955 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 956 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 957 << getLangOpts().CPlusPlus11 << Ty << CT); 958 break; 959 960 case VAK_Invalid: 961 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 962 Diag(E->getBeginLoc(), 963 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 964 << Ty << CT; 965 else if (Ty->isObjCObjectType()) 966 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 967 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 968 << Ty << CT); 969 else 970 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 971 << isa<InitListExpr>(E) << Ty << CT; 972 break; 973 } 974 } 975 976 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 977 /// will create a trap if the resulting type is not a POD type. 978 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 979 FunctionDecl *FDecl) { 980 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 981 // Strip the unbridged-cast placeholder expression off, if applicable. 982 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 983 (CT == VariadicMethod || 984 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 985 E = stripARCUnbridgedCast(E); 986 987 // Otherwise, do normal placeholder checking. 988 } else { 989 ExprResult ExprRes = CheckPlaceholderExpr(E); 990 if (ExprRes.isInvalid()) 991 return ExprError(); 992 E = ExprRes.get(); 993 } 994 } 995 996 ExprResult ExprRes = DefaultArgumentPromotion(E); 997 if (ExprRes.isInvalid()) 998 return ExprError(); 999 1000 // Copy blocks to the heap. 1001 if (ExprRes.get()->getType()->isBlockPointerType()) 1002 maybeExtendBlockObject(ExprRes); 1003 1004 E = ExprRes.get(); 1005 1006 // Diagnostics regarding non-POD argument types are 1007 // emitted along with format string checking in Sema::CheckFunctionCall(). 1008 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 1009 // Turn this into a trap. 1010 CXXScopeSpec SS; 1011 SourceLocation TemplateKWLoc; 1012 UnqualifiedId Name; 1013 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1014 E->getBeginLoc()); 1015 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1016 /*HasTrailingLParen=*/true, 1017 /*IsAddressOfOperand=*/false); 1018 if (TrapFn.isInvalid()) 1019 return ExprError(); 1020 1021 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1022 None, E->getEndLoc()); 1023 if (Call.isInvalid()) 1024 return ExprError(); 1025 1026 ExprResult Comma = 1027 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1028 if (Comma.isInvalid()) 1029 return ExprError(); 1030 return Comma.get(); 1031 } 1032 1033 if (!getLangOpts().CPlusPlus && 1034 RequireCompleteType(E->getExprLoc(), E->getType(), 1035 diag::err_call_incomplete_argument)) 1036 return ExprError(); 1037 1038 return E; 1039 } 1040 1041 /// Converts an integer to complex float type. Helper function of 1042 /// UsualArithmeticConversions() 1043 /// 1044 /// \return false if the integer expression is an integer type and is 1045 /// successfully converted to the complex type. 1046 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1047 ExprResult &ComplexExpr, 1048 QualType IntTy, 1049 QualType ComplexTy, 1050 bool SkipCast) { 1051 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1052 if (SkipCast) return false; 1053 if (IntTy->isIntegerType()) { 1054 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1055 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1056 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1057 CK_FloatingRealToComplex); 1058 } else { 1059 assert(IntTy->isComplexIntegerType()); 1060 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1061 CK_IntegralComplexToFloatingComplex); 1062 } 1063 return false; 1064 } 1065 1066 /// Handle arithmetic conversion with complex types. Helper function of 1067 /// UsualArithmeticConversions() 1068 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1069 ExprResult &RHS, QualType LHSType, 1070 QualType RHSType, 1071 bool IsCompAssign) { 1072 // if we have an integer operand, the result is the complex type. 1073 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1074 /*skipCast*/false)) 1075 return LHSType; 1076 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1077 /*skipCast*/IsCompAssign)) 1078 return RHSType; 1079 1080 // This handles complex/complex, complex/float, or float/complex. 1081 // When both operands are complex, the shorter operand is converted to the 1082 // type of the longer, and that is the type of the result. This corresponds 1083 // to what is done when combining two real floating-point operands. 1084 // The fun begins when size promotion occur across type domains. 1085 // From H&S 6.3.4: When one operand is complex and the other is a real 1086 // floating-point type, the less precise type is converted, within it's 1087 // real or complex domain, to the precision of the other type. For example, 1088 // when combining a "long double" with a "double _Complex", the 1089 // "double _Complex" is promoted to "long double _Complex". 1090 1091 // Compute the rank of the two types, regardless of whether they are complex. 1092 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1093 1094 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1095 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1096 QualType LHSElementType = 1097 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1098 QualType RHSElementType = 1099 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1100 1101 QualType ResultType = S.Context.getComplexType(LHSElementType); 1102 if (Order < 0) { 1103 // Promote the precision of the LHS if not an assignment. 1104 ResultType = S.Context.getComplexType(RHSElementType); 1105 if (!IsCompAssign) { 1106 if (LHSComplexType) 1107 LHS = 1108 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1109 else 1110 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1111 } 1112 } else if (Order > 0) { 1113 // Promote the precision of the RHS. 1114 if (RHSComplexType) 1115 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1116 else 1117 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1118 } 1119 return ResultType; 1120 } 1121 1122 /// Handle arithmetic conversion from integer to float. Helper function 1123 /// of UsualArithmeticConversions() 1124 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1125 ExprResult &IntExpr, 1126 QualType FloatTy, QualType IntTy, 1127 bool ConvertFloat, bool ConvertInt) { 1128 if (IntTy->isIntegerType()) { 1129 if (ConvertInt) 1130 // Convert intExpr to the lhs floating point type. 1131 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1132 CK_IntegralToFloating); 1133 return FloatTy; 1134 } 1135 1136 // Convert both sides to the appropriate complex float. 1137 assert(IntTy->isComplexIntegerType()); 1138 QualType result = S.Context.getComplexType(FloatTy); 1139 1140 // _Complex int -> _Complex float 1141 if (ConvertInt) 1142 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1143 CK_IntegralComplexToFloatingComplex); 1144 1145 // float -> _Complex float 1146 if (ConvertFloat) 1147 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1148 CK_FloatingRealToComplex); 1149 1150 return result; 1151 } 1152 1153 /// Handle arithmethic conversion with floating point types. Helper 1154 /// function of UsualArithmeticConversions() 1155 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1156 ExprResult &RHS, QualType LHSType, 1157 QualType RHSType, bool IsCompAssign) { 1158 bool LHSFloat = LHSType->isRealFloatingType(); 1159 bool RHSFloat = RHSType->isRealFloatingType(); 1160 1161 // N1169 4.1.4: If one of the operands has a floating type and the other 1162 // operand has a fixed-point type, the fixed-point operand 1163 // is converted to the floating type [...] 1164 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1165 if (LHSFloat) 1166 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1167 else if (!IsCompAssign) 1168 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1169 return LHSFloat ? LHSType : RHSType; 1170 } 1171 1172 // If we have two real floating types, convert the smaller operand 1173 // to the bigger result. 1174 if (LHSFloat && RHSFloat) { 1175 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1176 if (order > 0) { 1177 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1178 return LHSType; 1179 } 1180 1181 assert(order < 0 && "illegal float comparison"); 1182 if (!IsCompAssign) 1183 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1184 return RHSType; 1185 } 1186 1187 if (LHSFloat) { 1188 // Half FP has to be promoted to float unless it is natively supported 1189 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1190 LHSType = S.Context.FloatTy; 1191 1192 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1193 /*ConvertFloat=*/!IsCompAssign, 1194 /*ConvertInt=*/ true); 1195 } 1196 assert(RHSFloat); 1197 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1198 /*ConvertFloat=*/ true, 1199 /*ConvertInt=*/!IsCompAssign); 1200 } 1201 1202 /// Diagnose attempts to convert between __float128, __ibm128 and 1203 /// long double if there is no support for such conversion. 1204 /// Helper function of UsualArithmeticConversions(). 1205 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1206 QualType RHSType) { 1207 // No issue if either is not a floating point type. 1208 if (!LHSType->isFloatingType() || !RHSType->isFloatingType()) 1209 return false; 1210 1211 // No issue if both have the same 128-bit float semantics. 1212 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1213 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1214 1215 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType; 1216 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType; 1217 1218 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem); 1219 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem); 1220 1221 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() || 1222 &RHSSem != &llvm::APFloat::IEEEquad()) && 1223 (&LHSSem != &llvm::APFloat::IEEEquad() || 1224 &RHSSem != &llvm::APFloat::PPCDoubleDouble())) 1225 return false; 1226 1227 return true; 1228 } 1229 1230 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1231 1232 namespace { 1233 /// These helper callbacks are placed in an anonymous namespace to 1234 /// permit their use as function template parameters. 1235 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1236 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1237 } 1238 1239 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1240 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1241 CK_IntegralComplexCast); 1242 } 1243 } 1244 1245 /// Handle integer arithmetic conversions. Helper function of 1246 /// UsualArithmeticConversions() 1247 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1248 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1249 ExprResult &RHS, QualType LHSType, 1250 QualType RHSType, bool IsCompAssign) { 1251 // The rules for this case are in C99 6.3.1.8 1252 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1253 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1254 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1255 if (LHSSigned == RHSSigned) { 1256 // Same signedness; use the higher-ranked type 1257 if (order >= 0) { 1258 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1259 return LHSType; 1260 } else if (!IsCompAssign) 1261 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1262 return RHSType; 1263 } else if (order != (LHSSigned ? 1 : -1)) { 1264 // The unsigned type has greater than or equal rank to the 1265 // signed type, so use the unsigned type 1266 if (RHSSigned) { 1267 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1268 return LHSType; 1269 } else if (!IsCompAssign) 1270 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1271 return RHSType; 1272 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1273 // The two types are different widths; if we are here, that 1274 // means the signed type is larger than the unsigned type, so 1275 // use the signed type. 1276 if (LHSSigned) { 1277 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1278 return LHSType; 1279 } else if (!IsCompAssign) 1280 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1281 return RHSType; 1282 } else { 1283 // The signed type is higher-ranked than the unsigned type, 1284 // but isn't actually any bigger (like unsigned int and long 1285 // on most 32-bit systems). Use the unsigned type corresponding 1286 // to the signed type. 1287 QualType result = 1288 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1289 RHS = (*doRHSCast)(S, RHS.get(), result); 1290 if (!IsCompAssign) 1291 LHS = (*doLHSCast)(S, LHS.get(), result); 1292 return result; 1293 } 1294 } 1295 1296 /// Handle conversions with GCC complex int extension. Helper function 1297 /// of UsualArithmeticConversions() 1298 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1299 ExprResult &RHS, QualType LHSType, 1300 QualType RHSType, 1301 bool IsCompAssign) { 1302 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1303 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1304 1305 if (LHSComplexInt && RHSComplexInt) { 1306 QualType LHSEltType = LHSComplexInt->getElementType(); 1307 QualType RHSEltType = RHSComplexInt->getElementType(); 1308 QualType ScalarType = 1309 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1310 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1311 1312 return S.Context.getComplexType(ScalarType); 1313 } 1314 1315 if (LHSComplexInt) { 1316 QualType LHSEltType = LHSComplexInt->getElementType(); 1317 QualType ScalarType = 1318 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1319 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1320 QualType ComplexType = S.Context.getComplexType(ScalarType); 1321 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1322 CK_IntegralRealToComplex); 1323 1324 return ComplexType; 1325 } 1326 1327 assert(RHSComplexInt); 1328 1329 QualType RHSEltType = RHSComplexInt->getElementType(); 1330 QualType ScalarType = 1331 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1332 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1333 QualType ComplexType = S.Context.getComplexType(ScalarType); 1334 1335 if (!IsCompAssign) 1336 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1337 CK_IntegralRealToComplex); 1338 return ComplexType; 1339 } 1340 1341 /// Return the rank of a given fixed point or integer type. The value itself 1342 /// doesn't matter, but the values must be increasing with proper increasing 1343 /// rank as described in N1169 4.1.1. 1344 static unsigned GetFixedPointRank(QualType Ty) { 1345 const auto *BTy = Ty->getAs<BuiltinType>(); 1346 assert(BTy && "Expected a builtin type."); 1347 1348 switch (BTy->getKind()) { 1349 case BuiltinType::ShortFract: 1350 case BuiltinType::UShortFract: 1351 case BuiltinType::SatShortFract: 1352 case BuiltinType::SatUShortFract: 1353 return 1; 1354 case BuiltinType::Fract: 1355 case BuiltinType::UFract: 1356 case BuiltinType::SatFract: 1357 case BuiltinType::SatUFract: 1358 return 2; 1359 case BuiltinType::LongFract: 1360 case BuiltinType::ULongFract: 1361 case BuiltinType::SatLongFract: 1362 case BuiltinType::SatULongFract: 1363 return 3; 1364 case BuiltinType::ShortAccum: 1365 case BuiltinType::UShortAccum: 1366 case BuiltinType::SatShortAccum: 1367 case BuiltinType::SatUShortAccum: 1368 return 4; 1369 case BuiltinType::Accum: 1370 case BuiltinType::UAccum: 1371 case BuiltinType::SatAccum: 1372 case BuiltinType::SatUAccum: 1373 return 5; 1374 case BuiltinType::LongAccum: 1375 case BuiltinType::ULongAccum: 1376 case BuiltinType::SatLongAccum: 1377 case BuiltinType::SatULongAccum: 1378 return 6; 1379 default: 1380 if (BTy->isInteger()) 1381 return 0; 1382 llvm_unreachable("Unexpected fixed point or integer type"); 1383 } 1384 } 1385 1386 /// handleFixedPointConversion - Fixed point operations between fixed 1387 /// point types and integers or other fixed point types do not fall under 1388 /// usual arithmetic conversion since these conversions could result in loss 1389 /// of precsision (N1169 4.1.4). These operations should be calculated with 1390 /// the full precision of their result type (N1169 4.1.6.2.1). 1391 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1392 QualType RHSTy) { 1393 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1394 "Expected at least one of the operands to be a fixed point type"); 1395 assert((LHSTy->isFixedPointOrIntegerType() || 1396 RHSTy->isFixedPointOrIntegerType()) && 1397 "Special fixed point arithmetic operation conversions are only " 1398 "applied to ints or other fixed point types"); 1399 1400 // If one operand has signed fixed-point type and the other operand has 1401 // unsigned fixed-point type, then the unsigned fixed-point operand is 1402 // converted to its corresponding signed fixed-point type and the resulting 1403 // type is the type of the converted operand. 1404 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1405 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1406 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1407 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1408 1409 // The result type is the type with the highest rank, whereby a fixed-point 1410 // conversion rank is always greater than an integer conversion rank; if the 1411 // type of either of the operands is a saturating fixedpoint type, the result 1412 // type shall be the saturating fixed-point type corresponding to the type 1413 // with the highest rank; the resulting value is converted (taking into 1414 // account rounding and overflow) to the precision of the resulting type. 1415 // Same ranks between signed and unsigned types are resolved earlier, so both 1416 // types are either signed or both unsigned at this point. 1417 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1418 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1419 1420 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1421 1422 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1423 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1424 1425 return ResultTy; 1426 } 1427 1428 /// Check that the usual arithmetic conversions can be performed on this pair of 1429 /// expressions that might be of enumeration type. 1430 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1431 SourceLocation Loc, 1432 Sema::ArithConvKind ACK) { 1433 // C++2a [expr.arith.conv]p1: 1434 // If one operand is of enumeration type and the other operand is of a 1435 // different enumeration type or a floating-point type, this behavior is 1436 // deprecated ([depr.arith.conv.enum]). 1437 // 1438 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1439 // Eventually we will presumably reject these cases (in C++23 onwards?). 1440 QualType L = LHS->getType(), R = RHS->getType(); 1441 bool LEnum = L->isUnscopedEnumerationType(), 1442 REnum = R->isUnscopedEnumerationType(); 1443 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1444 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1445 (REnum && L->isFloatingType())) { 1446 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1447 ? diag::warn_arith_conv_enum_float_cxx20 1448 : diag::warn_arith_conv_enum_float) 1449 << LHS->getSourceRange() << RHS->getSourceRange() 1450 << (int)ACK << LEnum << L << R; 1451 } else if (!IsCompAssign && LEnum && REnum && 1452 !S.Context.hasSameUnqualifiedType(L, R)) { 1453 unsigned DiagID; 1454 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1455 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1456 // If either enumeration type is unnamed, it's less likely that the 1457 // user cares about this, but this situation is still deprecated in 1458 // C++2a. Use a different warning group. 1459 DiagID = S.getLangOpts().CPlusPlus20 1460 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1461 : diag::warn_arith_conv_mixed_anon_enum_types; 1462 } else if (ACK == Sema::ACK_Conditional) { 1463 // Conditional expressions are separated out because they have 1464 // historically had a different warning flag. 1465 DiagID = S.getLangOpts().CPlusPlus20 1466 ? diag::warn_conditional_mixed_enum_types_cxx20 1467 : diag::warn_conditional_mixed_enum_types; 1468 } else if (ACK == Sema::ACK_Comparison) { 1469 // Comparison expressions are separated out because they have 1470 // historically had a different warning flag. 1471 DiagID = S.getLangOpts().CPlusPlus20 1472 ? diag::warn_comparison_mixed_enum_types_cxx20 1473 : diag::warn_comparison_mixed_enum_types; 1474 } else { 1475 DiagID = S.getLangOpts().CPlusPlus20 1476 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1477 : diag::warn_arith_conv_mixed_enum_types; 1478 } 1479 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1480 << (int)ACK << L << R; 1481 } 1482 } 1483 1484 /// UsualArithmeticConversions - Performs various conversions that are common to 1485 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1486 /// routine returns the first non-arithmetic type found. The client is 1487 /// responsible for emitting appropriate error diagnostics. 1488 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1489 SourceLocation Loc, 1490 ArithConvKind ACK) { 1491 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1492 1493 if (ACK != ACK_CompAssign) { 1494 LHS = UsualUnaryConversions(LHS.get()); 1495 if (LHS.isInvalid()) 1496 return QualType(); 1497 } 1498 1499 RHS = UsualUnaryConversions(RHS.get()); 1500 if (RHS.isInvalid()) 1501 return QualType(); 1502 1503 // For conversion purposes, we ignore any qualifiers. 1504 // For example, "const float" and "float" are equivalent. 1505 QualType LHSType = 1506 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1507 QualType RHSType = 1508 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1509 1510 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1511 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1512 LHSType = AtomicLHS->getValueType(); 1513 1514 // If both types are identical, no conversion is needed. 1515 if (LHSType == RHSType) 1516 return LHSType; 1517 1518 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1519 // The caller can deal with this (e.g. pointer + int). 1520 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1521 return QualType(); 1522 1523 // Apply unary and bitfield promotions to the LHS's type. 1524 QualType LHSUnpromotedType = LHSType; 1525 if (LHSType->isPromotableIntegerType()) 1526 LHSType = Context.getPromotedIntegerType(LHSType); 1527 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1528 if (!LHSBitfieldPromoteTy.isNull()) 1529 LHSType = LHSBitfieldPromoteTy; 1530 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1531 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1532 1533 // If both types are identical, no conversion is needed. 1534 if (LHSType == RHSType) 1535 return LHSType; 1536 1537 // At this point, we have two different arithmetic types. 1538 1539 // Diagnose attempts to convert between __ibm128, __float128 and long double 1540 // where such conversions currently can't be handled. 1541 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1542 return QualType(); 1543 1544 // Handle complex types first (C99 6.3.1.8p1). 1545 if (LHSType->isComplexType() || RHSType->isComplexType()) 1546 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1547 ACK == ACK_CompAssign); 1548 1549 // Now handle "real" floating types (i.e. float, double, long double). 1550 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1551 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1552 ACK == ACK_CompAssign); 1553 1554 // Handle GCC complex int extension. 1555 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1556 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1557 ACK == ACK_CompAssign); 1558 1559 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1560 return handleFixedPointConversion(*this, LHSType, RHSType); 1561 1562 // Finally, we have two differing integer types. 1563 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1564 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1565 } 1566 1567 //===----------------------------------------------------------------------===// 1568 // Semantic Analysis for various Expression Types 1569 //===----------------------------------------------------------------------===// 1570 1571 1572 ExprResult 1573 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1574 SourceLocation DefaultLoc, 1575 SourceLocation RParenLoc, 1576 Expr *ControllingExpr, 1577 ArrayRef<ParsedType> ArgTypes, 1578 ArrayRef<Expr *> ArgExprs) { 1579 unsigned NumAssocs = ArgTypes.size(); 1580 assert(NumAssocs == ArgExprs.size()); 1581 1582 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1583 for (unsigned i = 0; i < NumAssocs; ++i) { 1584 if (ArgTypes[i]) 1585 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1586 else 1587 Types[i] = nullptr; 1588 } 1589 1590 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1591 ControllingExpr, 1592 llvm::makeArrayRef(Types, NumAssocs), 1593 ArgExprs); 1594 delete [] Types; 1595 return ER; 1596 } 1597 1598 ExprResult 1599 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1600 SourceLocation DefaultLoc, 1601 SourceLocation RParenLoc, 1602 Expr *ControllingExpr, 1603 ArrayRef<TypeSourceInfo *> Types, 1604 ArrayRef<Expr *> Exprs) { 1605 unsigned NumAssocs = Types.size(); 1606 assert(NumAssocs == Exprs.size()); 1607 1608 // Decay and strip qualifiers for the controlling expression type, and handle 1609 // placeholder type replacement. See committee discussion from WG14 DR423. 1610 { 1611 EnterExpressionEvaluationContext Unevaluated( 1612 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1613 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1614 if (R.isInvalid()) 1615 return ExprError(); 1616 ControllingExpr = R.get(); 1617 } 1618 1619 // The controlling expression is an unevaluated operand, so side effects are 1620 // likely unintended. 1621 if (!inTemplateInstantiation() && 1622 ControllingExpr->HasSideEffects(Context, false)) 1623 Diag(ControllingExpr->getExprLoc(), 1624 diag::warn_side_effects_unevaluated_context); 1625 1626 bool TypeErrorFound = false, 1627 IsResultDependent = ControllingExpr->isTypeDependent(), 1628 ContainsUnexpandedParameterPack 1629 = ControllingExpr->containsUnexpandedParameterPack(); 1630 1631 for (unsigned i = 0; i < NumAssocs; ++i) { 1632 if (Exprs[i]->containsUnexpandedParameterPack()) 1633 ContainsUnexpandedParameterPack = true; 1634 1635 if (Types[i]) { 1636 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1637 ContainsUnexpandedParameterPack = true; 1638 1639 if (Types[i]->getType()->isDependentType()) { 1640 IsResultDependent = true; 1641 } else { 1642 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1643 // complete object type other than a variably modified type." 1644 unsigned D = 0; 1645 if (Types[i]->getType()->isIncompleteType()) 1646 D = diag::err_assoc_type_incomplete; 1647 else if (!Types[i]->getType()->isObjectType()) 1648 D = diag::err_assoc_type_nonobject; 1649 else if (Types[i]->getType()->isVariablyModifiedType()) 1650 D = diag::err_assoc_type_variably_modified; 1651 1652 if (D != 0) { 1653 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1654 << Types[i]->getTypeLoc().getSourceRange() 1655 << Types[i]->getType(); 1656 TypeErrorFound = true; 1657 } 1658 1659 // C11 6.5.1.1p2 "No two generic associations in the same generic 1660 // selection shall specify compatible types." 1661 for (unsigned j = i+1; j < NumAssocs; ++j) 1662 if (Types[j] && !Types[j]->getType()->isDependentType() && 1663 Context.typesAreCompatible(Types[i]->getType(), 1664 Types[j]->getType())) { 1665 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1666 diag::err_assoc_compatible_types) 1667 << Types[j]->getTypeLoc().getSourceRange() 1668 << Types[j]->getType() 1669 << Types[i]->getType(); 1670 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1671 diag::note_compat_assoc) 1672 << Types[i]->getTypeLoc().getSourceRange() 1673 << Types[i]->getType(); 1674 TypeErrorFound = true; 1675 } 1676 } 1677 } 1678 } 1679 if (TypeErrorFound) 1680 return ExprError(); 1681 1682 // If we determined that the generic selection is result-dependent, don't 1683 // try to compute the result expression. 1684 if (IsResultDependent) 1685 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1686 Exprs, DefaultLoc, RParenLoc, 1687 ContainsUnexpandedParameterPack); 1688 1689 SmallVector<unsigned, 1> CompatIndices; 1690 unsigned DefaultIndex = -1U; 1691 for (unsigned i = 0; i < NumAssocs; ++i) { 1692 if (!Types[i]) 1693 DefaultIndex = i; 1694 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1695 Types[i]->getType())) 1696 CompatIndices.push_back(i); 1697 } 1698 1699 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1700 // type compatible with at most one of the types named in its generic 1701 // association list." 1702 if (CompatIndices.size() > 1) { 1703 // We strip parens here because the controlling expression is typically 1704 // parenthesized in macro definitions. 1705 ControllingExpr = ControllingExpr->IgnoreParens(); 1706 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1707 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1708 << (unsigned)CompatIndices.size(); 1709 for (unsigned I : CompatIndices) { 1710 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1711 diag::note_compat_assoc) 1712 << Types[I]->getTypeLoc().getSourceRange() 1713 << Types[I]->getType(); 1714 } 1715 return ExprError(); 1716 } 1717 1718 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1719 // its controlling expression shall have type compatible with exactly one of 1720 // the types named in its generic association list." 1721 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1722 // We strip parens here because the controlling expression is typically 1723 // parenthesized in macro definitions. 1724 ControllingExpr = ControllingExpr->IgnoreParens(); 1725 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1726 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1727 return ExprError(); 1728 } 1729 1730 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1731 // type name that is compatible with the type of the controlling expression, 1732 // then the result expression of the generic selection is the expression 1733 // in that generic association. Otherwise, the result expression of the 1734 // generic selection is the expression in the default generic association." 1735 unsigned ResultIndex = 1736 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1737 1738 return GenericSelectionExpr::Create( 1739 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1740 ContainsUnexpandedParameterPack, ResultIndex); 1741 } 1742 1743 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1744 /// location of the token and the offset of the ud-suffix within it. 1745 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1746 unsigned Offset) { 1747 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1748 S.getLangOpts()); 1749 } 1750 1751 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1752 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1753 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1754 IdentifierInfo *UDSuffix, 1755 SourceLocation UDSuffixLoc, 1756 ArrayRef<Expr*> Args, 1757 SourceLocation LitEndLoc) { 1758 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1759 1760 QualType ArgTy[2]; 1761 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1762 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1763 if (ArgTy[ArgIdx]->isArrayType()) 1764 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1765 } 1766 1767 DeclarationName OpName = 1768 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1769 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1770 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1771 1772 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1773 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1774 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1775 /*AllowStringTemplatePack*/ false, 1776 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1777 return ExprError(); 1778 1779 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1780 } 1781 1782 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1783 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1784 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1785 /// multiple tokens. However, the common case is that StringToks points to one 1786 /// string. 1787 /// 1788 ExprResult 1789 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1790 assert(!StringToks.empty() && "Must have at least one string!"); 1791 1792 StringLiteralParser Literal(StringToks, PP); 1793 if (Literal.hadError) 1794 return ExprError(); 1795 1796 SmallVector<SourceLocation, 4> StringTokLocs; 1797 for (const Token &Tok : StringToks) 1798 StringTokLocs.push_back(Tok.getLocation()); 1799 1800 QualType CharTy = Context.CharTy; 1801 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1802 if (Literal.isWide()) { 1803 CharTy = Context.getWideCharType(); 1804 Kind = StringLiteral::Wide; 1805 } else if (Literal.isUTF8()) { 1806 if (getLangOpts().Char8) 1807 CharTy = Context.Char8Ty; 1808 Kind = StringLiteral::UTF8; 1809 } else if (Literal.isUTF16()) { 1810 CharTy = Context.Char16Ty; 1811 Kind = StringLiteral::UTF16; 1812 } else if (Literal.isUTF32()) { 1813 CharTy = Context.Char32Ty; 1814 Kind = StringLiteral::UTF32; 1815 } else if (Literal.isPascal()) { 1816 CharTy = Context.UnsignedCharTy; 1817 } 1818 1819 // Warn on initializing an array of char from a u8 string literal; this 1820 // becomes ill-formed in C++2a. 1821 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1822 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1823 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1824 1825 // Create removals for all 'u8' prefixes in the string literal(s). This 1826 // ensures C++2a compatibility (but may change the program behavior when 1827 // built by non-Clang compilers for which the execution character set is 1828 // not always UTF-8). 1829 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1830 SourceLocation RemovalDiagLoc; 1831 for (const Token &Tok : StringToks) { 1832 if (Tok.getKind() == tok::utf8_string_literal) { 1833 if (RemovalDiagLoc.isInvalid()) 1834 RemovalDiagLoc = Tok.getLocation(); 1835 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1836 Tok.getLocation(), 1837 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1838 getSourceManager(), getLangOpts()))); 1839 } 1840 } 1841 Diag(RemovalDiagLoc, RemovalDiag); 1842 } 1843 1844 QualType StrTy = 1845 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1846 1847 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1848 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1849 Kind, Literal.Pascal, StrTy, 1850 &StringTokLocs[0], 1851 StringTokLocs.size()); 1852 if (Literal.getUDSuffix().empty()) 1853 return Lit; 1854 1855 // We're building a user-defined literal. 1856 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1857 SourceLocation UDSuffixLoc = 1858 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1859 Literal.getUDSuffixOffset()); 1860 1861 // Make sure we're allowed user-defined literals here. 1862 if (!UDLScope) 1863 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1864 1865 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1866 // operator "" X (str, len) 1867 QualType SizeType = Context.getSizeType(); 1868 1869 DeclarationName OpName = 1870 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1871 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1872 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1873 1874 QualType ArgTy[] = { 1875 Context.getArrayDecayedType(StrTy), SizeType 1876 }; 1877 1878 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1879 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1880 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1881 /*AllowStringTemplatePack*/ true, 1882 /*DiagnoseMissing*/ true, Lit)) { 1883 1884 case LOLR_Cooked: { 1885 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1886 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1887 StringTokLocs[0]); 1888 Expr *Args[] = { Lit, LenArg }; 1889 1890 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1891 } 1892 1893 case LOLR_Template: { 1894 TemplateArgumentListInfo ExplicitArgs; 1895 TemplateArgument Arg(Lit); 1896 TemplateArgumentLocInfo ArgInfo(Lit); 1897 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1898 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1899 &ExplicitArgs); 1900 } 1901 1902 case LOLR_StringTemplatePack: { 1903 TemplateArgumentListInfo ExplicitArgs; 1904 1905 unsigned CharBits = Context.getIntWidth(CharTy); 1906 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1907 llvm::APSInt Value(CharBits, CharIsUnsigned); 1908 1909 TemplateArgument TypeArg(CharTy); 1910 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1911 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1912 1913 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1914 Value = Lit->getCodeUnit(I); 1915 TemplateArgument Arg(Context, Value, CharTy); 1916 TemplateArgumentLocInfo ArgInfo; 1917 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1918 } 1919 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1920 &ExplicitArgs); 1921 } 1922 case LOLR_Raw: 1923 case LOLR_ErrorNoDiagnostic: 1924 llvm_unreachable("unexpected literal operator lookup result"); 1925 case LOLR_Error: 1926 return ExprError(); 1927 } 1928 llvm_unreachable("unexpected literal operator lookup result"); 1929 } 1930 1931 DeclRefExpr * 1932 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1933 SourceLocation Loc, 1934 const CXXScopeSpec *SS) { 1935 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1936 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1937 } 1938 1939 DeclRefExpr * 1940 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1941 const DeclarationNameInfo &NameInfo, 1942 const CXXScopeSpec *SS, NamedDecl *FoundD, 1943 SourceLocation TemplateKWLoc, 1944 const TemplateArgumentListInfo *TemplateArgs) { 1945 NestedNameSpecifierLoc NNS = 1946 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1947 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1948 TemplateArgs); 1949 } 1950 1951 // CUDA/HIP: Check whether a captured reference variable is referencing a 1952 // host variable in a device or host device lambda. 1953 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1954 VarDecl *VD) { 1955 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1956 return false; 1957 assert(VD->getType()->isReferenceType()); 1958 1959 // Check whether the reference variable is referencing a host variable. 1960 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1961 if (!DRE) 1962 return false; 1963 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 1964 if (!Referee || !Referee->hasGlobalStorage() || 1965 Referee->hasAttr<CUDADeviceAttr>()) 1966 return false; 1967 1968 // Check whether the current function is a device or host device lambda. 1969 // Check whether the reference variable is a capture by getDeclContext() 1970 // since refersToEnclosingVariableOrCapture() is not ready at this point. 1971 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 1972 if (MD && MD->getParent()->isLambda() && 1973 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 1974 VD->getDeclContext() != MD) 1975 return true; 1976 1977 return false; 1978 } 1979 1980 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1981 // A declaration named in an unevaluated operand never constitutes an odr-use. 1982 if (isUnevaluatedContext()) 1983 return NOUR_Unevaluated; 1984 1985 // C++2a [basic.def.odr]p4: 1986 // A variable x whose name appears as a potentially-evaluated expression e 1987 // is odr-used by e unless [...] x is a reference that is usable in 1988 // constant expressions. 1989 // CUDA/HIP: 1990 // If a reference variable referencing a host variable is captured in a 1991 // device or host device lambda, the value of the referee must be copied 1992 // to the capture and the reference variable must be treated as odr-use 1993 // since the value of the referee is not known at compile time and must 1994 // be loaded from the captured. 1995 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1996 if (VD->getType()->isReferenceType() && 1997 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1998 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 1999 VD->isUsableInConstantExpressions(Context)) 2000 return NOUR_Constant; 2001 } 2002 2003 // All remaining non-variable cases constitute an odr-use. For variables, we 2004 // need to wait and see how the expression is used. 2005 return NOUR_None; 2006 } 2007 2008 /// BuildDeclRefExpr - Build an expression that references a 2009 /// declaration that does not require a closure capture. 2010 DeclRefExpr * 2011 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2012 const DeclarationNameInfo &NameInfo, 2013 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2014 SourceLocation TemplateKWLoc, 2015 const TemplateArgumentListInfo *TemplateArgs) { 2016 bool RefersToCapturedVariable = 2017 isa<VarDecl>(D) && 2018 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2019 2020 DeclRefExpr *E = DeclRefExpr::Create( 2021 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2022 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2023 MarkDeclRefReferenced(E); 2024 2025 // C++ [except.spec]p17: 2026 // An exception-specification is considered to be needed when: 2027 // - in an expression, the function is the unique lookup result or 2028 // the selected member of a set of overloaded functions. 2029 // 2030 // We delay doing this until after we've built the function reference and 2031 // marked it as used so that: 2032 // a) if the function is defaulted, we get errors from defining it before / 2033 // instead of errors from computing its exception specification, and 2034 // b) if the function is a defaulted comparison, we can use the body we 2035 // build when defining it as input to the exception specification 2036 // computation rather than computing a new body. 2037 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2038 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2039 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2040 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2041 } 2042 } 2043 2044 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2045 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2046 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2047 getCurFunction()->recordUseOfWeak(E); 2048 2049 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2050 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2051 FD = IFD->getAnonField(); 2052 if (FD) { 2053 UnusedPrivateFields.remove(FD); 2054 // Just in case we're building an illegal pointer-to-member. 2055 if (FD->isBitField()) 2056 E->setObjectKind(OK_BitField); 2057 } 2058 2059 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2060 // designates a bit-field. 2061 if (auto *BD = dyn_cast<BindingDecl>(D)) 2062 if (auto *BE = BD->getBinding()) 2063 E->setObjectKind(BE->getObjectKind()); 2064 2065 return E; 2066 } 2067 2068 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2069 /// possibly a list of template arguments. 2070 /// 2071 /// If this produces template arguments, it is permitted to call 2072 /// DecomposeTemplateName. 2073 /// 2074 /// This actually loses a lot of source location information for 2075 /// non-standard name kinds; we should consider preserving that in 2076 /// some way. 2077 void 2078 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2079 TemplateArgumentListInfo &Buffer, 2080 DeclarationNameInfo &NameInfo, 2081 const TemplateArgumentListInfo *&TemplateArgs) { 2082 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2083 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2084 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2085 2086 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2087 Id.TemplateId->NumArgs); 2088 translateTemplateArguments(TemplateArgsPtr, Buffer); 2089 2090 TemplateName TName = Id.TemplateId->Template.get(); 2091 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2092 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2093 TemplateArgs = &Buffer; 2094 } else { 2095 NameInfo = GetNameFromUnqualifiedId(Id); 2096 TemplateArgs = nullptr; 2097 } 2098 } 2099 2100 static void emitEmptyLookupTypoDiagnostic( 2101 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2102 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2103 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2104 DeclContext *Ctx = 2105 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2106 if (!TC) { 2107 // Emit a special diagnostic for failed member lookups. 2108 // FIXME: computing the declaration context might fail here (?) 2109 if (Ctx) 2110 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2111 << SS.getRange(); 2112 else 2113 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2114 return; 2115 } 2116 2117 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2118 bool DroppedSpecifier = 2119 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2120 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2121 ? diag::note_implicit_param_decl 2122 : diag::note_previous_decl; 2123 if (!Ctx) 2124 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2125 SemaRef.PDiag(NoteID)); 2126 else 2127 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2128 << Typo << Ctx << DroppedSpecifier 2129 << SS.getRange(), 2130 SemaRef.PDiag(NoteID)); 2131 } 2132 2133 /// Diagnose a lookup that found results in an enclosing class during error 2134 /// recovery. This usually indicates that the results were found in a dependent 2135 /// base class that could not be searched as part of a template definition. 2136 /// Always issues a diagnostic (though this may be only a warning in MS 2137 /// compatibility mode). 2138 /// 2139 /// Return \c true if the error is unrecoverable, or \c false if the caller 2140 /// should attempt to recover using these lookup results. 2141 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2142 // During a default argument instantiation the CurContext points 2143 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2144 // function parameter list, hence add an explicit check. 2145 bool isDefaultArgument = 2146 !CodeSynthesisContexts.empty() && 2147 CodeSynthesisContexts.back().Kind == 2148 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2149 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2150 bool isInstance = CurMethod && CurMethod->isInstance() && 2151 R.getNamingClass() == CurMethod->getParent() && 2152 !isDefaultArgument; 2153 2154 // There are two ways we can find a class-scope declaration during template 2155 // instantiation that we did not find in the template definition: if it is a 2156 // member of a dependent base class, or if it is declared after the point of 2157 // use in the same class. Distinguish these by comparing the class in which 2158 // the member was found to the naming class of the lookup. 2159 unsigned DiagID = diag::err_found_in_dependent_base; 2160 unsigned NoteID = diag::note_member_declared_at; 2161 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2162 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2163 : diag::err_found_later_in_class; 2164 } else if (getLangOpts().MSVCCompat) { 2165 DiagID = diag::ext_found_in_dependent_base; 2166 NoteID = diag::note_dependent_member_use; 2167 } 2168 2169 if (isInstance) { 2170 // Give a code modification hint to insert 'this->'. 2171 Diag(R.getNameLoc(), DiagID) 2172 << R.getLookupName() 2173 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2174 CheckCXXThisCapture(R.getNameLoc()); 2175 } else { 2176 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2177 // they're not shadowed). 2178 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2179 } 2180 2181 for (NamedDecl *D : R) 2182 Diag(D->getLocation(), NoteID); 2183 2184 // Return true if we are inside a default argument instantiation 2185 // and the found name refers to an instance member function, otherwise 2186 // the caller will try to create an implicit member call and this is wrong 2187 // for default arguments. 2188 // 2189 // FIXME: Is this special case necessary? We could allow the caller to 2190 // diagnose this. 2191 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2192 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2193 return true; 2194 } 2195 2196 // Tell the callee to try to recover. 2197 return false; 2198 } 2199 2200 /// Diagnose an empty lookup. 2201 /// 2202 /// \return false if new lookup candidates were found 2203 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2204 CorrectionCandidateCallback &CCC, 2205 TemplateArgumentListInfo *ExplicitTemplateArgs, 2206 ArrayRef<Expr *> Args, TypoExpr **Out) { 2207 DeclarationName Name = R.getLookupName(); 2208 2209 unsigned diagnostic = diag::err_undeclared_var_use; 2210 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2211 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2212 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2213 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2214 diagnostic = diag::err_undeclared_use; 2215 diagnostic_suggest = diag::err_undeclared_use_suggest; 2216 } 2217 2218 // If the original lookup was an unqualified lookup, fake an 2219 // unqualified lookup. This is useful when (for example) the 2220 // original lookup would not have found something because it was a 2221 // dependent name. 2222 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2223 while (DC) { 2224 if (isa<CXXRecordDecl>(DC)) { 2225 LookupQualifiedName(R, DC); 2226 2227 if (!R.empty()) { 2228 // Don't give errors about ambiguities in this lookup. 2229 R.suppressDiagnostics(); 2230 2231 // If there's a best viable function among the results, only mention 2232 // that one in the notes. 2233 OverloadCandidateSet Candidates(R.getNameLoc(), 2234 OverloadCandidateSet::CSK_Normal); 2235 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2236 OverloadCandidateSet::iterator Best; 2237 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2238 OR_Success) { 2239 R.clear(); 2240 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2241 R.resolveKind(); 2242 } 2243 2244 return DiagnoseDependentMemberLookup(R); 2245 } 2246 2247 R.clear(); 2248 } 2249 2250 DC = DC->getLookupParent(); 2251 } 2252 2253 // We didn't find anything, so try to correct for a typo. 2254 TypoCorrection Corrected; 2255 if (S && Out) { 2256 SourceLocation TypoLoc = R.getNameLoc(); 2257 assert(!ExplicitTemplateArgs && 2258 "Diagnosing an empty lookup with explicit template args!"); 2259 *Out = CorrectTypoDelayed( 2260 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2261 [=](const TypoCorrection &TC) { 2262 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2263 diagnostic, diagnostic_suggest); 2264 }, 2265 nullptr, CTK_ErrorRecovery); 2266 if (*Out) 2267 return true; 2268 } else if (S && 2269 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2270 S, &SS, CCC, CTK_ErrorRecovery))) { 2271 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2272 bool DroppedSpecifier = 2273 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2274 R.setLookupName(Corrected.getCorrection()); 2275 2276 bool AcceptableWithRecovery = false; 2277 bool AcceptableWithoutRecovery = false; 2278 NamedDecl *ND = Corrected.getFoundDecl(); 2279 if (ND) { 2280 if (Corrected.isOverloaded()) { 2281 OverloadCandidateSet OCS(R.getNameLoc(), 2282 OverloadCandidateSet::CSK_Normal); 2283 OverloadCandidateSet::iterator Best; 2284 for (NamedDecl *CD : Corrected) { 2285 if (FunctionTemplateDecl *FTD = 2286 dyn_cast<FunctionTemplateDecl>(CD)) 2287 AddTemplateOverloadCandidate( 2288 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2289 Args, OCS); 2290 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2291 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2292 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2293 Args, OCS); 2294 } 2295 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2296 case OR_Success: 2297 ND = Best->FoundDecl; 2298 Corrected.setCorrectionDecl(ND); 2299 break; 2300 default: 2301 // FIXME: Arbitrarily pick the first declaration for the note. 2302 Corrected.setCorrectionDecl(ND); 2303 break; 2304 } 2305 } 2306 R.addDecl(ND); 2307 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2308 CXXRecordDecl *Record = nullptr; 2309 if (Corrected.getCorrectionSpecifier()) { 2310 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2311 Record = Ty->getAsCXXRecordDecl(); 2312 } 2313 if (!Record) 2314 Record = cast<CXXRecordDecl>( 2315 ND->getDeclContext()->getRedeclContext()); 2316 R.setNamingClass(Record); 2317 } 2318 2319 auto *UnderlyingND = ND->getUnderlyingDecl(); 2320 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2321 isa<FunctionTemplateDecl>(UnderlyingND); 2322 // FIXME: If we ended up with a typo for a type name or 2323 // Objective-C class name, we're in trouble because the parser 2324 // is in the wrong place to recover. Suggest the typo 2325 // correction, but don't make it a fix-it since we're not going 2326 // to recover well anyway. 2327 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2328 getAsTypeTemplateDecl(UnderlyingND) || 2329 isa<ObjCInterfaceDecl>(UnderlyingND); 2330 } else { 2331 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2332 // because we aren't able to recover. 2333 AcceptableWithoutRecovery = true; 2334 } 2335 2336 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2337 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2338 ? diag::note_implicit_param_decl 2339 : diag::note_previous_decl; 2340 if (SS.isEmpty()) 2341 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2342 PDiag(NoteID), AcceptableWithRecovery); 2343 else 2344 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2345 << Name << computeDeclContext(SS, false) 2346 << DroppedSpecifier << SS.getRange(), 2347 PDiag(NoteID), AcceptableWithRecovery); 2348 2349 // Tell the callee whether to try to recover. 2350 return !AcceptableWithRecovery; 2351 } 2352 } 2353 R.clear(); 2354 2355 // Emit a special diagnostic for failed member lookups. 2356 // FIXME: computing the declaration context might fail here (?) 2357 if (!SS.isEmpty()) { 2358 Diag(R.getNameLoc(), diag::err_no_member) 2359 << Name << computeDeclContext(SS, false) 2360 << SS.getRange(); 2361 return true; 2362 } 2363 2364 // Give up, we can't recover. 2365 Diag(R.getNameLoc(), diagnostic) << Name; 2366 return true; 2367 } 2368 2369 /// In Microsoft mode, if we are inside a template class whose parent class has 2370 /// dependent base classes, and we can't resolve an unqualified identifier, then 2371 /// assume the identifier is a member of a dependent base class. We can only 2372 /// recover successfully in static methods, instance methods, and other contexts 2373 /// where 'this' is available. This doesn't precisely match MSVC's 2374 /// instantiation model, but it's close enough. 2375 static Expr * 2376 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2377 DeclarationNameInfo &NameInfo, 2378 SourceLocation TemplateKWLoc, 2379 const TemplateArgumentListInfo *TemplateArgs) { 2380 // Only try to recover from lookup into dependent bases in static methods or 2381 // contexts where 'this' is available. 2382 QualType ThisType = S.getCurrentThisType(); 2383 const CXXRecordDecl *RD = nullptr; 2384 if (!ThisType.isNull()) 2385 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2386 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2387 RD = MD->getParent(); 2388 if (!RD || !RD->hasAnyDependentBases()) 2389 return nullptr; 2390 2391 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2392 // is available, suggest inserting 'this->' as a fixit. 2393 SourceLocation Loc = NameInfo.getLoc(); 2394 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2395 DB << NameInfo.getName() << RD; 2396 2397 if (!ThisType.isNull()) { 2398 DB << FixItHint::CreateInsertion(Loc, "this->"); 2399 return CXXDependentScopeMemberExpr::Create( 2400 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2401 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2402 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2403 } 2404 2405 // Synthesize a fake NNS that points to the derived class. This will 2406 // perform name lookup during template instantiation. 2407 CXXScopeSpec SS; 2408 auto *NNS = 2409 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2410 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2411 return DependentScopeDeclRefExpr::Create( 2412 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2413 TemplateArgs); 2414 } 2415 2416 ExprResult 2417 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2418 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2419 bool HasTrailingLParen, bool IsAddressOfOperand, 2420 CorrectionCandidateCallback *CCC, 2421 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2422 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2423 "cannot be direct & operand and have a trailing lparen"); 2424 if (SS.isInvalid()) 2425 return ExprError(); 2426 2427 TemplateArgumentListInfo TemplateArgsBuffer; 2428 2429 // Decompose the UnqualifiedId into the following data. 2430 DeclarationNameInfo NameInfo; 2431 const TemplateArgumentListInfo *TemplateArgs; 2432 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2433 2434 DeclarationName Name = NameInfo.getName(); 2435 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2436 SourceLocation NameLoc = NameInfo.getLoc(); 2437 2438 if (II && II->isEditorPlaceholder()) { 2439 // FIXME: When typed placeholders are supported we can create a typed 2440 // placeholder expression node. 2441 return ExprError(); 2442 } 2443 2444 // C++ [temp.dep.expr]p3: 2445 // An id-expression is type-dependent if it contains: 2446 // -- an identifier that was declared with a dependent type, 2447 // (note: handled after lookup) 2448 // -- a template-id that is dependent, 2449 // (note: handled in BuildTemplateIdExpr) 2450 // -- a conversion-function-id that specifies a dependent type, 2451 // -- a nested-name-specifier that contains a class-name that 2452 // names a dependent type. 2453 // Determine whether this is a member of an unknown specialization; 2454 // we need to handle these differently. 2455 bool DependentID = false; 2456 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2457 Name.getCXXNameType()->isDependentType()) { 2458 DependentID = true; 2459 } else if (SS.isSet()) { 2460 if (DeclContext *DC = computeDeclContext(SS, false)) { 2461 if (RequireCompleteDeclContext(SS, DC)) 2462 return ExprError(); 2463 } else { 2464 DependentID = true; 2465 } 2466 } 2467 2468 if (DependentID) 2469 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2470 IsAddressOfOperand, TemplateArgs); 2471 2472 // Perform the required lookup. 2473 LookupResult R(*this, NameInfo, 2474 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2475 ? LookupObjCImplicitSelfParam 2476 : LookupOrdinaryName); 2477 if (TemplateKWLoc.isValid() || TemplateArgs) { 2478 // Lookup the template name again to correctly establish the context in 2479 // which it was found. This is really unfortunate as we already did the 2480 // lookup to determine that it was a template name in the first place. If 2481 // this becomes a performance hit, we can work harder to preserve those 2482 // results until we get here but it's likely not worth it. 2483 bool MemberOfUnknownSpecialization; 2484 AssumedTemplateKind AssumedTemplate; 2485 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2486 MemberOfUnknownSpecialization, TemplateKWLoc, 2487 &AssumedTemplate)) 2488 return ExprError(); 2489 2490 if (MemberOfUnknownSpecialization || 2491 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2492 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2493 IsAddressOfOperand, TemplateArgs); 2494 } else { 2495 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2496 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2497 2498 // If the result might be in a dependent base class, this is a dependent 2499 // id-expression. 2500 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2501 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2502 IsAddressOfOperand, TemplateArgs); 2503 2504 // If this reference is in an Objective-C method, then we need to do 2505 // some special Objective-C lookup, too. 2506 if (IvarLookupFollowUp) { 2507 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2508 if (E.isInvalid()) 2509 return ExprError(); 2510 2511 if (Expr *Ex = E.getAs<Expr>()) 2512 return Ex; 2513 } 2514 } 2515 2516 if (R.isAmbiguous()) 2517 return ExprError(); 2518 2519 // This could be an implicitly declared function reference (legal in C90, 2520 // extension in C99, forbidden in C++). 2521 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2522 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2523 if (D) R.addDecl(D); 2524 } 2525 2526 // Determine whether this name might be a candidate for 2527 // argument-dependent lookup. 2528 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2529 2530 if (R.empty() && !ADL) { 2531 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2532 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2533 TemplateKWLoc, TemplateArgs)) 2534 return E; 2535 } 2536 2537 // Don't diagnose an empty lookup for inline assembly. 2538 if (IsInlineAsmIdentifier) 2539 return ExprError(); 2540 2541 // If this name wasn't predeclared and if this is not a function 2542 // call, diagnose the problem. 2543 TypoExpr *TE = nullptr; 2544 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2545 : nullptr); 2546 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2547 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2548 "Typo correction callback misconfigured"); 2549 if (CCC) { 2550 // Make sure the callback knows what the typo being diagnosed is. 2551 CCC->setTypoName(II); 2552 if (SS.isValid()) 2553 CCC->setTypoNNS(SS.getScopeRep()); 2554 } 2555 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2556 // a template name, but we happen to have always already looked up the name 2557 // before we get here if it must be a template name. 2558 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2559 None, &TE)) { 2560 if (TE && KeywordReplacement) { 2561 auto &State = getTypoExprState(TE); 2562 auto BestTC = State.Consumer->getNextCorrection(); 2563 if (BestTC.isKeyword()) { 2564 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2565 if (State.DiagHandler) 2566 State.DiagHandler(BestTC); 2567 KeywordReplacement->startToken(); 2568 KeywordReplacement->setKind(II->getTokenID()); 2569 KeywordReplacement->setIdentifierInfo(II); 2570 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2571 // Clean up the state associated with the TypoExpr, since it has 2572 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2573 clearDelayedTypo(TE); 2574 // Signal that a correction to a keyword was performed by returning a 2575 // valid-but-null ExprResult. 2576 return (Expr*)nullptr; 2577 } 2578 State.Consumer->resetCorrectionStream(); 2579 } 2580 return TE ? TE : ExprError(); 2581 } 2582 2583 assert(!R.empty() && 2584 "DiagnoseEmptyLookup returned false but added no results"); 2585 2586 // If we found an Objective-C instance variable, let 2587 // LookupInObjCMethod build the appropriate expression to 2588 // reference the ivar. 2589 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2590 R.clear(); 2591 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2592 // In a hopelessly buggy code, Objective-C instance variable 2593 // lookup fails and no expression will be built to reference it. 2594 if (!E.isInvalid() && !E.get()) 2595 return ExprError(); 2596 return E; 2597 } 2598 } 2599 2600 // This is guaranteed from this point on. 2601 assert(!R.empty() || ADL); 2602 2603 // Check whether this might be a C++ implicit instance member access. 2604 // C++ [class.mfct.non-static]p3: 2605 // When an id-expression that is not part of a class member access 2606 // syntax and not used to form a pointer to member is used in the 2607 // body of a non-static member function of class X, if name lookup 2608 // resolves the name in the id-expression to a non-static non-type 2609 // member of some class C, the id-expression is transformed into a 2610 // class member access expression using (*this) as the 2611 // postfix-expression to the left of the . operator. 2612 // 2613 // But we don't actually need to do this for '&' operands if R 2614 // resolved to a function or overloaded function set, because the 2615 // expression is ill-formed if it actually works out to be a 2616 // non-static member function: 2617 // 2618 // C++ [expr.ref]p4: 2619 // Otherwise, if E1.E2 refers to a non-static member function. . . 2620 // [t]he expression can be used only as the left-hand operand of a 2621 // member function call. 2622 // 2623 // There are other safeguards against such uses, but it's important 2624 // to get this right here so that we don't end up making a 2625 // spuriously dependent expression if we're inside a dependent 2626 // instance method. 2627 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2628 bool MightBeImplicitMember; 2629 if (!IsAddressOfOperand) 2630 MightBeImplicitMember = true; 2631 else if (!SS.isEmpty()) 2632 MightBeImplicitMember = false; 2633 else if (R.isOverloadedResult()) 2634 MightBeImplicitMember = false; 2635 else if (R.isUnresolvableResult()) 2636 MightBeImplicitMember = true; 2637 else 2638 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2639 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2640 isa<MSPropertyDecl>(R.getFoundDecl()); 2641 2642 if (MightBeImplicitMember) 2643 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2644 R, TemplateArgs, S); 2645 } 2646 2647 if (TemplateArgs || TemplateKWLoc.isValid()) { 2648 2649 // In C++1y, if this is a variable template id, then check it 2650 // in BuildTemplateIdExpr(). 2651 // The single lookup result must be a variable template declaration. 2652 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2653 Id.TemplateId->Kind == TNK_Var_template) { 2654 assert(R.getAsSingle<VarTemplateDecl>() && 2655 "There should only be one declaration found."); 2656 } 2657 2658 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2659 } 2660 2661 return BuildDeclarationNameExpr(SS, R, ADL); 2662 } 2663 2664 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2665 /// declaration name, generally during template instantiation. 2666 /// There's a large number of things which don't need to be done along 2667 /// this path. 2668 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2669 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2670 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2671 DeclContext *DC = computeDeclContext(SS, false); 2672 if (!DC) 2673 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2674 NameInfo, /*TemplateArgs=*/nullptr); 2675 2676 if (RequireCompleteDeclContext(SS, DC)) 2677 return ExprError(); 2678 2679 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2680 LookupQualifiedName(R, DC); 2681 2682 if (R.isAmbiguous()) 2683 return ExprError(); 2684 2685 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2686 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2687 NameInfo, /*TemplateArgs=*/nullptr); 2688 2689 if (R.empty()) { 2690 // Don't diagnose problems with invalid record decl, the secondary no_member 2691 // diagnostic during template instantiation is likely bogus, e.g. if a class 2692 // is invalid because it's derived from an invalid base class, then missing 2693 // members were likely supposed to be inherited. 2694 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2695 if (CD->isInvalidDecl()) 2696 return ExprError(); 2697 Diag(NameInfo.getLoc(), diag::err_no_member) 2698 << NameInfo.getName() << DC << SS.getRange(); 2699 return ExprError(); 2700 } 2701 2702 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2703 // Diagnose a missing typename if this resolved unambiguously to a type in 2704 // a dependent context. If we can recover with a type, downgrade this to 2705 // a warning in Microsoft compatibility mode. 2706 unsigned DiagID = diag::err_typename_missing; 2707 if (RecoveryTSI && getLangOpts().MSVCCompat) 2708 DiagID = diag::ext_typename_missing; 2709 SourceLocation Loc = SS.getBeginLoc(); 2710 auto D = Diag(Loc, DiagID); 2711 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2712 << SourceRange(Loc, NameInfo.getEndLoc()); 2713 2714 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2715 // context. 2716 if (!RecoveryTSI) 2717 return ExprError(); 2718 2719 // Only issue the fixit if we're prepared to recover. 2720 D << FixItHint::CreateInsertion(Loc, "typename "); 2721 2722 // Recover by pretending this was an elaborated type. 2723 QualType Ty = Context.getTypeDeclType(TD); 2724 TypeLocBuilder TLB; 2725 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2726 2727 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2728 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2729 QTL.setElaboratedKeywordLoc(SourceLocation()); 2730 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2731 2732 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2733 2734 return ExprEmpty(); 2735 } 2736 2737 // Defend against this resolving to an implicit member access. We usually 2738 // won't get here if this might be a legitimate a class member (we end up in 2739 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2740 // a pointer-to-member or in an unevaluated context in C++11. 2741 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2742 return BuildPossibleImplicitMemberExpr(SS, 2743 /*TemplateKWLoc=*/SourceLocation(), 2744 R, /*TemplateArgs=*/nullptr, S); 2745 2746 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2747 } 2748 2749 /// The parser has read a name in, and Sema has detected that we're currently 2750 /// inside an ObjC method. Perform some additional checks and determine if we 2751 /// should form a reference to an ivar. 2752 /// 2753 /// Ideally, most of this would be done by lookup, but there's 2754 /// actually quite a lot of extra work involved. 2755 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2756 IdentifierInfo *II) { 2757 SourceLocation Loc = Lookup.getNameLoc(); 2758 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2759 2760 // Check for error condition which is already reported. 2761 if (!CurMethod) 2762 return DeclResult(true); 2763 2764 // There are two cases to handle here. 1) scoped lookup could have failed, 2765 // in which case we should look for an ivar. 2) scoped lookup could have 2766 // found a decl, but that decl is outside the current instance method (i.e. 2767 // a global variable). In these two cases, we do a lookup for an ivar with 2768 // this name, if the lookup sucedes, we replace it our current decl. 2769 2770 // If we're in a class method, we don't normally want to look for 2771 // ivars. But if we don't find anything else, and there's an 2772 // ivar, that's an error. 2773 bool IsClassMethod = CurMethod->isClassMethod(); 2774 2775 bool LookForIvars; 2776 if (Lookup.empty()) 2777 LookForIvars = true; 2778 else if (IsClassMethod) 2779 LookForIvars = false; 2780 else 2781 LookForIvars = (Lookup.isSingleResult() && 2782 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2783 ObjCInterfaceDecl *IFace = nullptr; 2784 if (LookForIvars) { 2785 IFace = CurMethod->getClassInterface(); 2786 ObjCInterfaceDecl *ClassDeclared; 2787 ObjCIvarDecl *IV = nullptr; 2788 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2789 // Diagnose using an ivar in a class method. 2790 if (IsClassMethod) { 2791 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2792 return DeclResult(true); 2793 } 2794 2795 // Diagnose the use of an ivar outside of the declaring class. 2796 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2797 !declaresSameEntity(ClassDeclared, IFace) && 2798 !getLangOpts().DebuggerSupport) 2799 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2800 2801 // Success. 2802 return IV; 2803 } 2804 } else if (CurMethod->isInstanceMethod()) { 2805 // We should warn if a local variable hides an ivar. 2806 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2807 ObjCInterfaceDecl *ClassDeclared; 2808 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2809 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2810 declaresSameEntity(IFace, ClassDeclared)) 2811 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2812 } 2813 } 2814 } else if (Lookup.isSingleResult() && 2815 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2816 // If accessing a stand-alone ivar in a class method, this is an error. 2817 if (const ObjCIvarDecl *IV = 2818 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2819 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2820 return DeclResult(true); 2821 } 2822 } 2823 2824 // Didn't encounter an error, didn't find an ivar. 2825 return DeclResult(false); 2826 } 2827 2828 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2829 ObjCIvarDecl *IV) { 2830 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2831 assert(CurMethod && CurMethod->isInstanceMethod() && 2832 "should not reference ivar from this context"); 2833 2834 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2835 assert(IFace && "should not reference ivar from this context"); 2836 2837 // If we're referencing an invalid decl, just return this as a silent 2838 // error node. The error diagnostic was already emitted on the decl. 2839 if (IV->isInvalidDecl()) 2840 return ExprError(); 2841 2842 // Check if referencing a field with __attribute__((deprecated)). 2843 if (DiagnoseUseOfDecl(IV, Loc)) 2844 return ExprError(); 2845 2846 // FIXME: This should use a new expr for a direct reference, don't 2847 // turn this into Self->ivar, just return a BareIVarExpr or something. 2848 IdentifierInfo &II = Context.Idents.get("self"); 2849 UnqualifiedId SelfName; 2850 SelfName.setImplicitSelfParam(&II); 2851 CXXScopeSpec SelfScopeSpec; 2852 SourceLocation TemplateKWLoc; 2853 ExprResult SelfExpr = 2854 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2855 /*HasTrailingLParen=*/false, 2856 /*IsAddressOfOperand=*/false); 2857 if (SelfExpr.isInvalid()) 2858 return ExprError(); 2859 2860 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2861 if (SelfExpr.isInvalid()) 2862 return ExprError(); 2863 2864 MarkAnyDeclReferenced(Loc, IV, true); 2865 2866 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2867 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2868 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2869 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2870 2871 ObjCIvarRefExpr *Result = new (Context) 2872 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2873 IV->getLocation(), SelfExpr.get(), true, true); 2874 2875 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2876 if (!isUnevaluatedContext() && 2877 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2878 getCurFunction()->recordUseOfWeak(Result); 2879 } 2880 if (getLangOpts().ObjCAutoRefCount) 2881 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2882 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2883 2884 return Result; 2885 } 2886 2887 /// The parser has read a name in, and Sema has detected that we're currently 2888 /// inside an ObjC method. Perform some additional checks and determine if we 2889 /// should form a reference to an ivar. If so, build an expression referencing 2890 /// that ivar. 2891 ExprResult 2892 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2893 IdentifierInfo *II, bool AllowBuiltinCreation) { 2894 // FIXME: Integrate this lookup step into LookupParsedName. 2895 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2896 if (Ivar.isInvalid()) 2897 return ExprError(); 2898 if (Ivar.isUsable()) 2899 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2900 cast<ObjCIvarDecl>(Ivar.get())); 2901 2902 if (Lookup.empty() && II && AllowBuiltinCreation) 2903 LookupBuiltin(Lookup); 2904 2905 // Sentinel value saying that we didn't do anything special. 2906 return ExprResult(false); 2907 } 2908 2909 /// Cast a base object to a member's actual type. 2910 /// 2911 /// There are two relevant checks: 2912 /// 2913 /// C++ [class.access.base]p7: 2914 /// 2915 /// If a class member access operator [...] is used to access a non-static 2916 /// data member or non-static member function, the reference is ill-formed if 2917 /// the left operand [...] cannot be implicitly converted to a pointer to the 2918 /// naming class of the right operand. 2919 /// 2920 /// C++ [expr.ref]p7: 2921 /// 2922 /// If E2 is a non-static data member or a non-static member function, the 2923 /// program is ill-formed if the class of which E2 is directly a member is an 2924 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2925 /// 2926 /// Note that the latter check does not consider access; the access of the 2927 /// "real" base class is checked as appropriate when checking the access of the 2928 /// member name. 2929 ExprResult 2930 Sema::PerformObjectMemberConversion(Expr *From, 2931 NestedNameSpecifier *Qualifier, 2932 NamedDecl *FoundDecl, 2933 NamedDecl *Member) { 2934 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2935 if (!RD) 2936 return From; 2937 2938 QualType DestRecordType; 2939 QualType DestType; 2940 QualType FromRecordType; 2941 QualType FromType = From->getType(); 2942 bool PointerConversions = false; 2943 if (isa<FieldDecl>(Member)) { 2944 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2945 auto FromPtrType = FromType->getAs<PointerType>(); 2946 DestRecordType = Context.getAddrSpaceQualType( 2947 DestRecordType, FromPtrType 2948 ? FromType->getPointeeType().getAddressSpace() 2949 : FromType.getAddressSpace()); 2950 2951 if (FromPtrType) { 2952 DestType = Context.getPointerType(DestRecordType); 2953 FromRecordType = FromPtrType->getPointeeType(); 2954 PointerConversions = true; 2955 } else { 2956 DestType = DestRecordType; 2957 FromRecordType = FromType; 2958 } 2959 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2960 if (Method->isStatic()) 2961 return From; 2962 2963 DestType = Method->getThisType(); 2964 DestRecordType = DestType->getPointeeType(); 2965 2966 if (FromType->getAs<PointerType>()) { 2967 FromRecordType = FromType->getPointeeType(); 2968 PointerConversions = true; 2969 } else { 2970 FromRecordType = FromType; 2971 DestType = DestRecordType; 2972 } 2973 2974 LangAS FromAS = FromRecordType.getAddressSpace(); 2975 LangAS DestAS = DestRecordType.getAddressSpace(); 2976 if (FromAS != DestAS) { 2977 QualType FromRecordTypeWithoutAS = 2978 Context.removeAddrSpaceQualType(FromRecordType); 2979 QualType FromTypeWithDestAS = 2980 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2981 if (PointerConversions) 2982 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2983 From = ImpCastExprToType(From, FromTypeWithDestAS, 2984 CK_AddressSpaceConversion, From->getValueKind()) 2985 .get(); 2986 } 2987 } else { 2988 // No conversion necessary. 2989 return From; 2990 } 2991 2992 if (DestType->isDependentType() || FromType->isDependentType()) 2993 return From; 2994 2995 // If the unqualified types are the same, no conversion is necessary. 2996 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2997 return From; 2998 2999 SourceRange FromRange = From->getSourceRange(); 3000 SourceLocation FromLoc = FromRange.getBegin(); 3001 3002 ExprValueKind VK = From->getValueKind(); 3003 3004 // C++ [class.member.lookup]p8: 3005 // [...] Ambiguities can often be resolved by qualifying a name with its 3006 // class name. 3007 // 3008 // If the member was a qualified name and the qualified referred to a 3009 // specific base subobject type, we'll cast to that intermediate type 3010 // first and then to the object in which the member is declared. That allows 3011 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3012 // 3013 // class Base { public: int x; }; 3014 // class Derived1 : public Base { }; 3015 // class Derived2 : public Base { }; 3016 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3017 // 3018 // void VeryDerived::f() { 3019 // x = 17; // error: ambiguous base subobjects 3020 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3021 // } 3022 if (Qualifier && Qualifier->getAsType()) { 3023 QualType QType = QualType(Qualifier->getAsType(), 0); 3024 assert(QType->isRecordType() && "lookup done with non-record type"); 3025 3026 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3027 3028 // In C++98, the qualifier type doesn't actually have to be a base 3029 // type of the object type, in which case we just ignore it. 3030 // Otherwise build the appropriate casts. 3031 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3032 CXXCastPath BasePath; 3033 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3034 FromLoc, FromRange, &BasePath)) 3035 return ExprError(); 3036 3037 if (PointerConversions) 3038 QType = Context.getPointerType(QType); 3039 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3040 VK, &BasePath).get(); 3041 3042 FromType = QType; 3043 FromRecordType = QRecordType; 3044 3045 // If the qualifier type was the same as the destination type, 3046 // we're done. 3047 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3048 return From; 3049 } 3050 } 3051 3052 CXXCastPath BasePath; 3053 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3054 FromLoc, FromRange, &BasePath, 3055 /*IgnoreAccess=*/true)) 3056 return ExprError(); 3057 3058 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3059 VK, &BasePath); 3060 } 3061 3062 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3063 const LookupResult &R, 3064 bool HasTrailingLParen) { 3065 // Only when used directly as the postfix-expression of a call. 3066 if (!HasTrailingLParen) 3067 return false; 3068 3069 // Never if a scope specifier was provided. 3070 if (SS.isSet()) 3071 return false; 3072 3073 // Only in C++ or ObjC++. 3074 if (!getLangOpts().CPlusPlus) 3075 return false; 3076 3077 // Turn off ADL when we find certain kinds of declarations during 3078 // normal lookup: 3079 for (NamedDecl *D : R) { 3080 // C++0x [basic.lookup.argdep]p3: 3081 // -- a declaration of a class member 3082 // Since using decls preserve this property, we check this on the 3083 // original decl. 3084 if (D->isCXXClassMember()) 3085 return false; 3086 3087 // C++0x [basic.lookup.argdep]p3: 3088 // -- a block-scope function declaration that is not a 3089 // using-declaration 3090 // NOTE: we also trigger this for function templates (in fact, we 3091 // don't check the decl type at all, since all other decl types 3092 // turn off ADL anyway). 3093 if (isa<UsingShadowDecl>(D)) 3094 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3095 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3096 return false; 3097 3098 // C++0x [basic.lookup.argdep]p3: 3099 // -- a declaration that is neither a function or a function 3100 // template 3101 // And also for builtin functions. 3102 if (isa<FunctionDecl>(D)) { 3103 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3104 3105 // But also builtin functions. 3106 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3107 return false; 3108 } else if (!isa<FunctionTemplateDecl>(D)) 3109 return false; 3110 } 3111 3112 return true; 3113 } 3114 3115 3116 /// Diagnoses obvious problems with the use of the given declaration 3117 /// as an expression. This is only actually called for lookups that 3118 /// were not overloaded, and it doesn't promise that the declaration 3119 /// will in fact be used. 3120 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3121 if (D->isInvalidDecl()) 3122 return true; 3123 3124 if (isa<TypedefNameDecl>(D)) { 3125 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3126 return true; 3127 } 3128 3129 if (isa<ObjCInterfaceDecl>(D)) { 3130 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3131 return true; 3132 } 3133 3134 if (isa<NamespaceDecl>(D)) { 3135 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3136 return true; 3137 } 3138 3139 return false; 3140 } 3141 3142 // Certain multiversion types should be treated as overloaded even when there is 3143 // only one result. 3144 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3145 assert(R.isSingleResult() && "Expected only a single result"); 3146 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3147 return FD && 3148 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3149 } 3150 3151 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3152 LookupResult &R, bool NeedsADL, 3153 bool AcceptInvalidDecl) { 3154 // If this is a single, fully-resolved result and we don't need ADL, 3155 // just build an ordinary singleton decl ref. 3156 if (!NeedsADL && R.isSingleResult() && 3157 !R.getAsSingle<FunctionTemplateDecl>() && 3158 !ShouldLookupResultBeMultiVersionOverload(R)) 3159 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3160 R.getRepresentativeDecl(), nullptr, 3161 AcceptInvalidDecl); 3162 3163 // We only need to check the declaration if there's exactly one 3164 // result, because in the overloaded case the results can only be 3165 // functions and function templates. 3166 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3167 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3168 return ExprError(); 3169 3170 // Otherwise, just build an unresolved lookup expression. Suppress 3171 // any lookup-related diagnostics; we'll hash these out later, when 3172 // we've picked a target. 3173 R.suppressDiagnostics(); 3174 3175 UnresolvedLookupExpr *ULE 3176 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3177 SS.getWithLocInContext(Context), 3178 R.getLookupNameInfo(), 3179 NeedsADL, R.isOverloadedResult(), 3180 R.begin(), R.end()); 3181 3182 return ULE; 3183 } 3184 3185 static void 3186 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3187 ValueDecl *var, DeclContext *DC); 3188 3189 /// Complete semantic analysis for a reference to the given declaration. 3190 ExprResult Sema::BuildDeclarationNameExpr( 3191 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3192 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3193 bool AcceptInvalidDecl) { 3194 assert(D && "Cannot refer to a NULL declaration"); 3195 assert(!isa<FunctionTemplateDecl>(D) && 3196 "Cannot refer unambiguously to a function template"); 3197 3198 SourceLocation Loc = NameInfo.getLoc(); 3199 if (CheckDeclInExpr(*this, Loc, D)) 3200 return ExprError(); 3201 3202 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3203 // Specifically diagnose references to class templates that are missing 3204 // a template argument list. 3205 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3206 return ExprError(); 3207 } 3208 3209 // Make sure that we're referring to a value. 3210 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { 3211 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange(); 3212 Diag(D->getLocation(), diag::note_declared_at); 3213 return ExprError(); 3214 } 3215 3216 // Check whether this declaration can be used. Note that we suppress 3217 // this check when we're going to perform argument-dependent lookup 3218 // on this function name, because this might not be the function 3219 // that overload resolution actually selects. 3220 if (DiagnoseUseOfDecl(D, Loc)) 3221 return ExprError(); 3222 3223 auto *VD = cast<ValueDecl>(D); 3224 3225 // Only create DeclRefExpr's for valid Decl's. 3226 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3227 return ExprError(); 3228 3229 // Handle members of anonymous structs and unions. If we got here, 3230 // and the reference is to a class member indirect field, then this 3231 // must be the subject of a pointer-to-member expression. 3232 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3233 if (!indirectField->isCXXClassMember()) 3234 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3235 indirectField); 3236 3237 QualType type = VD->getType(); 3238 if (type.isNull()) 3239 return ExprError(); 3240 ExprValueKind valueKind = VK_PRValue; 3241 3242 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3243 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3244 // is expanded by some outer '...' in the context of the use. 3245 type = type.getNonPackExpansionType(); 3246 3247 switch (D->getKind()) { 3248 // Ignore all the non-ValueDecl kinds. 3249 #define ABSTRACT_DECL(kind) 3250 #define VALUE(type, base) 3251 #define DECL(type, base) case Decl::type: 3252 #include "clang/AST/DeclNodes.inc" 3253 llvm_unreachable("invalid value decl kind"); 3254 3255 // These shouldn't make it here. 3256 case Decl::ObjCAtDefsField: 3257 llvm_unreachable("forming non-member reference to ivar?"); 3258 3259 // Enum constants are always r-values and never references. 3260 // Unresolved using declarations are dependent. 3261 case Decl::EnumConstant: 3262 case Decl::UnresolvedUsingValue: 3263 case Decl::OMPDeclareReduction: 3264 case Decl::OMPDeclareMapper: 3265 valueKind = VK_PRValue; 3266 break; 3267 3268 // Fields and indirect fields that got here must be for 3269 // pointer-to-member expressions; we just call them l-values for 3270 // internal consistency, because this subexpression doesn't really 3271 // exist in the high-level semantics. 3272 case Decl::Field: 3273 case Decl::IndirectField: 3274 case Decl::ObjCIvar: 3275 assert(getLangOpts().CPlusPlus && "building reference to field in C?"); 3276 3277 // These can't have reference type in well-formed programs, but 3278 // for internal consistency we do this anyway. 3279 type = type.getNonReferenceType(); 3280 valueKind = VK_LValue; 3281 break; 3282 3283 // Non-type template parameters are either l-values or r-values 3284 // depending on the type. 3285 case Decl::NonTypeTemplateParm: { 3286 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3287 type = reftype->getPointeeType(); 3288 valueKind = VK_LValue; // even if the parameter is an r-value reference 3289 break; 3290 } 3291 3292 // [expr.prim.id.unqual]p2: 3293 // If the entity is a template parameter object for a template 3294 // parameter of type T, the type of the expression is const T. 3295 // [...] The expression is an lvalue if the entity is a [...] template 3296 // parameter object. 3297 if (type->isRecordType()) { 3298 type = type.getUnqualifiedType().withConst(); 3299 valueKind = VK_LValue; 3300 break; 3301 } 3302 3303 // For non-references, we need to strip qualifiers just in case 3304 // the template parameter was declared as 'const int' or whatever. 3305 valueKind = VK_PRValue; 3306 type = type.getUnqualifiedType(); 3307 break; 3308 } 3309 3310 case Decl::Var: 3311 case Decl::VarTemplateSpecialization: 3312 case Decl::VarTemplatePartialSpecialization: 3313 case Decl::Decomposition: 3314 case Decl::OMPCapturedExpr: 3315 // In C, "extern void blah;" is valid and is an r-value. 3316 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && 3317 type->isVoidType()) { 3318 valueKind = VK_PRValue; 3319 break; 3320 } 3321 LLVM_FALLTHROUGH; 3322 3323 case Decl::ImplicitParam: 3324 case Decl::ParmVar: { 3325 // These are always l-values. 3326 valueKind = VK_LValue; 3327 type = type.getNonReferenceType(); 3328 3329 // FIXME: Does the addition of const really only apply in 3330 // potentially-evaluated contexts? Since the variable isn't actually 3331 // captured in an unevaluated context, it seems that the answer is no. 3332 if (!isUnevaluatedContext()) { 3333 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3334 if (!CapturedType.isNull()) 3335 type = CapturedType; 3336 } 3337 3338 break; 3339 } 3340 3341 case Decl::Binding: { 3342 // These are always lvalues. 3343 valueKind = VK_LValue; 3344 type = type.getNonReferenceType(); 3345 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3346 // decides how that's supposed to work. 3347 auto *BD = cast<BindingDecl>(VD); 3348 if (BD->getDeclContext() != CurContext) { 3349 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3350 if (DD && DD->hasLocalStorage()) 3351 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3352 } 3353 break; 3354 } 3355 3356 case Decl::Function: { 3357 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3358 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3359 type = Context.BuiltinFnTy; 3360 valueKind = VK_PRValue; 3361 break; 3362 } 3363 } 3364 3365 const FunctionType *fty = type->castAs<FunctionType>(); 3366 3367 // If we're referring to a function with an __unknown_anytype 3368 // result type, make the entire expression __unknown_anytype. 3369 if (fty->getReturnType() == Context.UnknownAnyTy) { 3370 type = Context.UnknownAnyTy; 3371 valueKind = VK_PRValue; 3372 break; 3373 } 3374 3375 // Functions are l-values in C++. 3376 if (getLangOpts().CPlusPlus) { 3377 valueKind = VK_LValue; 3378 break; 3379 } 3380 3381 // C99 DR 316 says that, if a function type comes from a 3382 // function definition (without a prototype), that type is only 3383 // used for checking compatibility. Therefore, when referencing 3384 // the function, we pretend that we don't have the full function 3385 // type. 3386 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty)) 3387 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3388 fty->getExtInfo()); 3389 3390 // Functions are r-values in C. 3391 valueKind = VK_PRValue; 3392 break; 3393 } 3394 3395 case Decl::CXXDeductionGuide: 3396 llvm_unreachable("building reference to deduction guide"); 3397 3398 case Decl::MSProperty: 3399 case Decl::MSGuid: 3400 case Decl::TemplateParamObject: 3401 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3402 // capture in OpenMP, or duplicated between host and device? 3403 valueKind = VK_LValue; 3404 break; 3405 3406 case Decl::CXXMethod: 3407 // If we're referring to a method with an __unknown_anytype 3408 // result type, make the entire expression __unknown_anytype. 3409 // This should only be possible with a type written directly. 3410 if (const FunctionProtoType *proto = 3411 dyn_cast<FunctionProtoType>(VD->getType())) 3412 if (proto->getReturnType() == Context.UnknownAnyTy) { 3413 type = Context.UnknownAnyTy; 3414 valueKind = VK_PRValue; 3415 break; 3416 } 3417 3418 // C++ methods are l-values if static, r-values if non-static. 3419 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3420 valueKind = VK_LValue; 3421 break; 3422 } 3423 LLVM_FALLTHROUGH; 3424 3425 case Decl::CXXConversion: 3426 case Decl::CXXDestructor: 3427 case Decl::CXXConstructor: 3428 valueKind = VK_PRValue; 3429 break; 3430 } 3431 3432 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3433 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3434 TemplateArgs); 3435 } 3436 3437 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3438 SmallString<32> &Target) { 3439 Target.resize(CharByteWidth * (Source.size() + 1)); 3440 char *ResultPtr = &Target[0]; 3441 const llvm::UTF8 *ErrorPtr; 3442 bool success = 3443 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3444 (void)success; 3445 assert(success); 3446 Target.resize(ResultPtr - &Target[0]); 3447 } 3448 3449 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3450 PredefinedExpr::IdentKind IK) { 3451 // Pick the current block, lambda, captured statement or function. 3452 Decl *currentDecl = nullptr; 3453 if (const BlockScopeInfo *BSI = getCurBlock()) 3454 currentDecl = BSI->TheDecl; 3455 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3456 currentDecl = LSI->CallOperator; 3457 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3458 currentDecl = CSI->TheCapturedDecl; 3459 else 3460 currentDecl = getCurFunctionOrMethodDecl(); 3461 3462 if (!currentDecl) { 3463 Diag(Loc, diag::ext_predef_outside_function); 3464 currentDecl = Context.getTranslationUnitDecl(); 3465 } 3466 3467 QualType ResTy; 3468 StringLiteral *SL = nullptr; 3469 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3470 ResTy = Context.DependentTy; 3471 else { 3472 // Pre-defined identifiers are of type char[x], where x is the length of 3473 // the string. 3474 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3475 unsigned Length = Str.length(); 3476 3477 llvm::APInt LengthI(32, Length + 1); 3478 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3479 ResTy = 3480 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3481 SmallString<32> RawChars; 3482 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3483 Str, RawChars); 3484 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3485 ArrayType::Normal, 3486 /*IndexTypeQuals*/ 0); 3487 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3488 /*Pascal*/ false, ResTy, Loc); 3489 } else { 3490 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3491 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3492 ArrayType::Normal, 3493 /*IndexTypeQuals*/ 0); 3494 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3495 /*Pascal*/ false, ResTy, Loc); 3496 } 3497 } 3498 3499 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3500 } 3501 3502 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3503 SourceLocation LParen, 3504 SourceLocation RParen, 3505 TypeSourceInfo *TSI) { 3506 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); 3507 } 3508 3509 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3510 SourceLocation LParen, 3511 SourceLocation RParen, 3512 ParsedType ParsedTy) { 3513 TypeSourceInfo *TSI = nullptr; 3514 QualType Ty = GetTypeFromParser(ParsedTy, &TSI); 3515 3516 if (Ty.isNull()) 3517 return ExprError(); 3518 if (!TSI) 3519 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); 3520 3521 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); 3522 } 3523 3524 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3525 PredefinedExpr::IdentKind IK; 3526 3527 switch (Kind) { 3528 default: llvm_unreachable("Unknown simple primary expr!"); 3529 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3530 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3531 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3532 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3533 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3534 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3535 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3536 } 3537 3538 return BuildPredefinedExpr(Loc, IK); 3539 } 3540 3541 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3542 SmallString<16> CharBuffer; 3543 bool Invalid = false; 3544 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3545 if (Invalid) 3546 return ExprError(); 3547 3548 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3549 PP, Tok.getKind()); 3550 if (Literal.hadError()) 3551 return ExprError(); 3552 3553 QualType Ty; 3554 if (Literal.isWide()) 3555 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3556 else if (Literal.isUTF8() && getLangOpts().Char8) 3557 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3558 else if (Literal.isUTF16()) 3559 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3560 else if (Literal.isUTF32()) 3561 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3562 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3563 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3564 else 3565 Ty = Context.CharTy; // 'x' -> char in C++ 3566 3567 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3568 if (Literal.isWide()) 3569 Kind = CharacterLiteral::Wide; 3570 else if (Literal.isUTF16()) 3571 Kind = CharacterLiteral::UTF16; 3572 else if (Literal.isUTF32()) 3573 Kind = CharacterLiteral::UTF32; 3574 else if (Literal.isUTF8()) 3575 Kind = CharacterLiteral::UTF8; 3576 3577 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3578 Tok.getLocation()); 3579 3580 if (Literal.getUDSuffix().empty()) 3581 return Lit; 3582 3583 // We're building a user-defined literal. 3584 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3585 SourceLocation UDSuffixLoc = 3586 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3587 3588 // Make sure we're allowed user-defined literals here. 3589 if (!UDLScope) 3590 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3591 3592 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3593 // operator "" X (ch) 3594 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3595 Lit, Tok.getLocation()); 3596 } 3597 3598 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3599 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3600 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3601 Context.IntTy, Loc); 3602 } 3603 3604 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3605 QualType Ty, SourceLocation Loc) { 3606 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3607 3608 using llvm::APFloat; 3609 APFloat Val(Format); 3610 3611 APFloat::opStatus result = Literal.GetFloatValue(Val); 3612 3613 // Overflow is always an error, but underflow is only an error if 3614 // we underflowed to zero (APFloat reports denormals as underflow). 3615 if ((result & APFloat::opOverflow) || 3616 ((result & APFloat::opUnderflow) && Val.isZero())) { 3617 unsigned diagnostic; 3618 SmallString<20> buffer; 3619 if (result & APFloat::opOverflow) { 3620 diagnostic = diag::warn_float_overflow; 3621 APFloat::getLargest(Format).toString(buffer); 3622 } else { 3623 diagnostic = diag::warn_float_underflow; 3624 APFloat::getSmallest(Format).toString(buffer); 3625 } 3626 3627 S.Diag(Loc, diagnostic) 3628 << Ty 3629 << StringRef(buffer.data(), buffer.size()); 3630 } 3631 3632 bool isExact = (result == APFloat::opOK); 3633 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3634 } 3635 3636 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3637 assert(E && "Invalid expression"); 3638 3639 if (E->isValueDependent()) 3640 return false; 3641 3642 QualType QT = E->getType(); 3643 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3644 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3645 return true; 3646 } 3647 3648 llvm::APSInt ValueAPS; 3649 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3650 3651 if (R.isInvalid()) 3652 return true; 3653 3654 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3655 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3656 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3657 << toString(ValueAPS, 10) << ValueIsPositive; 3658 return true; 3659 } 3660 3661 return false; 3662 } 3663 3664 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3665 // Fast path for a single digit (which is quite common). A single digit 3666 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3667 if (Tok.getLength() == 1) { 3668 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3669 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3670 } 3671 3672 SmallString<128> SpellingBuffer; 3673 // NumericLiteralParser wants to overread by one character. Add padding to 3674 // the buffer in case the token is copied to the buffer. If getSpelling() 3675 // returns a StringRef to the memory buffer, it should have a null char at 3676 // the EOF, so it is also safe. 3677 SpellingBuffer.resize(Tok.getLength() + 1); 3678 3679 // Get the spelling of the token, which eliminates trigraphs, etc. 3680 bool Invalid = false; 3681 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3682 if (Invalid) 3683 return ExprError(); 3684 3685 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3686 PP.getSourceManager(), PP.getLangOpts(), 3687 PP.getTargetInfo(), PP.getDiagnostics()); 3688 if (Literal.hadError) 3689 return ExprError(); 3690 3691 if (Literal.hasUDSuffix()) { 3692 // We're building a user-defined literal. 3693 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3694 SourceLocation UDSuffixLoc = 3695 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3696 3697 // Make sure we're allowed user-defined literals here. 3698 if (!UDLScope) 3699 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3700 3701 QualType CookedTy; 3702 if (Literal.isFloatingLiteral()) { 3703 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3704 // long double, the literal is treated as a call of the form 3705 // operator "" X (f L) 3706 CookedTy = Context.LongDoubleTy; 3707 } else { 3708 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3709 // unsigned long long, the literal is treated as a call of the form 3710 // operator "" X (n ULL) 3711 CookedTy = Context.UnsignedLongLongTy; 3712 } 3713 3714 DeclarationName OpName = 3715 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3716 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3717 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3718 3719 SourceLocation TokLoc = Tok.getLocation(); 3720 3721 // Perform literal operator lookup to determine if we're building a raw 3722 // literal or a cooked one. 3723 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3724 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3725 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3726 /*AllowStringTemplatePack*/ false, 3727 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3728 case LOLR_ErrorNoDiagnostic: 3729 // Lookup failure for imaginary constants isn't fatal, there's still the 3730 // GNU extension producing _Complex types. 3731 break; 3732 case LOLR_Error: 3733 return ExprError(); 3734 case LOLR_Cooked: { 3735 Expr *Lit; 3736 if (Literal.isFloatingLiteral()) { 3737 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3738 } else { 3739 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3740 if (Literal.GetIntegerValue(ResultVal)) 3741 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3742 << /* Unsigned */ 1; 3743 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3744 Tok.getLocation()); 3745 } 3746 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3747 } 3748 3749 case LOLR_Raw: { 3750 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3751 // literal is treated as a call of the form 3752 // operator "" X ("n") 3753 unsigned Length = Literal.getUDSuffixOffset(); 3754 QualType StrTy = Context.getConstantArrayType( 3755 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3756 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3757 Expr *Lit = StringLiteral::Create( 3758 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3759 /*Pascal*/false, StrTy, &TokLoc, 1); 3760 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3761 } 3762 3763 case LOLR_Template: { 3764 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3765 // template), L is treated as a call fo the form 3766 // operator "" X <'c1', 'c2', ... 'ck'>() 3767 // where n is the source character sequence c1 c2 ... ck. 3768 TemplateArgumentListInfo ExplicitArgs; 3769 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3770 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3771 llvm::APSInt Value(CharBits, CharIsUnsigned); 3772 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3773 Value = TokSpelling[I]; 3774 TemplateArgument Arg(Context, Value, Context.CharTy); 3775 TemplateArgumentLocInfo ArgInfo; 3776 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3777 } 3778 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3779 &ExplicitArgs); 3780 } 3781 case LOLR_StringTemplatePack: 3782 llvm_unreachable("unexpected literal operator lookup result"); 3783 } 3784 } 3785 3786 Expr *Res; 3787 3788 if (Literal.isFixedPointLiteral()) { 3789 QualType Ty; 3790 3791 if (Literal.isAccum) { 3792 if (Literal.isHalf) { 3793 Ty = Context.ShortAccumTy; 3794 } else if (Literal.isLong) { 3795 Ty = Context.LongAccumTy; 3796 } else { 3797 Ty = Context.AccumTy; 3798 } 3799 } else if (Literal.isFract) { 3800 if (Literal.isHalf) { 3801 Ty = Context.ShortFractTy; 3802 } else if (Literal.isLong) { 3803 Ty = Context.LongFractTy; 3804 } else { 3805 Ty = Context.FractTy; 3806 } 3807 } 3808 3809 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3810 3811 bool isSigned = !Literal.isUnsigned; 3812 unsigned scale = Context.getFixedPointScale(Ty); 3813 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3814 3815 llvm::APInt Val(bit_width, 0, isSigned); 3816 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3817 bool ValIsZero = Val.isZero() && !Overflowed; 3818 3819 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3820 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3821 // Clause 6.4.4 - The value of a constant shall be in the range of 3822 // representable values for its type, with exception for constants of a 3823 // fract type with a value of exactly 1; such a constant shall denote 3824 // the maximal value for the type. 3825 --Val; 3826 else if (Val.ugt(MaxVal) || Overflowed) 3827 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3828 3829 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3830 Tok.getLocation(), scale); 3831 } else if (Literal.isFloatingLiteral()) { 3832 QualType Ty; 3833 if (Literal.isHalf){ 3834 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3835 Ty = Context.HalfTy; 3836 else { 3837 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3838 return ExprError(); 3839 } 3840 } else if (Literal.isFloat) 3841 Ty = Context.FloatTy; 3842 else if (Literal.isLong) 3843 Ty = Context.LongDoubleTy; 3844 else if (Literal.isFloat16) 3845 Ty = Context.Float16Ty; 3846 else if (Literal.isFloat128) 3847 Ty = Context.Float128Ty; 3848 else 3849 Ty = Context.DoubleTy; 3850 3851 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3852 3853 if (Ty == Context.DoubleTy) { 3854 if (getLangOpts().SinglePrecisionConstants) { 3855 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3856 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3857 } 3858 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3859 "cl_khr_fp64", getLangOpts())) { 3860 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3861 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) 3862 << (getLangOpts().getOpenCLCompatibleVersion() >= 300); 3863 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3864 } 3865 } 3866 } else if (!Literal.isIntegerLiteral()) { 3867 return ExprError(); 3868 } else { 3869 QualType Ty; 3870 3871 // 'long long' is a C99 or C++11 feature. 3872 if (!getLangOpts().C99 && Literal.isLongLong) { 3873 if (getLangOpts().CPlusPlus) 3874 Diag(Tok.getLocation(), 3875 getLangOpts().CPlusPlus11 ? 3876 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3877 else 3878 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3879 } 3880 3881 // 'z/uz' literals are a C++2b feature. 3882 if (Literal.isSizeT) 3883 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3884 ? getLangOpts().CPlusPlus2b 3885 ? diag::warn_cxx20_compat_size_t_suffix 3886 : diag::ext_cxx2b_size_t_suffix 3887 : diag::err_cxx2b_size_t_suffix); 3888 3889 // Get the value in the widest-possible width. 3890 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3891 llvm::APInt ResultVal(MaxWidth, 0); 3892 3893 if (Literal.GetIntegerValue(ResultVal)) { 3894 // If this value didn't fit into uintmax_t, error and force to ull. 3895 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3896 << /* Unsigned */ 1; 3897 Ty = Context.UnsignedLongLongTy; 3898 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3899 "long long is not intmax_t?"); 3900 } else { 3901 // If this value fits into a ULL, try to figure out what else it fits into 3902 // according to the rules of C99 6.4.4.1p5. 3903 3904 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3905 // be an unsigned int. 3906 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3907 3908 // Check from smallest to largest, picking the smallest type we can. 3909 unsigned Width = 0; 3910 3911 // Microsoft specific integer suffixes are explicitly sized. 3912 if (Literal.MicrosoftInteger) { 3913 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3914 Width = 8; 3915 Ty = Context.CharTy; 3916 } else { 3917 Width = Literal.MicrosoftInteger; 3918 Ty = Context.getIntTypeForBitwidth(Width, 3919 /*Signed=*/!Literal.isUnsigned); 3920 } 3921 } 3922 3923 // Check C++2b size_t literals. 3924 if (Literal.isSizeT) { 3925 assert(!Literal.MicrosoftInteger && 3926 "size_t literals can't be Microsoft literals"); 3927 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 3928 Context.getTargetInfo().getSizeType()); 3929 3930 // Does it fit in size_t? 3931 if (ResultVal.isIntN(SizeTSize)) { 3932 // Does it fit in ssize_t? 3933 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 3934 Ty = Context.getSignedSizeType(); 3935 else if (AllowUnsigned) 3936 Ty = Context.getSizeType(); 3937 Width = SizeTSize; 3938 } 3939 } 3940 3941 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 3942 !Literal.isSizeT) { 3943 // Are int/unsigned possibilities? 3944 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3945 3946 // Does it fit in a unsigned int? 3947 if (ResultVal.isIntN(IntSize)) { 3948 // Does it fit in a signed int? 3949 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3950 Ty = Context.IntTy; 3951 else if (AllowUnsigned) 3952 Ty = Context.UnsignedIntTy; 3953 Width = IntSize; 3954 } 3955 } 3956 3957 // Are long/unsigned long possibilities? 3958 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 3959 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3960 3961 // Does it fit in a unsigned long? 3962 if (ResultVal.isIntN(LongSize)) { 3963 // Does it fit in a signed long? 3964 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3965 Ty = Context.LongTy; 3966 else if (AllowUnsigned) 3967 Ty = Context.UnsignedLongTy; 3968 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3969 // is compatible. 3970 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3971 const unsigned LongLongSize = 3972 Context.getTargetInfo().getLongLongWidth(); 3973 Diag(Tok.getLocation(), 3974 getLangOpts().CPlusPlus 3975 ? Literal.isLong 3976 ? diag::warn_old_implicitly_unsigned_long_cxx 3977 : /*C++98 UB*/ diag:: 3978 ext_old_implicitly_unsigned_long_cxx 3979 : diag::warn_old_implicitly_unsigned_long) 3980 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3981 : /*will be ill-formed*/ 1); 3982 Ty = Context.UnsignedLongTy; 3983 } 3984 Width = LongSize; 3985 } 3986 } 3987 3988 // Check long long if needed. 3989 if (Ty.isNull() && !Literal.isSizeT) { 3990 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3991 3992 // Does it fit in a unsigned long long? 3993 if (ResultVal.isIntN(LongLongSize)) { 3994 // Does it fit in a signed long long? 3995 // To be compatible with MSVC, hex integer literals ending with the 3996 // LL or i64 suffix are always signed in Microsoft mode. 3997 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3998 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3999 Ty = Context.LongLongTy; 4000 else if (AllowUnsigned) 4001 Ty = Context.UnsignedLongLongTy; 4002 Width = LongLongSize; 4003 } 4004 } 4005 4006 // If we still couldn't decide a type, we either have 'size_t' literal 4007 // that is out of range, or a decimal literal that does not fit in a 4008 // signed long long and has no U suffix. 4009 if (Ty.isNull()) { 4010 if (Literal.isSizeT) 4011 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 4012 << Literal.isUnsigned; 4013 else 4014 Diag(Tok.getLocation(), 4015 diag::ext_integer_literal_too_large_for_signed); 4016 Ty = Context.UnsignedLongLongTy; 4017 Width = Context.getTargetInfo().getLongLongWidth(); 4018 } 4019 4020 if (ResultVal.getBitWidth() != Width) 4021 ResultVal = ResultVal.trunc(Width); 4022 } 4023 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 4024 } 4025 4026 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 4027 if (Literal.isImaginary) { 4028 Res = new (Context) ImaginaryLiteral(Res, 4029 Context.getComplexType(Res->getType())); 4030 4031 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4032 } 4033 return Res; 4034 } 4035 4036 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4037 assert(E && "ActOnParenExpr() missing expr"); 4038 QualType ExprTy = E->getType(); 4039 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && 4040 !E->isLValue() && ExprTy->hasFloatingRepresentation()) 4041 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); 4042 return new (Context) ParenExpr(L, R, E); 4043 } 4044 4045 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4046 SourceLocation Loc, 4047 SourceRange ArgRange) { 4048 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4049 // scalar or vector data type argument..." 4050 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4051 // type (C99 6.2.5p18) or void. 4052 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4053 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4054 << T << ArgRange; 4055 return true; 4056 } 4057 4058 assert((T->isVoidType() || !T->isIncompleteType()) && 4059 "Scalar types should always be complete"); 4060 return false; 4061 } 4062 4063 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4064 SourceLocation Loc, 4065 SourceRange ArgRange, 4066 UnaryExprOrTypeTrait TraitKind) { 4067 // Invalid types must be hard errors for SFINAE in C++. 4068 if (S.LangOpts.CPlusPlus) 4069 return true; 4070 4071 // C99 6.5.3.4p1: 4072 if (T->isFunctionType() && 4073 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4074 TraitKind == UETT_PreferredAlignOf)) { 4075 // sizeof(function)/alignof(function) is allowed as an extension. 4076 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4077 << getTraitSpelling(TraitKind) << ArgRange; 4078 return false; 4079 } 4080 4081 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4082 // this is an error (OpenCL v1.1 s6.3.k) 4083 if (T->isVoidType()) { 4084 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4085 : diag::ext_sizeof_alignof_void_type; 4086 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4087 return false; 4088 } 4089 4090 return true; 4091 } 4092 4093 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4094 SourceLocation Loc, 4095 SourceRange ArgRange, 4096 UnaryExprOrTypeTrait TraitKind) { 4097 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4098 // runtime doesn't allow it. 4099 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4100 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4101 << T << (TraitKind == UETT_SizeOf) 4102 << ArgRange; 4103 return true; 4104 } 4105 4106 return false; 4107 } 4108 4109 /// Check whether E is a pointer from a decayed array type (the decayed 4110 /// pointer type is equal to T) and emit a warning if it is. 4111 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4112 Expr *E) { 4113 // Don't warn if the operation changed the type. 4114 if (T != E->getType()) 4115 return; 4116 4117 // Now look for array decays. 4118 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4119 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4120 return; 4121 4122 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4123 << ICE->getType() 4124 << ICE->getSubExpr()->getType(); 4125 } 4126 4127 /// Check the constraints on expression operands to unary type expression 4128 /// and type traits. 4129 /// 4130 /// Completes any types necessary and validates the constraints on the operand 4131 /// expression. The logic mostly mirrors the type-based overload, but may modify 4132 /// the expression as it completes the type for that expression through template 4133 /// instantiation, etc. 4134 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4135 UnaryExprOrTypeTrait ExprKind) { 4136 QualType ExprTy = E->getType(); 4137 assert(!ExprTy->isReferenceType()); 4138 4139 bool IsUnevaluatedOperand = 4140 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4141 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4142 if (IsUnevaluatedOperand) { 4143 ExprResult Result = CheckUnevaluatedOperand(E); 4144 if (Result.isInvalid()) 4145 return true; 4146 E = Result.get(); 4147 } 4148 4149 // The operand for sizeof and alignof is in an unevaluated expression context, 4150 // so side effects could result in unintended consequences. 4151 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4152 // used to build SFINAE gadgets. 4153 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4154 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4155 !E->isInstantiationDependent() && 4156 E->HasSideEffects(Context, false)) 4157 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4158 4159 if (ExprKind == UETT_VecStep) 4160 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4161 E->getSourceRange()); 4162 4163 // Explicitly list some types as extensions. 4164 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4165 E->getSourceRange(), ExprKind)) 4166 return false; 4167 4168 // 'alignof' applied to an expression only requires the base element type of 4169 // the expression to be complete. 'sizeof' requires the expression's type to 4170 // be complete (and will attempt to complete it if it's an array of unknown 4171 // bound). 4172 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4173 if (RequireCompleteSizedType( 4174 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4175 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4176 getTraitSpelling(ExprKind), E->getSourceRange())) 4177 return true; 4178 } else { 4179 if (RequireCompleteSizedExprType( 4180 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4181 getTraitSpelling(ExprKind), E->getSourceRange())) 4182 return true; 4183 } 4184 4185 // Completing the expression's type may have changed it. 4186 ExprTy = E->getType(); 4187 assert(!ExprTy->isReferenceType()); 4188 4189 if (ExprTy->isFunctionType()) { 4190 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4191 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4192 return true; 4193 } 4194 4195 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4196 E->getSourceRange(), ExprKind)) 4197 return true; 4198 4199 if (ExprKind == UETT_SizeOf) { 4200 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4201 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4202 QualType OType = PVD->getOriginalType(); 4203 QualType Type = PVD->getType(); 4204 if (Type->isPointerType() && OType->isArrayType()) { 4205 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4206 << Type << OType; 4207 Diag(PVD->getLocation(), diag::note_declared_at); 4208 } 4209 } 4210 } 4211 4212 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4213 // decays into a pointer and returns an unintended result. This is most 4214 // likely a typo for "sizeof(array) op x". 4215 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4216 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4217 BO->getLHS()); 4218 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4219 BO->getRHS()); 4220 } 4221 } 4222 4223 return false; 4224 } 4225 4226 /// Check the constraints on operands to unary expression and type 4227 /// traits. 4228 /// 4229 /// This will complete any types necessary, and validate the various constraints 4230 /// on those operands. 4231 /// 4232 /// The UsualUnaryConversions() function is *not* called by this routine. 4233 /// C99 6.3.2.1p[2-4] all state: 4234 /// Except when it is the operand of the sizeof operator ... 4235 /// 4236 /// C++ [expr.sizeof]p4 4237 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4238 /// standard conversions are not applied to the operand of sizeof. 4239 /// 4240 /// This policy is followed for all of the unary trait expressions. 4241 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4242 SourceLocation OpLoc, 4243 SourceRange ExprRange, 4244 UnaryExprOrTypeTrait ExprKind) { 4245 if (ExprType->isDependentType()) 4246 return false; 4247 4248 // C++ [expr.sizeof]p2: 4249 // When applied to a reference or a reference type, the result 4250 // is the size of the referenced type. 4251 // C++11 [expr.alignof]p3: 4252 // When alignof is applied to a reference type, the result 4253 // shall be the alignment of the referenced type. 4254 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4255 ExprType = Ref->getPointeeType(); 4256 4257 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4258 // When alignof or _Alignof is applied to an array type, the result 4259 // is the alignment of the element type. 4260 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4261 ExprKind == UETT_OpenMPRequiredSimdAlign) 4262 ExprType = Context.getBaseElementType(ExprType); 4263 4264 if (ExprKind == UETT_VecStep) 4265 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4266 4267 // Explicitly list some types as extensions. 4268 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4269 ExprKind)) 4270 return false; 4271 4272 if (RequireCompleteSizedType( 4273 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4274 getTraitSpelling(ExprKind), ExprRange)) 4275 return true; 4276 4277 if (ExprType->isFunctionType()) { 4278 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4279 << getTraitSpelling(ExprKind) << ExprRange; 4280 return true; 4281 } 4282 4283 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4284 ExprKind)) 4285 return true; 4286 4287 return false; 4288 } 4289 4290 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4291 // Cannot know anything else if the expression is dependent. 4292 if (E->isTypeDependent()) 4293 return false; 4294 4295 if (E->getObjectKind() == OK_BitField) { 4296 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4297 << 1 << E->getSourceRange(); 4298 return true; 4299 } 4300 4301 ValueDecl *D = nullptr; 4302 Expr *Inner = E->IgnoreParens(); 4303 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4304 D = DRE->getDecl(); 4305 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4306 D = ME->getMemberDecl(); 4307 } 4308 4309 // If it's a field, require the containing struct to have a 4310 // complete definition so that we can compute the layout. 4311 // 4312 // This can happen in C++11 onwards, either by naming the member 4313 // in a way that is not transformed into a member access expression 4314 // (in an unevaluated operand, for instance), or by naming the member 4315 // in a trailing-return-type. 4316 // 4317 // For the record, since __alignof__ on expressions is a GCC 4318 // extension, GCC seems to permit this but always gives the 4319 // nonsensical answer 0. 4320 // 4321 // We don't really need the layout here --- we could instead just 4322 // directly check for all the appropriate alignment-lowing 4323 // attributes --- but that would require duplicating a lot of 4324 // logic that just isn't worth duplicating for such a marginal 4325 // use-case. 4326 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4327 // Fast path this check, since we at least know the record has a 4328 // definition if we can find a member of it. 4329 if (!FD->getParent()->isCompleteDefinition()) { 4330 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4331 << E->getSourceRange(); 4332 return true; 4333 } 4334 4335 // Otherwise, if it's a field, and the field doesn't have 4336 // reference type, then it must have a complete type (or be a 4337 // flexible array member, which we explicitly want to 4338 // white-list anyway), which makes the following checks trivial. 4339 if (!FD->getType()->isReferenceType()) 4340 return false; 4341 } 4342 4343 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4344 } 4345 4346 bool Sema::CheckVecStepExpr(Expr *E) { 4347 E = E->IgnoreParens(); 4348 4349 // Cannot know anything else if the expression is dependent. 4350 if (E->isTypeDependent()) 4351 return false; 4352 4353 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4354 } 4355 4356 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4357 CapturingScopeInfo *CSI) { 4358 assert(T->isVariablyModifiedType()); 4359 assert(CSI != nullptr); 4360 4361 // We're going to walk down into the type and look for VLA expressions. 4362 do { 4363 const Type *Ty = T.getTypePtr(); 4364 switch (Ty->getTypeClass()) { 4365 #define TYPE(Class, Base) 4366 #define ABSTRACT_TYPE(Class, Base) 4367 #define NON_CANONICAL_TYPE(Class, Base) 4368 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4369 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4370 #include "clang/AST/TypeNodes.inc" 4371 T = QualType(); 4372 break; 4373 // These types are never variably-modified. 4374 case Type::Builtin: 4375 case Type::Complex: 4376 case Type::Vector: 4377 case Type::ExtVector: 4378 case Type::ConstantMatrix: 4379 case Type::Record: 4380 case Type::Enum: 4381 case Type::Elaborated: 4382 case Type::TemplateSpecialization: 4383 case Type::ObjCObject: 4384 case Type::ObjCInterface: 4385 case Type::ObjCObjectPointer: 4386 case Type::ObjCTypeParam: 4387 case Type::Pipe: 4388 case Type::ExtInt: 4389 llvm_unreachable("type class is never variably-modified!"); 4390 case Type::Adjusted: 4391 T = cast<AdjustedType>(Ty)->getOriginalType(); 4392 break; 4393 case Type::Decayed: 4394 T = cast<DecayedType>(Ty)->getPointeeType(); 4395 break; 4396 case Type::Pointer: 4397 T = cast<PointerType>(Ty)->getPointeeType(); 4398 break; 4399 case Type::BlockPointer: 4400 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4401 break; 4402 case Type::LValueReference: 4403 case Type::RValueReference: 4404 T = cast<ReferenceType>(Ty)->getPointeeType(); 4405 break; 4406 case Type::MemberPointer: 4407 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4408 break; 4409 case Type::ConstantArray: 4410 case Type::IncompleteArray: 4411 // Losing element qualification here is fine. 4412 T = cast<ArrayType>(Ty)->getElementType(); 4413 break; 4414 case Type::VariableArray: { 4415 // Losing element qualification here is fine. 4416 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4417 4418 // Unknown size indication requires no size computation. 4419 // Otherwise, evaluate and record it. 4420 auto Size = VAT->getSizeExpr(); 4421 if (Size && !CSI->isVLATypeCaptured(VAT) && 4422 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4423 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4424 4425 T = VAT->getElementType(); 4426 break; 4427 } 4428 case Type::FunctionProto: 4429 case Type::FunctionNoProto: 4430 T = cast<FunctionType>(Ty)->getReturnType(); 4431 break; 4432 case Type::Paren: 4433 case Type::TypeOf: 4434 case Type::UnaryTransform: 4435 case Type::Attributed: 4436 case Type::SubstTemplateTypeParm: 4437 case Type::MacroQualified: 4438 // Keep walking after single level desugaring. 4439 T = T.getSingleStepDesugaredType(Context); 4440 break; 4441 case Type::Typedef: 4442 T = cast<TypedefType>(Ty)->desugar(); 4443 break; 4444 case Type::Decltype: 4445 T = cast<DecltypeType>(Ty)->desugar(); 4446 break; 4447 case Type::Auto: 4448 case Type::DeducedTemplateSpecialization: 4449 T = cast<DeducedType>(Ty)->getDeducedType(); 4450 break; 4451 case Type::TypeOfExpr: 4452 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4453 break; 4454 case Type::Atomic: 4455 T = cast<AtomicType>(Ty)->getValueType(); 4456 break; 4457 } 4458 } while (!T.isNull() && T->isVariablyModifiedType()); 4459 } 4460 4461 /// Build a sizeof or alignof expression given a type operand. 4462 ExprResult 4463 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4464 SourceLocation OpLoc, 4465 UnaryExprOrTypeTrait ExprKind, 4466 SourceRange R) { 4467 if (!TInfo) 4468 return ExprError(); 4469 4470 QualType T = TInfo->getType(); 4471 4472 if (!T->isDependentType() && 4473 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4474 return ExprError(); 4475 4476 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4477 if (auto *TT = T->getAs<TypedefType>()) { 4478 for (auto I = FunctionScopes.rbegin(), 4479 E = std::prev(FunctionScopes.rend()); 4480 I != E; ++I) { 4481 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4482 if (CSI == nullptr) 4483 break; 4484 DeclContext *DC = nullptr; 4485 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4486 DC = LSI->CallOperator; 4487 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4488 DC = CRSI->TheCapturedDecl; 4489 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4490 DC = BSI->TheDecl; 4491 if (DC) { 4492 if (DC->containsDecl(TT->getDecl())) 4493 break; 4494 captureVariablyModifiedType(Context, T, CSI); 4495 } 4496 } 4497 } 4498 } 4499 4500 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4501 return new (Context) UnaryExprOrTypeTraitExpr( 4502 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4503 } 4504 4505 /// Build a sizeof or alignof expression given an expression 4506 /// operand. 4507 ExprResult 4508 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4509 UnaryExprOrTypeTrait ExprKind) { 4510 ExprResult PE = CheckPlaceholderExpr(E); 4511 if (PE.isInvalid()) 4512 return ExprError(); 4513 4514 E = PE.get(); 4515 4516 // Verify that the operand is valid. 4517 bool isInvalid = false; 4518 if (E->isTypeDependent()) { 4519 // Delay type-checking for type-dependent expressions. 4520 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4521 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4522 } else if (ExprKind == UETT_VecStep) { 4523 isInvalid = CheckVecStepExpr(E); 4524 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4525 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4526 isInvalid = true; 4527 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4528 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4529 isInvalid = true; 4530 } else { 4531 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4532 } 4533 4534 if (isInvalid) 4535 return ExprError(); 4536 4537 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4538 PE = TransformToPotentiallyEvaluated(E); 4539 if (PE.isInvalid()) return ExprError(); 4540 E = PE.get(); 4541 } 4542 4543 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4544 return new (Context) UnaryExprOrTypeTraitExpr( 4545 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4546 } 4547 4548 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4549 /// expr and the same for @c alignof and @c __alignof 4550 /// Note that the ArgRange is invalid if isType is false. 4551 ExprResult 4552 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4553 UnaryExprOrTypeTrait ExprKind, bool IsType, 4554 void *TyOrEx, SourceRange ArgRange) { 4555 // If error parsing type, ignore. 4556 if (!TyOrEx) return ExprError(); 4557 4558 if (IsType) { 4559 TypeSourceInfo *TInfo; 4560 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4561 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4562 } 4563 4564 Expr *ArgEx = (Expr *)TyOrEx; 4565 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4566 return Result; 4567 } 4568 4569 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4570 bool IsReal) { 4571 if (V.get()->isTypeDependent()) 4572 return S.Context.DependentTy; 4573 4574 // _Real and _Imag are only l-values for normal l-values. 4575 if (V.get()->getObjectKind() != OK_Ordinary) { 4576 V = S.DefaultLvalueConversion(V.get()); 4577 if (V.isInvalid()) 4578 return QualType(); 4579 } 4580 4581 // These operators return the element type of a complex type. 4582 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4583 return CT->getElementType(); 4584 4585 // Otherwise they pass through real integer and floating point types here. 4586 if (V.get()->getType()->isArithmeticType()) 4587 return V.get()->getType(); 4588 4589 // Test for placeholders. 4590 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4591 if (PR.isInvalid()) return QualType(); 4592 if (PR.get() != V.get()) { 4593 V = PR; 4594 return CheckRealImagOperand(S, V, Loc, IsReal); 4595 } 4596 4597 // Reject anything else. 4598 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4599 << (IsReal ? "__real" : "__imag"); 4600 return QualType(); 4601 } 4602 4603 4604 4605 ExprResult 4606 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4607 tok::TokenKind Kind, Expr *Input) { 4608 UnaryOperatorKind Opc; 4609 switch (Kind) { 4610 default: llvm_unreachable("Unknown unary op!"); 4611 case tok::plusplus: Opc = UO_PostInc; break; 4612 case tok::minusminus: Opc = UO_PostDec; break; 4613 } 4614 4615 // Since this might is a postfix expression, get rid of ParenListExprs. 4616 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4617 if (Result.isInvalid()) return ExprError(); 4618 Input = Result.get(); 4619 4620 return BuildUnaryOp(S, OpLoc, Opc, Input); 4621 } 4622 4623 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4624 /// 4625 /// \return true on error 4626 static bool checkArithmeticOnObjCPointer(Sema &S, 4627 SourceLocation opLoc, 4628 Expr *op) { 4629 assert(op->getType()->isObjCObjectPointerType()); 4630 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4631 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4632 return false; 4633 4634 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4635 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4636 << op->getSourceRange(); 4637 return true; 4638 } 4639 4640 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4641 auto *BaseNoParens = Base->IgnoreParens(); 4642 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4643 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4644 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4645 } 4646 4647 ExprResult 4648 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4649 Expr *idx, SourceLocation rbLoc) { 4650 if (base && !base->getType().isNull() && 4651 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4652 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4653 SourceLocation(), /*Length*/ nullptr, 4654 /*Stride=*/nullptr, rbLoc); 4655 4656 // Since this might be a postfix expression, get rid of ParenListExprs. 4657 if (isa<ParenListExpr>(base)) { 4658 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4659 if (result.isInvalid()) return ExprError(); 4660 base = result.get(); 4661 } 4662 4663 // Check if base and idx form a MatrixSubscriptExpr. 4664 // 4665 // Helper to check for comma expressions, which are not allowed as indices for 4666 // matrix subscript expressions. 4667 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4668 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4669 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4670 << SourceRange(base->getBeginLoc(), rbLoc); 4671 return true; 4672 } 4673 return false; 4674 }; 4675 // The matrix subscript operator ([][])is considered a single operator. 4676 // Separating the index expressions by parenthesis is not allowed. 4677 if (base->getType()->isSpecificPlaceholderType( 4678 BuiltinType::IncompleteMatrixIdx) && 4679 !isa<MatrixSubscriptExpr>(base)) { 4680 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4681 << SourceRange(base->getBeginLoc(), rbLoc); 4682 return ExprError(); 4683 } 4684 // If the base is a MatrixSubscriptExpr, try to create a new 4685 // MatrixSubscriptExpr. 4686 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4687 if (matSubscriptE) { 4688 if (CheckAndReportCommaError(idx)) 4689 return ExprError(); 4690 4691 assert(matSubscriptE->isIncomplete() && 4692 "base has to be an incomplete matrix subscript"); 4693 return CreateBuiltinMatrixSubscriptExpr( 4694 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4695 } 4696 4697 // Handle any non-overload placeholder types in the base and index 4698 // expressions. We can't handle overloads here because the other 4699 // operand might be an overloadable type, in which case the overload 4700 // resolution for the operator overload should get the first crack 4701 // at the overload. 4702 bool IsMSPropertySubscript = false; 4703 if (base->getType()->isNonOverloadPlaceholderType()) { 4704 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4705 if (!IsMSPropertySubscript) { 4706 ExprResult result = CheckPlaceholderExpr(base); 4707 if (result.isInvalid()) 4708 return ExprError(); 4709 base = result.get(); 4710 } 4711 } 4712 4713 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4714 if (base->getType()->isMatrixType()) { 4715 if (CheckAndReportCommaError(idx)) 4716 return ExprError(); 4717 4718 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4719 } 4720 4721 // A comma-expression as the index is deprecated in C++2a onwards. 4722 if (getLangOpts().CPlusPlus20 && 4723 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4724 (isa<CXXOperatorCallExpr>(idx) && 4725 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4726 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4727 << SourceRange(base->getBeginLoc(), rbLoc); 4728 } 4729 4730 if (idx->getType()->isNonOverloadPlaceholderType()) { 4731 ExprResult result = CheckPlaceholderExpr(idx); 4732 if (result.isInvalid()) return ExprError(); 4733 idx = result.get(); 4734 } 4735 4736 // Build an unanalyzed expression if either operand is type-dependent. 4737 if (getLangOpts().CPlusPlus && 4738 (base->isTypeDependent() || idx->isTypeDependent())) { 4739 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4740 VK_LValue, OK_Ordinary, rbLoc); 4741 } 4742 4743 // MSDN, property (C++) 4744 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4745 // This attribute can also be used in the declaration of an empty array in a 4746 // class or structure definition. For example: 4747 // __declspec(property(get=GetX, put=PutX)) int x[]; 4748 // The above statement indicates that x[] can be used with one or more array 4749 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4750 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4751 if (IsMSPropertySubscript) { 4752 // Build MS property subscript expression if base is MS property reference 4753 // or MS property subscript. 4754 return new (Context) MSPropertySubscriptExpr( 4755 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4756 } 4757 4758 // Use C++ overloaded-operator rules if either operand has record 4759 // type. The spec says to do this if either type is *overloadable*, 4760 // but enum types can't declare subscript operators or conversion 4761 // operators, so there's nothing interesting for overload resolution 4762 // to do if there aren't any record types involved. 4763 // 4764 // ObjC pointers have their own subscripting logic that is not tied 4765 // to overload resolution and so should not take this path. 4766 if (getLangOpts().CPlusPlus && 4767 (base->getType()->isRecordType() || 4768 (!base->getType()->isObjCObjectPointerType() && 4769 idx->getType()->isRecordType()))) { 4770 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4771 } 4772 4773 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4774 4775 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4776 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4777 4778 return Res; 4779 } 4780 4781 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4782 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4783 InitializationKind Kind = 4784 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4785 InitializationSequence InitSeq(*this, Entity, Kind, E); 4786 return InitSeq.Perform(*this, Entity, Kind, E); 4787 } 4788 4789 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4790 Expr *ColumnIdx, 4791 SourceLocation RBLoc) { 4792 ExprResult BaseR = CheckPlaceholderExpr(Base); 4793 if (BaseR.isInvalid()) 4794 return BaseR; 4795 Base = BaseR.get(); 4796 4797 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4798 if (RowR.isInvalid()) 4799 return RowR; 4800 RowIdx = RowR.get(); 4801 4802 if (!ColumnIdx) 4803 return new (Context) MatrixSubscriptExpr( 4804 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4805 4806 // Build an unanalyzed expression if any of the operands is type-dependent. 4807 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4808 ColumnIdx->isTypeDependent()) 4809 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4810 Context.DependentTy, RBLoc); 4811 4812 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4813 if (ColumnR.isInvalid()) 4814 return ColumnR; 4815 ColumnIdx = ColumnR.get(); 4816 4817 // Check that IndexExpr is an integer expression. If it is a constant 4818 // expression, check that it is less than Dim (= the number of elements in the 4819 // corresponding dimension). 4820 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4821 bool IsColumnIdx) -> Expr * { 4822 if (!IndexExpr->getType()->isIntegerType() && 4823 !IndexExpr->isTypeDependent()) { 4824 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4825 << IsColumnIdx; 4826 return nullptr; 4827 } 4828 4829 if (Optional<llvm::APSInt> Idx = 4830 IndexExpr->getIntegerConstantExpr(Context)) { 4831 if ((*Idx < 0 || *Idx >= Dim)) { 4832 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4833 << IsColumnIdx << Dim; 4834 return nullptr; 4835 } 4836 } 4837 4838 ExprResult ConvExpr = 4839 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4840 assert(!ConvExpr.isInvalid() && 4841 "should be able to convert any integer type to size type"); 4842 return ConvExpr.get(); 4843 }; 4844 4845 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4846 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4847 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4848 if (!RowIdx || !ColumnIdx) 4849 return ExprError(); 4850 4851 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4852 MTy->getElementType(), RBLoc); 4853 } 4854 4855 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4856 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4857 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4858 4859 // For expressions like `&(*s).b`, the base is recorded and what should be 4860 // checked. 4861 const MemberExpr *Member = nullptr; 4862 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4863 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4864 4865 LastRecord.PossibleDerefs.erase(StrippedExpr); 4866 } 4867 4868 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4869 if (isUnevaluatedContext()) 4870 return; 4871 4872 QualType ResultTy = E->getType(); 4873 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4874 4875 // Bail if the element is an array since it is not memory access. 4876 if (isa<ArrayType>(ResultTy)) 4877 return; 4878 4879 if (ResultTy->hasAttr(attr::NoDeref)) { 4880 LastRecord.PossibleDerefs.insert(E); 4881 return; 4882 } 4883 4884 // Check if the base type is a pointer to a member access of a struct 4885 // marked with noderef. 4886 const Expr *Base = E->getBase(); 4887 QualType BaseTy = Base->getType(); 4888 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4889 // Not a pointer access 4890 return; 4891 4892 const MemberExpr *Member = nullptr; 4893 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4894 Member->isArrow()) 4895 Base = Member->getBase(); 4896 4897 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4898 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4899 LastRecord.PossibleDerefs.insert(E); 4900 } 4901 } 4902 4903 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4904 Expr *LowerBound, 4905 SourceLocation ColonLocFirst, 4906 SourceLocation ColonLocSecond, 4907 Expr *Length, Expr *Stride, 4908 SourceLocation RBLoc) { 4909 if (Base->getType()->isPlaceholderType() && 4910 !Base->getType()->isSpecificPlaceholderType( 4911 BuiltinType::OMPArraySection)) { 4912 ExprResult Result = CheckPlaceholderExpr(Base); 4913 if (Result.isInvalid()) 4914 return ExprError(); 4915 Base = Result.get(); 4916 } 4917 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4918 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4919 if (Result.isInvalid()) 4920 return ExprError(); 4921 Result = DefaultLvalueConversion(Result.get()); 4922 if (Result.isInvalid()) 4923 return ExprError(); 4924 LowerBound = Result.get(); 4925 } 4926 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4927 ExprResult Result = CheckPlaceholderExpr(Length); 4928 if (Result.isInvalid()) 4929 return ExprError(); 4930 Result = DefaultLvalueConversion(Result.get()); 4931 if (Result.isInvalid()) 4932 return ExprError(); 4933 Length = Result.get(); 4934 } 4935 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4936 ExprResult Result = CheckPlaceholderExpr(Stride); 4937 if (Result.isInvalid()) 4938 return ExprError(); 4939 Result = DefaultLvalueConversion(Result.get()); 4940 if (Result.isInvalid()) 4941 return ExprError(); 4942 Stride = Result.get(); 4943 } 4944 4945 // Build an unanalyzed expression if either operand is type-dependent. 4946 if (Base->isTypeDependent() || 4947 (LowerBound && 4948 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4949 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4950 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4951 return new (Context) OMPArraySectionExpr( 4952 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4953 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4954 } 4955 4956 // Perform default conversions. 4957 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4958 QualType ResultTy; 4959 if (OriginalTy->isAnyPointerType()) { 4960 ResultTy = OriginalTy->getPointeeType(); 4961 } else if (OriginalTy->isArrayType()) { 4962 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4963 } else { 4964 return ExprError( 4965 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4966 << Base->getSourceRange()); 4967 } 4968 // C99 6.5.2.1p1 4969 if (LowerBound) { 4970 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4971 LowerBound); 4972 if (Res.isInvalid()) 4973 return ExprError(Diag(LowerBound->getExprLoc(), 4974 diag::err_omp_typecheck_section_not_integer) 4975 << 0 << LowerBound->getSourceRange()); 4976 LowerBound = Res.get(); 4977 4978 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4979 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4980 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4981 << 0 << LowerBound->getSourceRange(); 4982 } 4983 if (Length) { 4984 auto Res = 4985 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4986 if (Res.isInvalid()) 4987 return ExprError(Diag(Length->getExprLoc(), 4988 diag::err_omp_typecheck_section_not_integer) 4989 << 1 << Length->getSourceRange()); 4990 Length = Res.get(); 4991 4992 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4993 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4994 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4995 << 1 << Length->getSourceRange(); 4996 } 4997 if (Stride) { 4998 ExprResult Res = 4999 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 5000 if (Res.isInvalid()) 5001 return ExprError(Diag(Stride->getExprLoc(), 5002 diag::err_omp_typecheck_section_not_integer) 5003 << 1 << Stride->getSourceRange()); 5004 Stride = Res.get(); 5005 5006 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5007 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5008 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5009 << 1 << Stride->getSourceRange(); 5010 } 5011 5012 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5013 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5014 // type. Note that functions are not objects, and that (in C99 parlance) 5015 // incomplete types are not object types. 5016 if (ResultTy->isFunctionType()) { 5017 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5018 << ResultTy << Base->getSourceRange(); 5019 return ExprError(); 5020 } 5021 5022 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5023 diag::err_omp_section_incomplete_type, Base)) 5024 return ExprError(); 5025 5026 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5027 Expr::EvalResult Result; 5028 if (LowerBound->EvaluateAsInt(Result, Context)) { 5029 // OpenMP 5.0, [2.1.5 Array Sections] 5030 // The array section must be a subset of the original array. 5031 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5032 if (LowerBoundValue.isNegative()) { 5033 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5034 << LowerBound->getSourceRange(); 5035 return ExprError(); 5036 } 5037 } 5038 } 5039 5040 if (Length) { 5041 Expr::EvalResult Result; 5042 if (Length->EvaluateAsInt(Result, Context)) { 5043 // OpenMP 5.0, [2.1.5 Array Sections] 5044 // The length must evaluate to non-negative integers. 5045 llvm::APSInt LengthValue = Result.Val.getInt(); 5046 if (LengthValue.isNegative()) { 5047 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5048 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5049 << Length->getSourceRange(); 5050 return ExprError(); 5051 } 5052 } 5053 } else if (ColonLocFirst.isValid() && 5054 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5055 !OriginalTy->isVariableArrayType()))) { 5056 // OpenMP 5.0, [2.1.5 Array Sections] 5057 // When the size of the array dimension is not known, the length must be 5058 // specified explicitly. 5059 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5060 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5061 return ExprError(); 5062 } 5063 5064 if (Stride) { 5065 Expr::EvalResult Result; 5066 if (Stride->EvaluateAsInt(Result, Context)) { 5067 // OpenMP 5.0, [2.1.5 Array Sections] 5068 // The stride must evaluate to a positive integer. 5069 llvm::APSInt StrideValue = Result.Val.getInt(); 5070 if (!StrideValue.isStrictlyPositive()) { 5071 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5072 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5073 << Stride->getSourceRange(); 5074 return ExprError(); 5075 } 5076 } 5077 } 5078 5079 if (!Base->getType()->isSpecificPlaceholderType( 5080 BuiltinType::OMPArraySection)) { 5081 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5082 if (Result.isInvalid()) 5083 return ExprError(); 5084 Base = Result.get(); 5085 } 5086 return new (Context) OMPArraySectionExpr( 5087 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5088 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5089 } 5090 5091 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5092 SourceLocation RParenLoc, 5093 ArrayRef<Expr *> Dims, 5094 ArrayRef<SourceRange> Brackets) { 5095 if (Base->getType()->isPlaceholderType()) { 5096 ExprResult Result = CheckPlaceholderExpr(Base); 5097 if (Result.isInvalid()) 5098 return ExprError(); 5099 Result = DefaultLvalueConversion(Result.get()); 5100 if (Result.isInvalid()) 5101 return ExprError(); 5102 Base = Result.get(); 5103 } 5104 QualType BaseTy = Base->getType(); 5105 // Delay analysis of the types/expressions if instantiation/specialization is 5106 // required. 5107 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5108 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5109 LParenLoc, RParenLoc, Dims, Brackets); 5110 if (!BaseTy->isPointerType() || 5111 (!Base->isTypeDependent() && 5112 BaseTy->getPointeeType()->isIncompleteType())) 5113 return ExprError(Diag(Base->getExprLoc(), 5114 diag::err_omp_non_pointer_type_array_shaping_base) 5115 << Base->getSourceRange()); 5116 5117 SmallVector<Expr *, 4> NewDims; 5118 bool ErrorFound = false; 5119 for (Expr *Dim : Dims) { 5120 if (Dim->getType()->isPlaceholderType()) { 5121 ExprResult Result = CheckPlaceholderExpr(Dim); 5122 if (Result.isInvalid()) { 5123 ErrorFound = true; 5124 continue; 5125 } 5126 Result = DefaultLvalueConversion(Result.get()); 5127 if (Result.isInvalid()) { 5128 ErrorFound = true; 5129 continue; 5130 } 5131 Dim = Result.get(); 5132 } 5133 if (!Dim->isTypeDependent()) { 5134 ExprResult Result = 5135 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5136 if (Result.isInvalid()) { 5137 ErrorFound = true; 5138 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5139 << Dim->getSourceRange(); 5140 continue; 5141 } 5142 Dim = Result.get(); 5143 Expr::EvalResult EvResult; 5144 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5145 // OpenMP 5.0, [2.1.4 Array Shaping] 5146 // Each si is an integral type expression that must evaluate to a 5147 // positive integer. 5148 llvm::APSInt Value = EvResult.Val.getInt(); 5149 if (!Value.isStrictlyPositive()) { 5150 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5151 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5152 << Dim->getSourceRange(); 5153 ErrorFound = true; 5154 continue; 5155 } 5156 } 5157 } 5158 NewDims.push_back(Dim); 5159 } 5160 if (ErrorFound) 5161 return ExprError(); 5162 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5163 LParenLoc, RParenLoc, NewDims, Brackets); 5164 } 5165 5166 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5167 SourceLocation LLoc, SourceLocation RLoc, 5168 ArrayRef<OMPIteratorData> Data) { 5169 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5170 bool IsCorrect = true; 5171 for (const OMPIteratorData &D : Data) { 5172 TypeSourceInfo *TInfo = nullptr; 5173 SourceLocation StartLoc; 5174 QualType DeclTy; 5175 if (!D.Type.getAsOpaquePtr()) { 5176 // OpenMP 5.0, 2.1.6 Iterators 5177 // In an iterator-specifier, if the iterator-type is not specified then 5178 // the type of that iterator is of int type. 5179 DeclTy = Context.IntTy; 5180 StartLoc = D.DeclIdentLoc; 5181 } else { 5182 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5183 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5184 } 5185 5186 bool IsDeclTyDependent = DeclTy->isDependentType() || 5187 DeclTy->containsUnexpandedParameterPack() || 5188 DeclTy->isInstantiationDependentType(); 5189 if (!IsDeclTyDependent) { 5190 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5191 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5192 // The iterator-type must be an integral or pointer type. 5193 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5194 << DeclTy; 5195 IsCorrect = false; 5196 continue; 5197 } 5198 if (DeclTy.isConstant(Context)) { 5199 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5200 // The iterator-type must not be const qualified. 5201 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5202 << DeclTy; 5203 IsCorrect = false; 5204 continue; 5205 } 5206 } 5207 5208 // Iterator declaration. 5209 assert(D.DeclIdent && "Identifier expected."); 5210 // Always try to create iterator declarator to avoid extra error messages 5211 // about unknown declarations use. 5212 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5213 D.DeclIdent, DeclTy, TInfo, SC_None); 5214 VD->setImplicit(); 5215 if (S) { 5216 // Check for conflicting previous declaration. 5217 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5218 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5219 ForVisibleRedeclaration); 5220 Previous.suppressDiagnostics(); 5221 LookupName(Previous, S); 5222 5223 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5224 /*AllowInlineNamespace=*/false); 5225 if (!Previous.empty()) { 5226 NamedDecl *Old = Previous.getRepresentativeDecl(); 5227 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5228 Diag(Old->getLocation(), diag::note_previous_definition); 5229 } else { 5230 PushOnScopeChains(VD, S); 5231 } 5232 } else { 5233 CurContext->addDecl(VD); 5234 } 5235 Expr *Begin = D.Range.Begin; 5236 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5237 ExprResult BeginRes = 5238 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5239 Begin = BeginRes.get(); 5240 } 5241 Expr *End = D.Range.End; 5242 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5243 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5244 End = EndRes.get(); 5245 } 5246 Expr *Step = D.Range.Step; 5247 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5248 if (!Step->getType()->isIntegralType(Context)) { 5249 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5250 << Step << Step->getSourceRange(); 5251 IsCorrect = false; 5252 continue; 5253 } 5254 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5255 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5256 // If the step expression of a range-specification equals zero, the 5257 // behavior is unspecified. 5258 if (Result && Result->isZero()) { 5259 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5260 << Step << Step->getSourceRange(); 5261 IsCorrect = false; 5262 continue; 5263 } 5264 } 5265 if (!Begin || !End || !IsCorrect) { 5266 IsCorrect = false; 5267 continue; 5268 } 5269 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5270 IDElem.IteratorDecl = VD; 5271 IDElem.AssignmentLoc = D.AssignLoc; 5272 IDElem.Range.Begin = Begin; 5273 IDElem.Range.End = End; 5274 IDElem.Range.Step = Step; 5275 IDElem.ColonLoc = D.ColonLoc; 5276 IDElem.SecondColonLoc = D.SecColonLoc; 5277 } 5278 if (!IsCorrect) { 5279 // Invalidate all created iterator declarations if error is found. 5280 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5281 if (Decl *ID = D.IteratorDecl) 5282 ID->setInvalidDecl(); 5283 } 5284 return ExprError(); 5285 } 5286 SmallVector<OMPIteratorHelperData, 4> Helpers; 5287 if (!CurContext->isDependentContext()) { 5288 // Build number of ityeration for each iteration range. 5289 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5290 // ((Begini-Stepi-1-Endi) / -Stepi); 5291 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5292 // (Endi - Begini) 5293 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5294 D.Range.Begin); 5295 if(!Res.isUsable()) { 5296 IsCorrect = false; 5297 continue; 5298 } 5299 ExprResult St, St1; 5300 if (D.Range.Step) { 5301 St = D.Range.Step; 5302 // (Endi - Begini) + Stepi 5303 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5304 if (!Res.isUsable()) { 5305 IsCorrect = false; 5306 continue; 5307 } 5308 // (Endi - Begini) + Stepi - 1 5309 Res = 5310 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5311 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5312 if (!Res.isUsable()) { 5313 IsCorrect = false; 5314 continue; 5315 } 5316 // ((Endi - Begini) + Stepi - 1) / Stepi 5317 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5318 if (!Res.isUsable()) { 5319 IsCorrect = false; 5320 continue; 5321 } 5322 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5323 // (Begini - Endi) 5324 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5325 D.Range.Begin, D.Range.End); 5326 if (!Res1.isUsable()) { 5327 IsCorrect = false; 5328 continue; 5329 } 5330 // (Begini - Endi) - Stepi 5331 Res1 = 5332 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5333 if (!Res1.isUsable()) { 5334 IsCorrect = false; 5335 continue; 5336 } 5337 // (Begini - Endi) - Stepi - 1 5338 Res1 = 5339 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5340 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5341 if (!Res1.isUsable()) { 5342 IsCorrect = false; 5343 continue; 5344 } 5345 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5346 Res1 = 5347 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5348 if (!Res1.isUsable()) { 5349 IsCorrect = false; 5350 continue; 5351 } 5352 // Stepi > 0. 5353 ExprResult CmpRes = 5354 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5355 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5356 if (!CmpRes.isUsable()) { 5357 IsCorrect = false; 5358 continue; 5359 } 5360 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5361 Res.get(), Res1.get()); 5362 if (!Res.isUsable()) { 5363 IsCorrect = false; 5364 continue; 5365 } 5366 } 5367 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5368 if (!Res.isUsable()) { 5369 IsCorrect = false; 5370 continue; 5371 } 5372 5373 // Build counter update. 5374 // Build counter. 5375 auto *CounterVD = 5376 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5377 D.IteratorDecl->getBeginLoc(), nullptr, 5378 Res.get()->getType(), nullptr, SC_None); 5379 CounterVD->setImplicit(); 5380 ExprResult RefRes = 5381 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5382 D.IteratorDecl->getBeginLoc()); 5383 // Build counter update. 5384 // I = Begini + counter * Stepi; 5385 ExprResult UpdateRes; 5386 if (D.Range.Step) { 5387 UpdateRes = CreateBuiltinBinOp( 5388 D.AssignmentLoc, BO_Mul, 5389 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5390 } else { 5391 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5392 } 5393 if (!UpdateRes.isUsable()) { 5394 IsCorrect = false; 5395 continue; 5396 } 5397 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5398 UpdateRes.get()); 5399 if (!UpdateRes.isUsable()) { 5400 IsCorrect = false; 5401 continue; 5402 } 5403 ExprResult VDRes = 5404 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5405 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5406 D.IteratorDecl->getBeginLoc()); 5407 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5408 UpdateRes.get()); 5409 if (!UpdateRes.isUsable()) { 5410 IsCorrect = false; 5411 continue; 5412 } 5413 UpdateRes = 5414 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5415 if (!UpdateRes.isUsable()) { 5416 IsCorrect = false; 5417 continue; 5418 } 5419 ExprResult CounterUpdateRes = 5420 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5421 if (!CounterUpdateRes.isUsable()) { 5422 IsCorrect = false; 5423 continue; 5424 } 5425 CounterUpdateRes = 5426 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5427 if (!CounterUpdateRes.isUsable()) { 5428 IsCorrect = false; 5429 continue; 5430 } 5431 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5432 HD.CounterVD = CounterVD; 5433 HD.Upper = Res.get(); 5434 HD.Update = UpdateRes.get(); 5435 HD.CounterUpdate = CounterUpdateRes.get(); 5436 } 5437 } else { 5438 Helpers.assign(ID.size(), {}); 5439 } 5440 if (!IsCorrect) { 5441 // Invalidate all created iterator declarations if error is found. 5442 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5443 if (Decl *ID = D.IteratorDecl) 5444 ID->setInvalidDecl(); 5445 } 5446 return ExprError(); 5447 } 5448 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5449 LLoc, RLoc, ID, Helpers); 5450 } 5451 5452 ExprResult 5453 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5454 Expr *Idx, SourceLocation RLoc) { 5455 Expr *LHSExp = Base; 5456 Expr *RHSExp = Idx; 5457 5458 ExprValueKind VK = VK_LValue; 5459 ExprObjectKind OK = OK_Ordinary; 5460 5461 // Per C++ core issue 1213, the result is an xvalue if either operand is 5462 // a non-lvalue array, and an lvalue otherwise. 5463 if (getLangOpts().CPlusPlus11) { 5464 for (auto *Op : {LHSExp, RHSExp}) { 5465 Op = Op->IgnoreImplicit(); 5466 if (Op->getType()->isArrayType() && !Op->isLValue()) 5467 VK = VK_XValue; 5468 } 5469 } 5470 5471 // Perform default conversions. 5472 if (!LHSExp->getType()->getAs<VectorType>()) { 5473 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5474 if (Result.isInvalid()) 5475 return ExprError(); 5476 LHSExp = Result.get(); 5477 } 5478 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5479 if (Result.isInvalid()) 5480 return ExprError(); 5481 RHSExp = Result.get(); 5482 5483 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5484 5485 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5486 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5487 // in the subscript position. As a result, we need to derive the array base 5488 // and index from the expression types. 5489 Expr *BaseExpr, *IndexExpr; 5490 QualType ResultType; 5491 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5492 BaseExpr = LHSExp; 5493 IndexExpr = RHSExp; 5494 ResultType = Context.DependentTy; 5495 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5496 BaseExpr = LHSExp; 5497 IndexExpr = RHSExp; 5498 ResultType = PTy->getPointeeType(); 5499 } else if (const ObjCObjectPointerType *PTy = 5500 LHSTy->getAs<ObjCObjectPointerType>()) { 5501 BaseExpr = LHSExp; 5502 IndexExpr = RHSExp; 5503 5504 // Use custom logic if this should be the pseudo-object subscript 5505 // expression. 5506 if (!LangOpts.isSubscriptPointerArithmetic()) 5507 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5508 nullptr); 5509 5510 ResultType = PTy->getPointeeType(); 5511 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5512 // Handle the uncommon case of "123[Ptr]". 5513 BaseExpr = RHSExp; 5514 IndexExpr = LHSExp; 5515 ResultType = PTy->getPointeeType(); 5516 } else if (const ObjCObjectPointerType *PTy = 5517 RHSTy->getAs<ObjCObjectPointerType>()) { 5518 // Handle the uncommon case of "123[Ptr]". 5519 BaseExpr = RHSExp; 5520 IndexExpr = LHSExp; 5521 ResultType = PTy->getPointeeType(); 5522 if (!LangOpts.isSubscriptPointerArithmetic()) { 5523 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5524 << ResultType << BaseExpr->getSourceRange(); 5525 return ExprError(); 5526 } 5527 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5528 BaseExpr = LHSExp; // vectors: V[123] 5529 IndexExpr = RHSExp; 5530 // We apply C++ DR1213 to vector subscripting too. 5531 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5532 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5533 if (Materialized.isInvalid()) 5534 return ExprError(); 5535 LHSExp = Materialized.get(); 5536 } 5537 VK = LHSExp->getValueKind(); 5538 if (VK != VK_PRValue) 5539 OK = OK_VectorComponent; 5540 5541 ResultType = VTy->getElementType(); 5542 QualType BaseType = BaseExpr->getType(); 5543 Qualifiers BaseQuals = BaseType.getQualifiers(); 5544 Qualifiers MemberQuals = ResultType.getQualifiers(); 5545 Qualifiers Combined = BaseQuals + MemberQuals; 5546 if (Combined != MemberQuals) 5547 ResultType = Context.getQualifiedType(ResultType, Combined); 5548 } else if (LHSTy->isArrayType()) { 5549 // If we see an array that wasn't promoted by 5550 // DefaultFunctionArrayLvalueConversion, it must be an array that 5551 // wasn't promoted because of the C90 rule that doesn't 5552 // allow promoting non-lvalue arrays. Warn, then 5553 // force the promotion here. 5554 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5555 << LHSExp->getSourceRange(); 5556 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5557 CK_ArrayToPointerDecay).get(); 5558 LHSTy = LHSExp->getType(); 5559 5560 BaseExpr = LHSExp; 5561 IndexExpr = RHSExp; 5562 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5563 } else if (RHSTy->isArrayType()) { 5564 // Same as previous, except for 123[f().a] case 5565 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5566 << RHSExp->getSourceRange(); 5567 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5568 CK_ArrayToPointerDecay).get(); 5569 RHSTy = RHSExp->getType(); 5570 5571 BaseExpr = RHSExp; 5572 IndexExpr = LHSExp; 5573 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5574 } else { 5575 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5576 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5577 } 5578 // C99 6.5.2.1p1 5579 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5580 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5581 << IndexExpr->getSourceRange()); 5582 5583 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5584 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5585 && !IndexExpr->isTypeDependent()) 5586 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5587 5588 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5589 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5590 // type. Note that Functions are not objects, and that (in C99 parlance) 5591 // incomplete types are not object types. 5592 if (ResultType->isFunctionType()) { 5593 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5594 << ResultType << BaseExpr->getSourceRange(); 5595 return ExprError(); 5596 } 5597 5598 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5599 // GNU extension: subscripting on pointer to void 5600 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5601 << BaseExpr->getSourceRange(); 5602 5603 // C forbids expressions of unqualified void type from being l-values. 5604 // See IsCForbiddenLValueType. 5605 if (!ResultType.hasQualifiers()) 5606 VK = VK_PRValue; 5607 } else if (!ResultType->isDependentType() && 5608 RequireCompleteSizedType( 5609 LLoc, ResultType, 5610 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5611 return ExprError(); 5612 5613 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 5614 !ResultType.isCForbiddenLValueType()); 5615 5616 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5617 FunctionScopes.size() > 1) { 5618 if (auto *TT = 5619 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5620 for (auto I = FunctionScopes.rbegin(), 5621 E = std::prev(FunctionScopes.rend()); 5622 I != E; ++I) { 5623 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5624 if (CSI == nullptr) 5625 break; 5626 DeclContext *DC = nullptr; 5627 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5628 DC = LSI->CallOperator; 5629 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5630 DC = CRSI->TheCapturedDecl; 5631 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5632 DC = BSI->TheDecl; 5633 if (DC) { 5634 if (DC->containsDecl(TT->getDecl())) 5635 break; 5636 captureVariablyModifiedType( 5637 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5638 } 5639 } 5640 } 5641 } 5642 5643 return new (Context) 5644 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5645 } 5646 5647 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5648 ParmVarDecl *Param) { 5649 if (Param->hasUnparsedDefaultArg()) { 5650 // If we've already cleared out the location for the default argument, 5651 // that means we're parsing it right now. 5652 if (!UnparsedDefaultArgLocs.count(Param)) { 5653 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5654 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5655 Param->setInvalidDecl(); 5656 return true; 5657 } 5658 5659 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5660 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5661 Diag(UnparsedDefaultArgLocs[Param], 5662 diag::note_default_argument_declared_here); 5663 return true; 5664 } 5665 5666 if (Param->hasUninstantiatedDefaultArg() && 5667 InstantiateDefaultArgument(CallLoc, FD, Param)) 5668 return true; 5669 5670 assert(Param->hasInit() && "default argument but no initializer?"); 5671 5672 // If the default expression creates temporaries, we need to 5673 // push them to the current stack of expression temporaries so they'll 5674 // be properly destroyed. 5675 // FIXME: We should really be rebuilding the default argument with new 5676 // bound temporaries; see the comment in PR5810. 5677 // We don't need to do that with block decls, though, because 5678 // blocks in default argument expression can never capture anything. 5679 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5680 // Set the "needs cleanups" bit regardless of whether there are 5681 // any explicit objects. 5682 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5683 5684 // Append all the objects to the cleanup list. Right now, this 5685 // should always be a no-op, because blocks in default argument 5686 // expressions should never be able to capture anything. 5687 assert(!Init->getNumObjects() && 5688 "default argument expression has capturing blocks?"); 5689 } 5690 5691 // We already type-checked the argument, so we know it works. 5692 // Just mark all of the declarations in this potentially-evaluated expression 5693 // as being "referenced". 5694 EnterExpressionEvaluationContext EvalContext( 5695 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5696 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5697 /*SkipLocalVariables=*/true); 5698 return false; 5699 } 5700 5701 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5702 FunctionDecl *FD, ParmVarDecl *Param) { 5703 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5704 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5705 return ExprError(); 5706 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5707 } 5708 5709 Sema::VariadicCallType 5710 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5711 Expr *Fn) { 5712 if (Proto && Proto->isVariadic()) { 5713 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5714 return VariadicConstructor; 5715 else if (Fn && Fn->getType()->isBlockPointerType()) 5716 return VariadicBlock; 5717 else if (FDecl) { 5718 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5719 if (Method->isInstance()) 5720 return VariadicMethod; 5721 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5722 return VariadicMethod; 5723 return VariadicFunction; 5724 } 5725 return VariadicDoesNotApply; 5726 } 5727 5728 namespace { 5729 class FunctionCallCCC final : public FunctionCallFilterCCC { 5730 public: 5731 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5732 unsigned NumArgs, MemberExpr *ME) 5733 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5734 FunctionName(FuncName) {} 5735 5736 bool ValidateCandidate(const TypoCorrection &candidate) override { 5737 if (!candidate.getCorrectionSpecifier() || 5738 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5739 return false; 5740 } 5741 5742 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5743 } 5744 5745 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5746 return std::make_unique<FunctionCallCCC>(*this); 5747 } 5748 5749 private: 5750 const IdentifierInfo *const FunctionName; 5751 }; 5752 } 5753 5754 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5755 FunctionDecl *FDecl, 5756 ArrayRef<Expr *> Args) { 5757 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5758 DeclarationName FuncName = FDecl->getDeclName(); 5759 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5760 5761 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5762 if (TypoCorrection Corrected = S.CorrectTypo( 5763 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5764 S.getScopeForContext(S.CurContext), nullptr, CCC, 5765 Sema::CTK_ErrorRecovery)) { 5766 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5767 if (Corrected.isOverloaded()) { 5768 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5769 OverloadCandidateSet::iterator Best; 5770 for (NamedDecl *CD : Corrected) { 5771 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5772 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5773 OCS); 5774 } 5775 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5776 case OR_Success: 5777 ND = Best->FoundDecl; 5778 Corrected.setCorrectionDecl(ND); 5779 break; 5780 default: 5781 break; 5782 } 5783 } 5784 ND = ND->getUnderlyingDecl(); 5785 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5786 return Corrected; 5787 } 5788 } 5789 return TypoCorrection(); 5790 } 5791 5792 /// ConvertArgumentsForCall - Converts the arguments specified in 5793 /// Args/NumArgs to the parameter types of the function FDecl with 5794 /// function prototype Proto. Call is the call expression itself, and 5795 /// Fn is the function expression. For a C++ member function, this 5796 /// routine does not attempt to convert the object argument. Returns 5797 /// true if the call is ill-formed. 5798 bool 5799 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5800 FunctionDecl *FDecl, 5801 const FunctionProtoType *Proto, 5802 ArrayRef<Expr *> Args, 5803 SourceLocation RParenLoc, 5804 bool IsExecConfig) { 5805 // Bail out early if calling a builtin with custom typechecking. 5806 if (FDecl) 5807 if (unsigned ID = FDecl->getBuiltinID()) 5808 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5809 return false; 5810 5811 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5812 // assignment, to the types of the corresponding parameter, ... 5813 unsigned NumParams = Proto->getNumParams(); 5814 bool Invalid = false; 5815 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5816 unsigned FnKind = Fn->getType()->isBlockPointerType() 5817 ? 1 /* block */ 5818 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5819 : 0 /* function */); 5820 5821 // If too few arguments are available (and we don't have default 5822 // arguments for the remaining parameters), don't make the call. 5823 if (Args.size() < NumParams) { 5824 if (Args.size() < MinArgs) { 5825 TypoCorrection TC; 5826 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5827 unsigned diag_id = 5828 MinArgs == NumParams && !Proto->isVariadic() 5829 ? diag::err_typecheck_call_too_few_args_suggest 5830 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5831 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5832 << static_cast<unsigned>(Args.size()) 5833 << TC.getCorrectionRange()); 5834 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5835 Diag(RParenLoc, 5836 MinArgs == NumParams && !Proto->isVariadic() 5837 ? diag::err_typecheck_call_too_few_args_one 5838 : diag::err_typecheck_call_too_few_args_at_least_one) 5839 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5840 else 5841 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5842 ? diag::err_typecheck_call_too_few_args 5843 : diag::err_typecheck_call_too_few_args_at_least) 5844 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5845 << Fn->getSourceRange(); 5846 5847 // Emit the location of the prototype. 5848 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5849 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5850 5851 return true; 5852 } 5853 // We reserve space for the default arguments when we create 5854 // the call expression, before calling ConvertArgumentsForCall. 5855 assert((Call->getNumArgs() == NumParams) && 5856 "We should have reserved space for the default arguments before!"); 5857 } 5858 5859 // If too many are passed and not variadic, error on the extras and drop 5860 // them. 5861 if (Args.size() > NumParams) { 5862 if (!Proto->isVariadic()) { 5863 TypoCorrection TC; 5864 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5865 unsigned diag_id = 5866 MinArgs == NumParams && !Proto->isVariadic() 5867 ? diag::err_typecheck_call_too_many_args_suggest 5868 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5869 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5870 << static_cast<unsigned>(Args.size()) 5871 << TC.getCorrectionRange()); 5872 } else if (NumParams == 1 && FDecl && 5873 FDecl->getParamDecl(0)->getDeclName()) 5874 Diag(Args[NumParams]->getBeginLoc(), 5875 MinArgs == NumParams 5876 ? diag::err_typecheck_call_too_many_args_one 5877 : diag::err_typecheck_call_too_many_args_at_most_one) 5878 << FnKind << FDecl->getParamDecl(0) 5879 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5880 << SourceRange(Args[NumParams]->getBeginLoc(), 5881 Args.back()->getEndLoc()); 5882 else 5883 Diag(Args[NumParams]->getBeginLoc(), 5884 MinArgs == NumParams 5885 ? diag::err_typecheck_call_too_many_args 5886 : diag::err_typecheck_call_too_many_args_at_most) 5887 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5888 << Fn->getSourceRange() 5889 << SourceRange(Args[NumParams]->getBeginLoc(), 5890 Args.back()->getEndLoc()); 5891 5892 // Emit the location of the prototype. 5893 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5894 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5895 5896 // This deletes the extra arguments. 5897 Call->shrinkNumArgs(NumParams); 5898 return true; 5899 } 5900 } 5901 SmallVector<Expr *, 8> AllArgs; 5902 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5903 5904 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5905 AllArgs, CallType); 5906 if (Invalid) 5907 return true; 5908 unsigned TotalNumArgs = AllArgs.size(); 5909 for (unsigned i = 0; i < TotalNumArgs; ++i) 5910 Call->setArg(i, AllArgs[i]); 5911 5912 Call->computeDependence(); 5913 return false; 5914 } 5915 5916 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5917 const FunctionProtoType *Proto, 5918 unsigned FirstParam, ArrayRef<Expr *> Args, 5919 SmallVectorImpl<Expr *> &AllArgs, 5920 VariadicCallType CallType, bool AllowExplicit, 5921 bool IsListInitialization) { 5922 unsigned NumParams = Proto->getNumParams(); 5923 bool Invalid = false; 5924 size_t ArgIx = 0; 5925 // Continue to check argument types (even if we have too few/many args). 5926 for (unsigned i = FirstParam; i < NumParams; i++) { 5927 QualType ProtoArgType = Proto->getParamType(i); 5928 5929 Expr *Arg; 5930 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5931 if (ArgIx < Args.size()) { 5932 Arg = Args[ArgIx++]; 5933 5934 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5935 diag::err_call_incomplete_argument, Arg)) 5936 return true; 5937 5938 // Strip the unbridged-cast placeholder expression off, if applicable. 5939 bool CFAudited = false; 5940 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5941 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5942 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5943 Arg = stripARCUnbridgedCast(Arg); 5944 else if (getLangOpts().ObjCAutoRefCount && 5945 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5946 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5947 CFAudited = true; 5948 5949 if (Proto->getExtParameterInfo(i).isNoEscape() && 5950 ProtoArgType->isBlockPointerType()) 5951 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5952 BE->getBlockDecl()->setDoesNotEscape(); 5953 5954 InitializedEntity Entity = 5955 Param ? InitializedEntity::InitializeParameter(Context, Param, 5956 ProtoArgType) 5957 : InitializedEntity::InitializeParameter( 5958 Context, ProtoArgType, Proto->isParamConsumed(i)); 5959 5960 // Remember that parameter belongs to a CF audited API. 5961 if (CFAudited) 5962 Entity.setParameterCFAudited(); 5963 5964 ExprResult ArgE = PerformCopyInitialization( 5965 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5966 if (ArgE.isInvalid()) 5967 return true; 5968 5969 Arg = ArgE.getAs<Expr>(); 5970 } else { 5971 assert(Param && "can't use default arguments without a known callee"); 5972 5973 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5974 if (ArgExpr.isInvalid()) 5975 return true; 5976 5977 Arg = ArgExpr.getAs<Expr>(); 5978 } 5979 5980 // Check for array bounds violations for each argument to the call. This 5981 // check only triggers warnings when the argument isn't a more complex Expr 5982 // with its own checking, such as a BinaryOperator. 5983 CheckArrayAccess(Arg); 5984 5985 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5986 CheckStaticArrayArgument(CallLoc, Param, Arg); 5987 5988 AllArgs.push_back(Arg); 5989 } 5990 5991 // If this is a variadic call, handle args passed through "...". 5992 if (CallType != VariadicDoesNotApply) { 5993 // Assume that extern "C" functions with variadic arguments that 5994 // return __unknown_anytype aren't *really* variadic. 5995 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5996 FDecl->isExternC()) { 5997 for (Expr *A : Args.slice(ArgIx)) { 5998 QualType paramType; // ignored 5999 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 6000 Invalid |= arg.isInvalid(); 6001 AllArgs.push_back(arg.get()); 6002 } 6003 6004 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6005 } else { 6006 for (Expr *A : Args.slice(ArgIx)) { 6007 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6008 Invalid |= Arg.isInvalid(); 6009 AllArgs.push_back(Arg.get()); 6010 } 6011 } 6012 6013 // Check for array bounds violations. 6014 for (Expr *A : Args.slice(ArgIx)) 6015 CheckArrayAccess(A); 6016 } 6017 return Invalid; 6018 } 6019 6020 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6021 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6022 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6023 TL = DTL.getOriginalLoc(); 6024 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6025 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6026 << ATL.getLocalSourceRange(); 6027 } 6028 6029 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6030 /// array parameter, check that it is non-null, and that if it is formed by 6031 /// array-to-pointer decay, the underlying array is sufficiently large. 6032 /// 6033 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6034 /// array type derivation, then for each call to the function, the value of the 6035 /// corresponding actual argument shall provide access to the first element of 6036 /// an array with at least as many elements as specified by the size expression. 6037 void 6038 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6039 ParmVarDecl *Param, 6040 const Expr *ArgExpr) { 6041 // Static array parameters are not supported in C++. 6042 if (!Param || getLangOpts().CPlusPlus) 6043 return; 6044 6045 QualType OrigTy = Param->getOriginalType(); 6046 6047 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6048 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6049 return; 6050 6051 if (ArgExpr->isNullPointerConstant(Context, 6052 Expr::NPC_NeverValueDependent)) { 6053 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6054 DiagnoseCalleeStaticArrayParam(*this, Param); 6055 return; 6056 } 6057 6058 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6059 if (!CAT) 6060 return; 6061 6062 const ConstantArrayType *ArgCAT = 6063 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6064 if (!ArgCAT) 6065 return; 6066 6067 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6068 ArgCAT->getElementType())) { 6069 if (ArgCAT->getSize().ult(CAT->getSize())) { 6070 Diag(CallLoc, diag::warn_static_array_too_small) 6071 << ArgExpr->getSourceRange() 6072 << (unsigned)ArgCAT->getSize().getZExtValue() 6073 << (unsigned)CAT->getSize().getZExtValue() << 0; 6074 DiagnoseCalleeStaticArrayParam(*this, Param); 6075 } 6076 return; 6077 } 6078 6079 Optional<CharUnits> ArgSize = 6080 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6081 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6082 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6083 Diag(CallLoc, diag::warn_static_array_too_small) 6084 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6085 << (unsigned)ParmSize->getQuantity() << 1; 6086 DiagnoseCalleeStaticArrayParam(*this, Param); 6087 } 6088 } 6089 6090 /// Given a function expression of unknown-any type, try to rebuild it 6091 /// to have a function type. 6092 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6093 6094 /// Is the given type a placeholder that we need to lower out 6095 /// immediately during argument processing? 6096 static bool isPlaceholderToRemoveAsArg(QualType type) { 6097 // Placeholders are never sugared. 6098 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6099 if (!placeholder) return false; 6100 6101 switch (placeholder->getKind()) { 6102 // Ignore all the non-placeholder types. 6103 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6104 case BuiltinType::Id: 6105 #include "clang/Basic/OpenCLImageTypes.def" 6106 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6107 case BuiltinType::Id: 6108 #include "clang/Basic/OpenCLExtensionTypes.def" 6109 // In practice we'll never use this, since all SVE types are sugared 6110 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6111 #define SVE_TYPE(Name, Id, SingletonId) \ 6112 case BuiltinType::Id: 6113 #include "clang/Basic/AArch64SVEACLETypes.def" 6114 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6115 case BuiltinType::Id: 6116 #include "clang/Basic/PPCTypes.def" 6117 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6118 #include "clang/Basic/RISCVVTypes.def" 6119 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6120 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6121 #include "clang/AST/BuiltinTypes.def" 6122 return false; 6123 6124 // We cannot lower out overload sets; they might validly be resolved 6125 // by the call machinery. 6126 case BuiltinType::Overload: 6127 return false; 6128 6129 // Unbridged casts in ARC can be handled in some call positions and 6130 // should be left in place. 6131 case BuiltinType::ARCUnbridgedCast: 6132 return false; 6133 6134 // Pseudo-objects should be converted as soon as possible. 6135 case BuiltinType::PseudoObject: 6136 return true; 6137 6138 // The debugger mode could theoretically but currently does not try 6139 // to resolve unknown-typed arguments based on known parameter types. 6140 case BuiltinType::UnknownAny: 6141 return true; 6142 6143 // These are always invalid as call arguments and should be reported. 6144 case BuiltinType::BoundMember: 6145 case BuiltinType::BuiltinFn: 6146 case BuiltinType::IncompleteMatrixIdx: 6147 case BuiltinType::OMPArraySection: 6148 case BuiltinType::OMPArrayShaping: 6149 case BuiltinType::OMPIterator: 6150 return true; 6151 6152 } 6153 llvm_unreachable("bad builtin type kind"); 6154 } 6155 6156 /// Check an argument list for placeholders that we won't try to 6157 /// handle later. 6158 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6159 // Apply this processing to all the arguments at once instead of 6160 // dying at the first failure. 6161 bool hasInvalid = false; 6162 for (size_t i = 0, e = args.size(); i != e; i++) { 6163 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6164 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6165 if (result.isInvalid()) hasInvalid = true; 6166 else args[i] = result.get(); 6167 } 6168 } 6169 return hasInvalid; 6170 } 6171 6172 /// If a builtin function has a pointer argument with no explicit address 6173 /// space, then it should be able to accept a pointer to any address 6174 /// space as input. In order to do this, we need to replace the 6175 /// standard builtin declaration with one that uses the same address space 6176 /// as the call. 6177 /// 6178 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6179 /// it does not contain any pointer arguments without 6180 /// an address space qualifer. Otherwise the rewritten 6181 /// FunctionDecl is returned. 6182 /// TODO: Handle pointer return types. 6183 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6184 FunctionDecl *FDecl, 6185 MultiExprArg ArgExprs) { 6186 6187 QualType DeclType = FDecl->getType(); 6188 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6189 6190 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6191 ArgExprs.size() < FT->getNumParams()) 6192 return nullptr; 6193 6194 bool NeedsNewDecl = false; 6195 unsigned i = 0; 6196 SmallVector<QualType, 8> OverloadParams; 6197 6198 for (QualType ParamType : FT->param_types()) { 6199 6200 // Convert array arguments to pointer to simplify type lookup. 6201 ExprResult ArgRes = 6202 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6203 if (ArgRes.isInvalid()) 6204 return nullptr; 6205 Expr *Arg = ArgRes.get(); 6206 QualType ArgType = Arg->getType(); 6207 if (!ParamType->isPointerType() || 6208 ParamType.hasAddressSpace() || 6209 !ArgType->isPointerType() || 6210 !ArgType->getPointeeType().hasAddressSpace()) { 6211 OverloadParams.push_back(ParamType); 6212 continue; 6213 } 6214 6215 QualType PointeeType = ParamType->getPointeeType(); 6216 if (PointeeType.hasAddressSpace()) 6217 continue; 6218 6219 NeedsNewDecl = true; 6220 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6221 6222 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6223 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6224 } 6225 6226 if (!NeedsNewDecl) 6227 return nullptr; 6228 6229 FunctionProtoType::ExtProtoInfo EPI; 6230 EPI.Variadic = FT->isVariadic(); 6231 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6232 OverloadParams, EPI); 6233 DeclContext *Parent = FDecl->getParent(); 6234 FunctionDecl *OverloadDecl = FunctionDecl::Create( 6235 Context, Parent, FDecl->getLocation(), FDecl->getLocation(), 6236 FDecl->getIdentifier(), OverloadTy, 6237 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), 6238 false, 6239 /*hasPrototype=*/true); 6240 SmallVector<ParmVarDecl*, 16> Params; 6241 FT = cast<FunctionProtoType>(OverloadTy); 6242 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6243 QualType ParamType = FT->getParamType(i); 6244 ParmVarDecl *Parm = 6245 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6246 SourceLocation(), nullptr, ParamType, 6247 /*TInfo=*/nullptr, SC_None, nullptr); 6248 Parm->setScopeInfo(0, i); 6249 Params.push_back(Parm); 6250 } 6251 OverloadDecl->setParams(Params); 6252 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6253 return OverloadDecl; 6254 } 6255 6256 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6257 FunctionDecl *Callee, 6258 MultiExprArg ArgExprs) { 6259 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6260 // similar attributes) really don't like it when functions are called with an 6261 // invalid number of args. 6262 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6263 /*PartialOverloading=*/false) && 6264 !Callee->isVariadic()) 6265 return; 6266 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6267 return; 6268 6269 if (const EnableIfAttr *Attr = 6270 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6271 S.Diag(Fn->getBeginLoc(), 6272 isa<CXXMethodDecl>(Callee) 6273 ? diag::err_ovl_no_viable_member_function_in_call 6274 : diag::err_ovl_no_viable_function_in_call) 6275 << Callee << Callee->getSourceRange(); 6276 S.Diag(Callee->getLocation(), 6277 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6278 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6279 return; 6280 } 6281 } 6282 6283 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6284 const UnresolvedMemberExpr *const UME, Sema &S) { 6285 6286 const auto GetFunctionLevelDCIfCXXClass = 6287 [](Sema &S) -> const CXXRecordDecl * { 6288 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6289 if (!DC || !DC->getParent()) 6290 return nullptr; 6291 6292 // If the call to some member function was made from within a member 6293 // function body 'M' return return 'M's parent. 6294 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6295 return MD->getParent()->getCanonicalDecl(); 6296 // else the call was made from within a default member initializer of a 6297 // class, so return the class. 6298 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6299 return RD->getCanonicalDecl(); 6300 return nullptr; 6301 }; 6302 // If our DeclContext is neither a member function nor a class (in the 6303 // case of a lambda in a default member initializer), we can't have an 6304 // enclosing 'this'. 6305 6306 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6307 if (!CurParentClass) 6308 return false; 6309 6310 // The naming class for implicit member functions call is the class in which 6311 // name lookup starts. 6312 const CXXRecordDecl *const NamingClass = 6313 UME->getNamingClass()->getCanonicalDecl(); 6314 assert(NamingClass && "Must have naming class even for implicit access"); 6315 6316 // If the unresolved member functions were found in a 'naming class' that is 6317 // related (either the same or derived from) to the class that contains the 6318 // member function that itself contained the implicit member access. 6319 6320 return CurParentClass == NamingClass || 6321 CurParentClass->isDerivedFrom(NamingClass); 6322 } 6323 6324 static void 6325 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6326 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6327 6328 if (!UME) 6329 return; 6330 6331 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6332 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6333 // already been captured, or if this is an implicit member function call (if 6334 // it isn't, an attempt to capture 'this' should already have been made). 6335 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6336 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6337 return; 6338 6339 // Check if the naming class in which the unresolved members were found is 6340 // related (same as or is a base of) to the enclosing class. 6341 6342 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6343 return; 6344 6345 6346 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6347 // If the enclosing function is not dependent, then this lambda is 6348 // capture ready, so if we can capture this, do so. 6349 if (!EnclosingFunctionCtx->isDependentContext()) { 6350 // If the current lambda and all enclosing lambdas can capture 'this' - 6351 // then go ahead and capture 'this' (since our unresolved overload set 6352 // contains at least one non-static member function). 6353 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6354 S.CheckCXXThisCapture(CallLoc); 6355 } else if (S.CurContext->isDependentContext()) { 6356 // ... since this is an implicit member reference, that might potentially 6357 // involve a 'this' capture, mark 'this' for potential capture in 6358 // enclosing lambdas. 6359 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6360 CurLSI->addPotentialThisCapture(CallLoc); 6361 } 6362 } 6363 6364 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6365 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6366 Expr *ExecConfig) { 6367 ExprResult Call = 6368 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6369 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6370 if (Call.isInvalid()) 6371 return Call; 6372 6373 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6374 // language modes. 6375 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6376 if (ULE->hasExplicitTemplateArgs() && 6377 ULE->decls_begin() == ULE->decls_end()) { 6378 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6379 ? diag::warn_cxx17_compat_adl_only_template_id 6380 : diag::ext_adl_only_template_id) 6381 << ULE->getName(); 6382 } 6383 } 6384 6385 if (LangOpts.OpenMP) 6386 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6387 ExecConfig); 6388 6389 return Call; 6390 } 6391 6392 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6393 /// This provides the location of the left/right parens and a list of comma 6394 /// locations. 6395 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6396 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6397 Expr *ExecConfig, bool IsExecConfig, 6398 bool AllowRecovery) { 6399 // Since this might be a postfix expression, get rid of ParenListExprs. 6400 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6401 if (Result.isInvalid()) return ExprError(); 6402 Fn = Result.get(); 6403 6404 if (checkArgsForPlaceholders(*this, ArgExprs)) 6405 return ExprError(); 6406 6407 if (getLangOpts().CPlusPlus) { 6408 // If this is a pseudo-destructor expression, build the call immediately. 6409 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6410 if (!ArgExprs.empty()) { 6411 // Pseudo-destructor calls should not have any arguments. 6412 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6413 << FixItHint::CreateRemoval( 6414 SourceRange(ArgExprs.front()->getBeginLoc(), 6415 ArgExprs.back()->getEndLoc())); 6416 } 6417 6418 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6419 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6420 } 6421 if (Fn->getType() == Context.PseudoObjectTy) { 6422 ExprResult result = CheckPlaceholderExpr(Fn); 6423 if (result.isInvalid()) return ExprError(); 6424 Fn = result.get(); 6425 } 6426 6427 // Determine whether this is a dependent call inside a C++ template, 6428 // in which case we won't do any semantic analysis now. 6429 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6430 if (ExecConfig) { 6431 return CUDAKernelCallExpr::Create(Context, Fn, 6432 cast<CallExpr>(ExecConfig), ArgExprs, 6433 Context.DependentTy, VK_PRValue, 6434 RParenLoc, CurFPFeatureOverrides()); 6435 } else { 6436 6437 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6438 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6439 Fn->getBeginLoc()); 6440 6441 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6442 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6443 } 6444 } 6445 6446 // Determine whether this is a call to an object (C++ [over.call.object]). 6447 if (Fn->getType()->isRecordType()) 6448 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6449 RParenLoc); 6450 6451 if (Fn->getType() == Context.UnknownAnyTy) { 6452 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6453 if (result.isInvalid()) return ExprError(); 6454 Fn = result.get(); 6455 } 6456 6457 if (Fn->getType() == Context.BoundMemberTy) { 6458 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6459 RParenLoc, ExecConfig, IsExecConfig, 6460 AllowRecovery); 6461 } 6462 } 6463 6464 // Check for overloaded calls. This can happen even in C due to extensions. 6465 if (Fn->getType() == Context.OverloadTy) { 6466 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6467 6468 // We aren't supposed to apply this logic if there's an '&' involved. 6469 if (!find.HasFormOfMemberPointer) { 6470 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6471 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6472 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6473 OverloadExpr *ovl = find.Expression; 6474 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6475 return BuildOverloadedCallExpr( 6476 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6477 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6478 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6479 RParenLoc, ExecConfig, IsExecConfig, 6480 AllowRecovery); 6481 } 6482 } 6483 6484 // If we're directly calling a function, get the appropriate declaration. 6485 if (Fn->getType() == Context.UnknownAnyTy) { 6486 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6487 if (result.isInvalid()) return ExprError(); 6488 Fn = result.get(); 6489 } 6490 6491 Expr *NakedFn = Fn->IgnoreParens(); 6492 6493 bool CallingNDeclIndirectly = false; 6494 NamedDecl *NDecl = nullptr; 6495 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6496 if (UnOp->getOpcode() == UO_AddrOf) { 6497 CallingNDeclIndirectly = true; 6498 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6499 } 6500 } 6501 6502 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6503 NDecl = DRE->getDecl(); 6504 6505 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6506 if (FDecl && FDecl->getBuiltinID()) { 6507 // Rewrite the function decl for this builtin by replacing parameters 6508 // with no explicit address space with the address space of the arguments 6509 // in ArgExprs. 6510 if ((FDecl = 6511 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6512 NDecl = FDecl; 6513 Fn = DeclRefExpr::Create( 6514 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6515 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6516 nullptr, DRE->isNonOdrUse()); 6517 } 6518 } 6519 } else if (isa<MemberExpr>(NakedFn)) 6520 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6521 6522 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6523 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6524 FD, /*Complain=*/true, Fn->getBeginLoc())) 6525 return ExprError(); 6526 6527 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6528 6529 // If this expression is a call to a builtin function in HIP device 6530 // compilation, allow a pointer-type argument to default address space to be 6531 // passed as a pointer-type parameter to a non-default address space. 6532 // If Arg is declared in the default address space and Param is declared 6533 // in a non-default address space, perform an implicit address space cast to 6534 // the parameter type. 6535 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && 6536 FD->getBuiltinID()) { 6537 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) { 6538 ParmVarDecl *Param = FD->getParamDecl(Idx); 6539 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || 6540 !ArgExprs[Idx]->getType()->isPointerType()) 6541 continue; 6542 6543 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); 6544 auto ArgTy = ArgExprs[Idx]->getType(); 6545 auto ArgPtTy = ArgTy->getPointeeType(); 6546 auto ArgAS = ArgPtTy.getAddressSpace(); 6547 6548 // Add address space cast if target address spaces are different 6549 bool NeedImplicitASC = 6550 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling. 6551 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS 6552 // or from specific AS which has target AS matching that of Param. 6553 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS)); 6554 if (!NeedImplicitASC) 6555 continue; 6556 6557 // First, ensure that the Arg is an RValue. 6558 if (ArgExprs[Idx]->isGLValue()) { 6559 ArgExprs[Idx] = ImplicitCastExpr::Create( 6560 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx], 6561 nullptr, VK_PRValue, FPOptionsOverride()); 6562 } 6563 6564 // Construct a new arg type with address space of Param 6565 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); 6566 ArgPtQuals.setAddressSpace(ParamAS); 6567 auto NewArgPtTy = 6568 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); 6569 auto NewArgTy = 6570 Context.getQualifiedType(Context.getPointerType(NewArgPtTy), 6571 ArgTy.getQualifiers()); 6572 6573 // Finally perform an implicit address space cast 6574 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, 6575 CK_AddressSpaceConversion) 6576 .get(); 6577 } 6578 } 6579 } 6580 6581 if (Context.isDependenceAllowed() && 6582 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6583 assert(!getLangOpts().CPlusPlus); 6584 assert((Fn->containsErrors() || 6585 llvm::any_of(ArgExprs, 6586 [](clang::Expr *E) { return E->containsErrors(); })) && 6587 "should only occur in error-recovery path."); 6588 QualType ReturnType = 6589 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6590 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6591 : Context.DependentTy; 6592 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6593 Expr::getValueKindForType(ReturnType), RParenLoc, 6594 CurFPFeatureOverrides()); 6595 } 6596 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6597 ExecConfig, IsExecConfig); 6598 } 6599 6600 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id 6601 // with the specified CallArgs 6602 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 6603 MultiExprArg CallArgs) { 6604 StringRef Name = Context.BuiltinInfo.getName(Id); 6605 LookupResult R(*this, &Context.Idents.get(Name), Loc, 6606 Sema::LookupOrdinaryName); 6607 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); 6608 6609 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); 6610 assert(BuiltInDecl && "failed to find builtin declaration"); 6611 6612 ExprResult DeclRef = 6613 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); 6614 assert(DeclRef.isUsable() && "Builtin reference cannot fail"); 6615 6616 ExprResult Call = 6617 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); 6618 6619 assert(!Call.isInvalid() && "Call to builtin cannot fail!"); 6620 return Call.get(); 6621 } 6622 6623 /// Parse a __builtin_astype expression. 6624 /// 6625 /// __builtin_astype( value, dst type ) 6626 /// 6627 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6628 SourceLocation BuiltinLoc, 6629 SourceLocation RParenLoc) { 6630 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6631 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6632 } 6633 6634 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6635 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6636 SourceLocation BuiltinLoc, 6637 SourceLocation RParenLoc) { 6638 ExprValueKind VK = VK_PRValue; 6639 ExprObjectKind OK = OK_Ordinary; 6640 QualType SrcTy = E->getType(); 6641 if (!SrcTy->isDependentType() && 6642 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6643 return ExprError( 6644 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6645 << DestTy << SrcTy << E->getSourceRange()); 6646 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6647 } 6648 6649 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6650 /// provided arguments. 6651 /// 6652 /// __builtin_convertvector( value, dst type ) 6653 /// 6654 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6655 SourceLocation BuiltinLoc, 6656 SourceLocation RParenLoc) { 6657 TypeSourceInfo *TInfo; 6658 GetTypeFromParser(ParsedDestTy, &TInfo); 6659 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6660 } 6661 6662 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6663 /// i.e. an expression not of \p OverloadTy. The expression should 6664 /// unary-convert to an expression of function-pointer or 6665 /// block-pointer type. 6666 /// 6667 /// \param NDecl the declaration being called, if available 6668 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6669 SourceLocation LParenLoc, 6670 ArrayRef<Expr *> Args, 6671 SourceLocation RParenLoc, Expr *Config, 6672 bool IsExecConfig, ADLCallKind UsesADL) { 6673 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6674 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6675 6676 // Functions with 'interrupt' attribute cannot be called directly. 6677 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6678 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6679 return ExprError(); 6680 } 6681 6682 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6683 // so there's some risk when calling out to non-interrupt handler functions 6684 // that the callee might not preserve them. This is easy to diagnose here, 6685 // but can be very challenging to debug. 6686 // Likewise, X86 interrupt handlers may only call routines with attribute 6687 // no_caller_saved_registers since there is no efficient way to 6688 // save and restore the non-GPR state. 6689 if (auto *Caller = getCurFunctionDecl()) { 6690 if (Caller->hasAttr<ARMInterruptAttr>()) { 6691 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6692 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6693 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6694 if (FDecl) 6695 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6696 } 6697 } 6698 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6699 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6700 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6701 if (FDecl) 6702 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6703 } 6704 } 6705 6706 // Promote the function operand. 6707 // We special-case function promotion here because we only allow promoting 6708 // builtin functions to function pointers in the callee of a call. 6709 ExprResult Result; 6710 QualType ResultTy; 6711 if (BuiltinID && 6712 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6713 // Extract the return type from the (builtin) function pointer type. 6714 // FIXME Several builtins still have setType in 6715 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6716 // Builtins.def to ensure they are correct before removing setType calls. 6717 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6718 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6719 ResultTy = FDecl->getCallResultType(); 6720 } else { 6721 Result = CallExprUnaryConversions(Fn); 6722 ResultTy = Context.BoolTy; 6723 } 6724 if (Result.isInvalid()) 6725 return ExprError(); 6726 Fn = Result.get(); 6727 6728 // Check for a valid function type, but only if it is not a builtin which 6729 // requires custom type checking. These will be handled by 6730 // CheckBuiltinFunctionCall below just after creation of the call expression. 6731 const FunctionType *FuncT = nullptr; 6732 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6733 retry: 6734 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6735 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6736 // have type pointer to function". 6737 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6738 if (!FuncT) 6739 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6740 << Fn->getType() << Fn->getSourceRange()); 6741 } else if (const BlockPointerType *BPT = 6742 Fn->getType()->getAs<BlockPointerType>()) { 6743 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6744 } else { 6745 // Handle calls to expressions of unknown-any type. 6746 if (Fn->getType() == Context.UnknownAnyTy) { 6747 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6748 if (rewrite.isInvalid()) 6749 return ExprError(); 6750 Fn = rewrite.get(); 6751 goto retry; 6752 } 6753 6754 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6755 << Fn->getType() << Fn->getSourceRange()); 6756 } 6757 } 6758 6759 // Get the number of parameters in the function prototype, if any. 6760 // We will allocate space for max(Args.size(), NumParams) arguments 6761 // in the call expression. 6762 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6763 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6764 6765 CallExpr *TheCall; 6766 if (Config) { 6767 assert(UsesADL == ADLCallKind::NotADL && 6768 "CUDAKernelCallExpr should not use ADL"); 6769 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6770 Args, ResultTy, VK_PRValue, RParenLoc, 6771 CurFPFeatureOverrides(), NumParams); 6772 } else { 6773 TheCall = 6774 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6775 CurFPFeatureOverrides(), NumParams, UsesADL); 6776 } 6777 6778 if (!Context.isDependenceAllowed()) { 6779 // Forget about the nulled arguments since typo correction 6780 // do not handle them well. 6781 TheCall->shrinkNumArgs(Args.size()); 6782 // C cannot always handle TypoExpr nodes in builtin calls and direct 6783 // function calls as their argument checking don't necessarily handle 6784 // dependent types properly, so make sure any TypoExprs have been 6785 // dealt with. 6786 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6787 if (!Result.isUsable()) return ExprError(); 6788 CallExpr *TheOldCall = TheCall; 6789 TheCall = dyn_cast<CallExpr>(Result.get()); 6790 bool CorrectedTypos = TheCall != TheOldCall; 6791 if (!TheCall) return Result; 6792 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6793 6794 // A new call expression node was created if some typos were corrected. 6795 // However it may not have been constructed with enough storage. In this 6796 // case, rebuild the node with enough storage. The waste of space is 6797 // immaterial since this only happens when some typos were corrected. 6798 if (CorrectedTypos && Args.size() < NumParams) { 6799 if (Config) 6800 TheCall = CUDAKernelCallExpr::Create( 6801 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 6802 RParenLoc, CurFPFeatureOverrides(), NumParams); 6803 else 6804 TheCall = 6805 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6806 CurFPFeatureOverrides(), NumParams, UsesADL); 6807 } 6808 // We can now handle the nulled arguments for the default arguments. 6809 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6810 } 6811 6812 // Bail out early if calling a builtin with custom type checking. 6813 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6814 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6815 6816 if (getLangOpts().CUDA) { 6817 if (Config) { 6818 // CUDA: Kernel calls must be to global functions 6819 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6820 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6821 << FDecl << Fn->getSourceRange()); 6822 6823 // CUDA: Kernel function must have 'void' return type 6824 if (!FuncT->getReturnType()->isVoidType() && 6825 !FuncT->getReturnType()->getAs<AutoType>() && 6826 !FuncT->getReturnType()->isInstantiationDependentType()) 6827 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6828 << Fn->getType() << Fn->getSourceRange()); 6829 } else { 6830 // CUDA: Calls to global functions must be configured 6831 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6832 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6833 << FDecl << Fn->getSourceRange()); 6834 } 6835 } 6836 6837 // Check for a valid return type 6838 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6839 FDecl)) 6840 return ExprError(); 6841 6842 // We know the result type of the call, set it. 6843 TheCall->setType(FuncT->getCallResultType(Context)); 6844 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6845 6846 if (Proto) { 6847 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6848 IsExecConfig)) 6849 return ExprError(); 6850 } else { 6851 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6852 6853 if (FDecl) { 6854 // Check if we have too few/too many template arguments, based 6855 // on our knowledge of the function definition. 6856 const FunctionDecl *Def = nullptr; 6857 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6858 Proto = Def->getType()->getAs<FunctionProtoType>(); 6859 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6860 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6861 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6862 } 6863 6864 // If the function we're calling isn't a function prototype, but we have 6865 // a function prototype from a prior declaratiom, use that prototype. 6866 if (!FDecl->hasPrototype()) 6867 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6868 } 6869 6870 // Promote the arguments (C99 6.5.2.2p6). 6871 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6872 Expr *Arg = Args[i]; 6873 6874 if (Proto && i < Proto->getNumParams()) { 6875 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6876 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6877 ExprResult ArgE = 6878 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6879 if (ArgE.isInvalid()) 6880 return true; 6881 6882 Arg = ArgE.getAs<Expr>(); 6883 6884 } else { 6885 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6886 6887 if (ArgE.isInvalid()) 6888 return true; 6889 6890 Arg = ArgE.getAs<Expr>(); 6891 } 6892 6893 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6894 diag::err_call_incomplete_argument, Arg)) 6895 return ExprError(); 6896 6897 TheCall->setArg(i, Arg); 6898 } 6899 TheCall->computeDependence(); 6900 } 6901 6902 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6903 if (!Method->isStatic()) 6904 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6905 << Fn->getSourceRange()); 6906 6907 // Check for sentinels 6908 if (NDecl) 6909 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6910 6911 // Warn for unions passing across security boundary (CMSE). 6912 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6913 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6914 if (const auto *RT = 6915 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6916 if (RT->getDecl()->isOrContainsUnion()) 6917 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6918 << 0 << i; 6919 } 6920 } 6921 } 6922 6923 // Do special checking on direct calls to functions. 6924 if (FDecl) { 6925 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6926 return ExprError(); 6927 6928 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6929 6930 if (BuiltinID) 6931 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6932 } else if (NDecl) { 6933 if (CheckPointerCall(NDecl, TheCall, Proto)) 6934 return ExprError(); 6935 } else { 6936 if (CheckOtherCall(TheCall, Proto)) 6937 return ExprError(); 6938 } 6939 6940 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6941 } 6942 6943 ExprResult 6944 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6945 SourceLocation RParenLoc, Expr *InitExpr) { 6946 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6947 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6948 6949 TypeSourceInfo *TInfo; 6950 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6951 if (!TInfo) 6952 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6953 6954 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6955 } 6956 6957 ExprResult 6958 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6959 SourceLocation RParenLoc, Expr *LiteralExpr) { 6960 QualType literalType = TInfo->getType(); 6961 6962 if (literalType->isArrayType()) { 6963 if (RequireCompleteSizedType( 6964 LParenLoc, Context.getBaseElementType(literalType), 6965 diag::err_array_incomplete_or_sizeless_type, 6966 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6967 return ExprError(); 6968 if (literalType->isVariableArrayType()) { 6969 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 6970 diag::err_variable_object_no_init)) { 6971 return ExprError(); 6972 } 6973 } 6974 } else if (!literalType->isDependentType() && 6975 RequireCompleteType(LParenLoc, literalType, 6976 diag::err_typecheck_decl_incomplete_type, 6977 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6978 return ExprError(); 6979 6980 InitializedEntity Entity 6981 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6982 InitializationKind Kind 6983 = InitializationKind::CreateCStyleCast(LParenLoc, 6984 SourceRange(LParenLoc, RParenLoc), 6985 /*InitList=*/true); 6986 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6987 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6988 &literalType); 6989 if (Result.isInvalid()) 6990 return ExprError(); 6991 LiteralExpr = Result.get(); 6992 6993 bool isFileScope = !CurContext->isFunctionOrMethod(); 6994 6995 // In C, compound literals are l-values for some reason. 6996 // For GCC compatibility, in C++, file-scope array compound literals with 6997 // constant initializers are also l-values, and compound literals are 6998 // otherwise prvalues. 6999 // 7000 // (GCC also treats C++ list-initialized file-scope array prvalues with 7001 // constant initializers as l-values, but that's non-conforming, so we don't 7002 // follow it there.) 7003 // 7004 // FIXME: It would be better to handle the lvalue cases as materializing and 7005 // lifetime-extending a temporary object, but our materialized temporaries 7006 // representation only supports lifetime extension from a variable, not "out 7007 // of thin air". 7008 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 7009 // is bound to the result of applying array-to-pointer decay to the compound 7010 // literal. 7011 // FIXME: GCC supports compound literals of reference type, which should 7012 // obviously have a value kind derived from the kind of reference involved. 7013 ExprValueKind VK = 7014 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 7015 ? VK_PRValue 7016 : VK_LValue; 7017 7018 if (isFileScope) 7019 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 7020 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 7021 Expr *Init = ILE->getInit(i); 7022 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 7023 } 7024 7025 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 7026 VK, LiteralExpr, isFileScope); 7027 if (isFileScope) { 7028 if (!LiteralExpr->isTypeDependent() && 7029 !LiteralExpr->isValueDependent() && 7030 !literalType->isDependentType()) // C99 6.5.2.5p3 7031 if (CheckForConstantInitializer(LiteralExpr, literalType)) 7032 return ExprError(); 7033 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 7034 literalType.getAddressSpace() != LangAS::Default) { 7035 // Embedded-C extensions to C99 6.5.2.5: 7036 // "If the compound literal occurs inside the body of a function, the 7037 // type name shall not be qualified by an address-space qualifier." 7038 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 7039 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 7040 return ExprError(); 7041 } 7042 7043 if (!isFileScope && !getLangOpts().CPlusPlus) { 7044 // Compound literals that have automatic storage duration are destroyed at 7045 // the end of the scope in C; in C++, they're just temporaries. 7046 7047 // Emit diagnostics if it is or contains a C union type that is non-trivial 7048 // to destruct. 7049 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 7050 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 7051 NTCUC_CompoundLiteral, NTCUK_Destruct); 7052 7053 // Diagnose jumps that enter or exit the lifetime of the compound literal. 7054 if (literalType.isDestructedType()) { 7055 Cleanup.setExprNeedsCleanups(true); 7056 ExprCleanupObjects.push_back(E); 7057 getCurFunction()->setHasBranchProtectedScope(); 7058 } 7059 } 7060 7061 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7062 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7063 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7064 E->getInitializer()->getExprLoc()); 7065 7066 return MaybeBindToTemporary(E); 7067 } 7068 7069 ExprResult 7070 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7071 SourceLocation RBraceLoc) { 7072 // Only produce each kind of designated initialization diagnostic once. 7073 SourceLocation FirstDesignator; 7074 bool DiagnosedArrayDesignator = false; 7075 bool DiagnosedNestedDesignator = false; 7076 bool DiagnosedMixedDesignator = false; 7077 7078 // Check that any designated initializers are syntactically valid in the 7079 // current language mode. 7080 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7081 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7082 if (FirstDesignator.isInvalid()) 7083 FirstDesignator = DIE->getBeginLoc(); 7084 7085 if (!getLangOpts().CPlusPlus) 7086 break; 7087 7088 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7089 DiagnosedNestedDesignator = true; 7090 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7091 << DIE->getDesignatorsSourceRange(); 7092 } 7093 7094 for (auto &Desig : DIE->designators()) { 7095 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7096 DiagnosedArrayDesignator = true; 7097 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7098 << Desig.getSourceRange(); 7099 } 7100 } 7101 7102 if (!DiagnosedMixedDesignator && 7103 !isa<DesignatedInitExpr>(InitArgList[0])) { 7104 DiagnosedMixedDesignator = true; 7105 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7106 << DIE->getSourceRange(); 7107 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7108 << InitArgList[0]->getSourceRange(); 7109 } 7110 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7111 isa<DesignatedInitExpr>(InitArgList[0])) { 7112 DiagnosedMixedDesignator = true; 7113 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7114 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7115 << DIE->getSourceRange(); 7116 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7117 << InitArgList[I]->getSourceRange(); 7118 } 7119 } 7120 7121 if (FirstDesignator.isValid()) { 7122 // Only diagnose designated initiaization as a C++20 extension if we didn't 7123 // already diagnose use of (non-C++20) C99 designator syntax. 7124 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7125 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7126 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7127 ? diag::warn_cxx17_compat_designated_init 7128 : diag::ext_cxx_designated_init); 7129 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7130 Diag(FirstDesignator, diag::ext_designated_init); 7131 } 7132 } 7133 7134 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7135 } 7136 7137 ExprResult 7138 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7139 SourceLocation RBraceLoc) { 7140 // Semantic analysis for initializers is done by ActOnDeclarator() and 7141 // CheckInitializer() - it requires knowledge of the object being initialized. 7142 7143 // Immediately handle non-overload placeholders. Overloads can be 7144 // resolved contextually, but everything else here can't. 7145 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7146 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7147 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7148 7149 // Ignore failures; dropping the entire initializer list because 7150 // of one failure would be terrible for indexing/etc. 7151 if (result.isInvalid()) continue; 7152 7153 InitArgList[I] = result.get(); 7154 } 7155 } 7156 7157 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7158 RBraceLoc); 7159 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7160 return E; 7161 } 7162 7163 /// Do an explicit extend of the given block pointer if we're in ARC. 7164 void Sema::maybeExtendBlockObject(ExprResult &E) { 7165 assert(E.get()->getType()->isBlockPointerType()); 7166 assert(E.get()->isPRValue()); 7167 7168 // Only do this in an r-value context. 7169 if (!getLangOpts().ObjCAutoRefCount) return; 7170 7171 E = ImplicitCastExpr::Create( 7172 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7173 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 7174 Cleanup.setExprNeedsCleanups(true); 7175 } 7176 7177 /// Prepare a conversion of the given expression to an ObjC object 7178 /// pointer type. 7179 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7180 QualType type = E.get()->getType(); 7181 if (type->isObjCObjectPointerType()) { 7182 return CK_BitCast; 7183 } else if (type->isBlockPointerType()) { 7184 maybeExtendBlockObject(E); 7185 return CK_BlockPointerToObjCPointerCast; 7186 } else { 7187 assert(type->isPointerType()); 7188 return CK_CPointerToObjCPointerCast; 7189 } 7190 } 7191 7192 /// Prepares for a scalar cast, performing all the necessary stages 7193 /// except the final cast and returning the kind required. 7194 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7195 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7196 // Also, callers should have filtered out the invalid cases with 7197 // pointers. Everything else should be possible. 7198 7199 QualType SrcTy = Src.get()->getType(); 7200 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7201 return CK_NoOp; 7202 7203 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7204 case Type::STK_MemberPointer: 7205 llvm_unreachable("member pointer type in C"); 7206 7207 case Type::STK_CPointer: 7208 case Type::STK_BlockPointer: 7209 case Type::STK_ObjCObjectPointer: 7210 switch (DestTy->getScalarTypeKind()) { 7211 case Type::STK_CPointer: { 7212 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7213 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7214 if (SrcAS != DestAS) 7215 return CK_AddressSpaceConversion; 7216 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7217 return CK_NoOp; 7218 return CK_BitCast; 7219 } 7220 case Type::STK_BlockPointer: 7221 return (SrcKind == Type::STK_BlockPointer 7222 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7223 case Type::STK_ObjCObjectPointer: 7224 if (SrcKind == Type::STK_ObjCObjectPointer) 7225 return CK_BitCast; 7226 if (SrcKind == Type::STK_CPointer) 7227 return CK_CPointerToObjCPointerCast; 7228 maybeExtendBlockObject(Src); 7229 return CK_BlockPointerToObjCPointerCast; 7230 case Type::STK_Bool: 7231 return CK_PointerToBoolean; 7232 case Type::STK_Integral: 7233 return CK_PointerToIntegral; 7234 case Type::STK_Floating: 7235 case Type::STK_FloatingComplex: 7236 case Type::STK_IntegralComplex: 7237 case Type::STK_MemberPointer: 7238 case Type::STK_FixedPoint: 7239 llvm_unreachable("illegal cast from pointer"); 7240 } 7241 llvm_unreachable("Should have returned before this"); 7242 7243 case Type::STK_FixedPoint: 7244 switch (DestTy->getScalarTypeKind()) { 7245 case Type::STK_FixedPoint: 7246 return CK_FixedPointCast; 7247 case Type::STK_Bool: 7248 return CK_FixedPointToBoolean; 7249 case Type::STK_Integral: 7250 return CK_FixedPointToIntegral; 7251 case Type::STK_Floating: 7252 return CK_FixedPointToFloating; 7253 case Type::STK_IntegralComplex: 7254 case Type::STK_FloatingComplex: 7255 Diag(Src.get()->getExprLoc(), 7256 diag::err_unimplemented_conversion_with_fixed_point_type) 7257 << DestTy; 7258 return CK_IntegralCast; 7259 case Type::STK_CPointer: 7260 case Type::STK_ObjCObjectPointer: 7261 case Type::STK_BlockPointer: 7262 case Type::STK_MemberPointer: 7263 llvm_unreachable("illegal cast to pointer type"); 7264 } 7265 llvm_unreachable("Should have returned before this"); 7266 7267 case Type::STK_Bool: // casting from bool is like casting from an integer 7268 case Type::STK_Integral: 7269 switch (DestTy->getScalarTypeKind()) { 7270 case Type::STK_CPointer: 7271 case Type::STK_ObjCObjectPointer: 7272 case Type::STK_BlockPointer: 7273 if (Src.get()->isNullPointerConstant(Context, 7274 Expr::NPC_ValueDependentIsNull)) 7275 return CK_NullToPointer; 7276 return CK_IntegralToPointer; 7277 case Type::STK_Bool: 7278 return CK_IntegralToBoolean; 7279 case Type::STK_Integral: 7280 return CK_IntegralCast; 7281 case Type::STK_Floating: 7282 return CK_IntegralToFloating; 7283 case Type::STK_IntegralComplex: 7284 Src = ImpCastExprToType(Src.get(), 7285 DestTy->castAs<ComplexType>()->getElementType(), 7286 CK_IntegralCast); 7287 return CK_IntegralRealToComplex; 7288 case Type::STK_FloatingComplex: 7289 Src = ImpCastExprToType(Src.get(), 7290 DestTy->castAs<ComplexType>()->getElementType(), 7291 CK_IntegralToFloating); 7292 return CK_FloatingRealToComplex; 7293 case Type::STK_MemberPointer: 7294 llvm_unreachable("member pointer type in C"); 7295 case Type::STK_FixedPoint: 7296 return CK_IntegralToFixedPoint; 7297 } 7298 llvm_unreachable("Should have returned before this"); 7299 7300 case Type::STK_Floating: 7301 switch (DestTy->getScalarTypeKind()) { 7302 case Type::STK_Floating: 7303 return CK_FloatingCast; 7304 case Type::STK_Bool: 7305 return CK_FloatingToBoolean; 7306 case Type::STK_Integral: 7307 return CK_FloatingToIntegral; 7308 case Type::STK_FloatingComplex: 7309 Src = ImpCastExprToType(Src.get(), 7310 DestTy->castAs<ComplexType>()->getElementType(), 7311 CK_FloatingCast); 7312 return CK_FloatingRealToComplex; 7313 case Type::STK_IntegralComplex: 7314 Src = ImpCastExprToType(Src.get(), 7315 DestTy->castAs<ComplexType>()->getElementType(), 7316 CK_FloatingToIntegral); 7317 return CK_IntegralRealToComplex; 7318 case Type::STK_CPointer: 7319 case Type::STK_ObjCObjectPointer: 7320 case Type::STK_BlockPointer: 7321 llvm_unreachable("valid float->pointer cast?"); 7322 case Type::STK_MemberPointer: 7323 llvm_unreachable("member pointer type in C"); 7324 case Type::STK_FixedPoint: 7325 return CK_FloatingToFixedPoint; 7326 } 7327 llvm_unreachable("Should have returned before this"); 7328 7329 case Type::STK_FloatingComplex: 7330 switch (DestTy->getScalarTypeKind()) { 7331 case Type::STK_FloatingComplex: 7332 return CK_FloatingComplexCast; 7333 case Type::STK_IntegralComplex: 7334 return CK_FloatingComplexToIntegralComplex; 7335 case Type::STK_Floating: { 7336 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7337 if (Context.hasSameType(ET, DestTy)) 7338 return CK_FloatingComplexToReal; 7339 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7340 return CK_FloatingCast; 7341 } 7342 case Type::STK_Bool: 7343 return CK_FloatingComplexToBoolean; 7344 case Type::STK_Integral: 7345 Src = ImpCastExprToType(Src.get(), 7346 SrcTy->castAs<ComplexType>()->getElementType(), 7347 CK_FloatingComplexToReal); 7348 return CK_FloatingToIntegral; 7349 case Type::STK_CPointer: 7350 case Type::STK_ObjCObjectPointer: 7351 case Type::STK_BlockPointer: 7352 llvm_unreachable("valid complex float->pointer cast?"); 7353 case Type::STK_MemberPointer: 7354 llvm_unreachable("member pointer type in C"); 7355 case Type::STK_FixedPoint: 7356 Diag(Src.get()->getExprLoc(), 7357 diag::err_unimplemented_conversion_with_fixed_point_type) 7358 << SrcTy; 7359 return CK_IntegralCast; 7360 } 7361 llvm_unreachable("Should have returned before this"); 7362 7363 case Type::STK_IntegralComplex: 7364 switch (DestTy->getScalarTypeKind()) { 7365 case Type::STK_FloatingComplex: 7366 return CK_IntegralComplexToFloatingComplex; 7367 case Type::STK_IntegralComplex: 7368 return CK_IntegralComplexCast; 7369 case Type::STK_Integral: { 7370 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7371 if (Context.hasSameType(ET, DestTy)) 7372 return CK_IntegralComplexToReal; 7373 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7374 return CK_IntegralCast; 7375 } 7376 case Type::STK_Bool: 7377 return CK_IntegralComplexToBoolean; 7378 case Type::STK_Floating: 7379 Src = ImpCastExprToType(Src.get(), 7380 SrcTy->castAs<ComplexType>()->getElementType(), 7381 CK_IntegralComplexToReal); 7382 return CK_IntegralToFloating; 7383 case Type::STK_CPointer: 7384 case Type::STK_ObjCObjectPointer: 7385 case Type::STK_BlockPointer: 7386 llvm_unreachable("valid complex int->pointer cast?"); 7387 case Type::STK_MemberPointer: 7388 llvm_unreachable("member pointer type in C"); 7389 case Type::STK_FixedPoint: 7390 Diag(Src.get()->getExprLoc(), 7391 diag::err_unimplemented_conversion_with_fixed_point_type) 7392 << SrcTy; 7393 return CK_IntegralCast; 7394 } 7395 llvm_unreachable("Should have returned before this"); 7396 } 7397 7398 llvm_unreachable("Unhandled scalar cast"); 7399 } 7400 7401 static bool breakDownVectorType(QualType type, uint64_t &len, 7402 QualType &eltType) { 7403 // Vectors are simple. 7404 if (const VectorType *vecType = type->getAs<VectorType>()) { 7405 len = vecType->getNumElements(); 7406 eltType = vecType->getElementType(); 7407 assert(eltType->isScalarType()); 7408 return true; 7409 } 7410 7411 // We allow lax conversion to and from non-vector types, but only if 7412 // they're real types (i.e. non-complex, non-pointer scalar types). 7413 if (!type->isRealType()) return false; 7414 7415 len = 1; 7416 eltType = type; 7417 return true; 7418 } 7419 7420 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7421 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7422 /// allowed? 7423 /// 7424 /// This will also return false if the two given types do not make sense from 7425 /// the perspective of SVE bitcasts. 7426 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7427 assert(srcTy->isVectorType() || destTy->isVectorType()); 7428 7429 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7430 if (!FirstType->isSizelessBuiltinType()) 7431 return false; 7432 7433 const auto *VecTy = SecondType->getAs<VectorType>(); 7434 return VecTy && 7435 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7436 }; 7437 7438 return ValidScalableConversion(srcTy, destTy) || 7439 ValidScalableConversion(destTy, srcTy); 7440 } 7441 7442 /// Are the two types matrix types and do they have the same dimensions i.e. 7443 /// do they have the same number of rows and the same number of columns? 7444 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7445 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7446 return false; 7447 7448 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7449 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7450 7451 return matSrcType->getNumRows() == matDestType->getNumRows() && 7452 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7453 } 7454 7455 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7456 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7457 7458 uint64_t SrcLen, DestLen; 7459 QualType SrcEltTy, DestEltTy; 7460 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7461 return false; 7462 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7463 return false; 7464 7465 // ASTContext::getTypeSize will return the size rounded up to a 7466 // power of 2, so instead of using that, we need to use the raw 7467 // element size multiplied by the element count. 7468 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7469 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7470 7471 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7472 } 7473 7474 /// Are the two types lax-compatible vector types? That is, given 7475 /// that one of them is a vector, do they have equal storage sizes, 7476 /// where the storage size is the number of elements times the element 7477 /// size? 7478 /// 7479 /// This will also return false if either of the types is neither a 7480 /// vector nor a real type. 7481 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7482 assert(destTy->isVectorType() || srcTy->isVectorType()); 7483 7484 // Disallow lax conversions between scalars and ExtVectors (these 7485 // conversions are allowed for other vector types because common headers 7486 // depend on them). Most scalar OP ExtVector cases are handled by the 7487 // splat path anyway, which does what we want (convert, not bitcast). 7488 // What this rules out for ExtVectors is crazy things like char4*float. 7489 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7490 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7491 7492 return areVectorTypesSameSize(srcTy, destTy); 7493 } 7494 7495 /// Is this a legal conversion between two types, one of which is 7496 /// known to be a vector type? 7497 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7498 assert(destTy->isVectorType() || srcTy->isVectorType()); 7499 7500 switch (Context.getLangOpts().getLaxVectorConversions()) { 7501 case LangOptions::LaxVectorConversionKind::None: 7502 return false; 7503 7504 case LangOptions::LaxVectorConversionKind::Integer: 7505 if (!srcTy->isIntegralOrEnumerationType()) { 7506 auto *Vec = srcTy->getAs<VectorType>(); 7507 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7508 return false; 7509 } 7510 if (!destTy->isIntegralOrEnumerationType()) { 7511 auto *Vec = destTy->getAs<VectorType>(); 7512 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7513 return false; 7514 } 7515 // OK, integer (vector) -> integer (vector) bitcast. 7516 break; 7517 7518 case LangOptions::LaxVectorConversionKind::All: 7519 break; 7520 } 7521 7522 return areLaxCompatibleVectorTypes(srcTy, destTy); 7523 } 7524 7525 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7526 CastKind &Kind) { 7527 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7528 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7529 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7530 << DestTy << SrcTy << R; 7531 } 7532 } else if (SrcTy->isMatrixType()) { 7533 return Diag(R.getBegin(), 7534 diag::err_invalid_conversion_between_matrix_and_type) 7535 << SrcTy << DestTy << R; 7536 } else if (DestTy->isMatrixType()) { 7537 return Diag(R.getBegin(), 7538 diag::err_invalid_conversion_between_matrix_and_type) 7539 << DestTy << SrcTy << R; 7540 } 7541 7542 Kind = CK_MatrixCast; 7543 return false; 7544 } 7545 7546 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7547 CastKind &Kind) { 7548 assert(VectorTy->isVectorType() && "Not a vector type!"); 7549 7550 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7551 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7552 return Diag(R.getBegin(), 7553 Ty->isVectorType() ? 7554 diag::err_invalid_conversion_between_vectors : 7555 diag::err_invalid_conversion_between_vector_and_integer) 7556 << VectorTy << Ty << R; 7557 } else 7558 return Diag(R.getBegin(), 7559 diag::err_invalid_conversion_between_vector_and_scalar) 7560 << VectorTy << Ty << R; 7561 7562 Kind = CK_BitCast; 7563 return false; 7564 } 7565 7566 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7567 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7568 7569 if (DestElemTy == SplattedExpr->getType()) 7570 return SplattedExpr; 7571 7572 assert(DestElemTy->isFloatingType() || 7573 DestElemTy->isIntegralOrEnumerationType()); 7574 7575 CastKind CK; 7576 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7577 // OpenCL requires that we convert `true` boolean expressions to -1, but 7578 // only when splatting vectors. 7579 if (DestElemTy->isFloatingType()) { 7580 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7581 // in two steps: boolean to signed integral, then to floating. 7582 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7583 CK_BooleanToSignedIntegral); 7584 SplattedExpr = CastExprRes.get(); 7585 CK = CK_IntegralToFloating; 7586 } else { 7587 CK = CK_BooleanToSignedIntegral; 7588 } 7589 } else { 7590 ExprResult CastExprRes = SplattedExpr; 7591 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7592 if (CastExprRes.isInvalid()) 7593 return ExprError(); 7594 SplattedExpr = CastExprRes.get(); 7595 } 7596 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7597 } 7598 7599 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7600 Expr *CastExpr, CastKind &Kind) { 7601 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7602 7603 QualType SrcTy = CastExpr->getType(); 7604 7605 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7606 // an ExtVectorType. 7607 // In OpenCL, casts between vectors of different types are not allowed. 7608 // (See OpenCL 6.2). 7609 if (SrcTy->isVectorType()) { 7610 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7611 (getLangOpts().OpenCL && 7612 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7613 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7614 << DestTy << SrcTy << R; 7615 return ExprError(); 7616 } 7617 Kind = CK_BitCast; 7618 return CastExpr; 7619 } 7620 7621 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7622 // conversion will take place first from scalar to elt type, and then 7623 // splat from elt type to vector. 7624 if (SrcTy->isPointerType()) 7625 return Diag(R.getBegin(), 7626 diag::err_invalid_conversion_between_vector_and_scalar) 7627 << DestTy << SrcTy << R; 7628 7629 Kind = CK_VectorSplat; 7630 return prepareVectorSplat(DestTy, CastExpr); 7631 } 7632 7633 ExprResult 7634 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7635 Declarator &D, ParsedType &Ty, 7636 SourceLocation RParenLoc, Expr *CastExpr) { 7637 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7638 "ActOnCastExpr(): missing type or expr"); 7639 7640 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7641 if (D.isInvalidType()) 7642 return ExprError(); 7643 7644 if (getLangOpts().CPlusPlus) { 7645 // Check that there are no default arguments (C++ only). 7646 CheckExtraCXXDefaultArguments(D); 7647 } else { 7648 // Make sure any TypoExprs have been dealt with. 7649 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7650 if (!Res.isUsable()) 7651 return ExprError(); 7652 CastExpr = Res.get(); 7653 } 7654 7655 checkUnusedDeclAttributes(D); 7656 7657 QualType castType = castTInfo->getType(); 7658 Ty = CreateParsedType(castType, castTInfo); 7659 7660 bool isVectorLiteral = false; 7661 7662 // Check for an altivec or OpenCL literal, 7663 // i.e. all the elements are integer constants. 7664 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7665 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7666 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7667 && castType->isVectorType() && (PE || PLE)) { 7668 if (PLE && PLE->getNumExprs() == 0) { 7669 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7670 return ExprError(); 7671 } 7672 if (PE || PLE->getNumExprs() == 1) { 7673 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7674 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7675 isVectorLiteral = true; 7676 } 7677 else 7678 isVectorLiteral = true; 7679 } 7680 7681 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7682 // then handle it as such. 7683 if (isVectorLiteral) 7684 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7685 7686 // If the Expr being casted is a ParenListExpr, handle it specially. 7687 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7688 // sequence of BinOp comma operators. 7689 if (isa<ParenListExpr>(CastExpr)) { 7690 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7691 if (Result.isInvalid()) return ExprError(); 7692 CastExpr = Result.get(); 7693 } 7694 7695 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7696 !getSourceManager().isInSystemMacro(LParenLoc)) 7697 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7698 7699 CheckTollFreeBridgeCast(castType, CastExpr); 7700 7701 CheckObjCBridgeRelatedCast(castType, CastExpr); 7702 7703 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7704 7705 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7706 } 7707 7708 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7709 SourceLocation RParenLoc, Expr *E, 7710 TypeSourceInfo *TInfo) { 7711 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7712 "Expected paren or paren list expression"); 7713 7714 Expr **exprs; 7715 unsigned numExprs; 7716 Expr *subExpr; 7717 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7718 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7719 LiteralLParenLoc = PE->getLParenLoc(); 7720 LiteralRParenLoc = PE->getRParenLoc(); 7721 exprs = PE->getExprs(); 7722 numExprs = PE->getNumExprs(); 7723 } else { // isa<ParenExpr> by assertion at function entrance 7724 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7725 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7726 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7727 exprs = &subExpr; 7728 numExprs = 1; 7729 } 7730 7731 QualType Ty = TInfo->getType(); 7732 assert(Ty->isVectorType() && "Expected vector type"); 7733 7734 SmallVector<Expr *, 8> initExprs; 7735 const VectorType *VTy = Ty->castAs<VectorType>(); 7736 unsigned numElems = VTy->getNumElements(); 7737 7738 // '(...)' form of vector initialization in AltiVec: the number of 7739 // initializers must be one or must match the size of the vector. 7740 // If a single value is specified in the initializer then it will be 7741 // replicated to all the components of the vector 7742 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, 7743 VTy->getElementType())) 7744 return ExprError(); 7745 if (ShouldSplatAltivecScalarInCast(VTy)) { 7746 // The number of initializers must be one or must match the size of the 7747 // vector. If a single value is specified in the initializer then it will 7748 // be replicated to all the components of the vector 7749 if (numExprs == 1) { 7750 QualType ElemTy = VTy->getElementType(); 7751 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7752 if (Literal.isInvalid()) 7753 return ExprError(); 7754 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7755 PrepareScalarCast(Literal, ElemTy)); 7756 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7757 } 7758 else if (numExprs < numElems) { 7759 Diag(E->getExprLoc(), 7760 diag::err_incorrect_number_of_vector_initializers); 7761 return ExprError(); 7762 } 7763 else 7764 initExprs.append(exprs, exprs + numExprs); 7765 } 7766 else { 7767 // For OpenCL, when the number of initializers is a single value, 7768 // it will be replicated to all components of the vector. 7769 if (getLangOpts().OpenCL && 7770 VTy->getVectorKind() == VectorType::GenericVector && 7771 numExprs == 1) { 7772 QualType ElemTy = VTy->getElementType(); 7773 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7774 if (Literal.isInvalid()) 7775 return ExprError(); 7776 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7777 PrepareScalarCast(Literal, ElemTy)); 7778 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7779 } 7780 7781 initExprs.append(exprs, exprs + numExprs); 7782 } 7783 // FIXME: This means that pretty-printing the final AST will produce curly 7784 // braces instead of the original commas. 7785 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7786 initExprs, LiteralRParenLoc); 7787 initE->setType(Ty); 7788 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7789 } 7790 7791 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7792 /// the ParenListExpr into a sequence of comma binary operators. 7793 ExprResult 7794 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7795 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7796 if (!E) 7797 return OrigExpr; 7798 7799 ExprResult Result(E->getExpr(0)); 7800 7801 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7802 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7803 E->getExpr(i)); 7804 7805 if (Result.isInvalid()) return ExprError(); 7806 7807 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7808 } 7809 7810 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7811 SourceLocation R, 7812 MultiExprArg Val) { 7813 return ParenListExpr::Create(Context, L, Val, R); 7814 } 7815 7816 /// Emit a specialized diagnostic when one expression is a null pointer 7817 /// constant and the other is not a pointer. Returns true if a diagnostic is 7818 /// emitted. 7819 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7820 SourceLocation QuestionLoc) { 7821 Expr *NullExpr = LHSExpr; 7822 Expr *NonPointerExpr = RHSExpr; 7823 Expr::NullPointerConstantKind NullKind = 7824 NullExpr->isNullPointerConstant(Context, 7825 Expr::NPC_ValueDependentIsNotNull); 7826 7827 if (NullKind == Expr::NPCK_NotNull) { 7828 NullExpr = RHSExpr; 7829 NonPointerExpr = LHSExpr; 7830 NullKind = 7831 NullExpr->isNullPointerConstant(Context, 7832 Expr::NPC_ValueDependentIsNotNull); 7833 } 7834 7835 if (NullKind == Expr::NPCK_NotNull) 7836 return false; 7837 7838 if (NullKind == Expr::NPCK_ZeroExpression) 7839 return false; 7840 7841 if (NullKind == Expr::NPCK_ZeroLiteral) { 7842 // In this case, check to make sure that we got here from a "NULL" 7843 // string in the source code. 7844 NullExpr = NullExpr->IgnoreParenImpCasts(); 7845 SourceLocation loc = NullExpr->getExprLoc(); 7846 if (!findMacroSpelling(loc, "NULL")) 7847 return false; 7848 } 7849 7850 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7851 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7852 << NonPointerExpr->getType() << DiagType 7853 << NonPointerExpr->getSourceRange(); 7854 return true; 7855 } 7856 7857 /// Return false if the condition expression is valid, true otherwise. 7858 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7859 QualType CondTy = Cond->getType(); 7860 7861 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7862 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7863 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7864 << CondTy << Cond->getSourceRange(); 7865 return true; 7866 } 7867 7868 // C99 6.5.15p2 7869 if (CondTy->isScalarType()) return false; 7870 7871 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7872 << CondTy << Cond->getSourceRange(); 7873 return true; 7874 } 7875 7876 /// Handle when one or both operands are void type. 7877 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7878 ExprResult &RHS) { 7879 Expr *LHSExpr = LHS.get(); 7880 Expr *RHSExpr = RHS.get(); 7881 7882 if (!LHSExpr->getType()->isVoidType()) 7883 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7884 << RHSExpr->getSourceRange(); 7885 if (!RHSExpr->getType()->isVoidType()) 7886 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7887 << LHSExpr->getSourceRange(); 7888 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7889 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7890 return S.Context.VoidTy; 7891 } 7892 7893 /// Return false if the NullExpr can be promoted to PointerTy, 7894 /// true otherwise. 7895 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7896 QualType PointerTy) { 7897 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7898 !NullExpr.get()->isNullPointerConstant(S.Context, 7899 Expr::NPC_ValueDependentIsNull)) 7900 return true; 7901 7902 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7903 return false; 7904 } 7905 7906 /// Checks compatibility between two pointers and return the resulting 7907 /// type. 7908 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7909 ExprResult &RHS, 7910 SourceLocation Loc) { 7911 QualType LHSTy = LHS.get()->getType(); 7912 QualType RHSTy = RHS.get()->getType(); 7913 7914 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7915 // Two identical pointers types are always compatible. 7916 return LHSTy; 7917 } 7918 7919 QualType lhptee, rhptee; 7920 7921 // Get the pointee types. 7922 bool IsBlockPointer = false; 7923 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7924 lhptee = LHSBTy->getPointeeType(); 7925 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7926 IsBlockPointer = true; 7927 } else { 7928 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7929 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7930 } 7931 7932 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7933 // differently qualified versions of compatible types, the result type is 7934 // a pointer to an appropriately qualified version of the composite 7935 // type. 7936 7937 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7938 // clause doesn't make sense for our extensions. E.g. address space 2 should 7939 // be incompatible with address space 3: they may live on different devices or 7940 // anything. 7941 Qualifiers lhQual = lhptee.getQualifiers(); 7942 Qualifiers rhQual = rhptee.getQualifiers(); 7943 7944 LangAS ResultAddrSpace = LangAS::Default; 7945 LangAS LAddrSpace = lhQual.getAddressSpace(); 7946 LangAS RAddrSpace = rhQual.getAddressSpace(); 7947 7948 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7949 // spaces is disallowed. 7950 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7951 ResultAddrSpace = LAddrSpace; 7952 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7953 ResultAddrSpace = RAddrSpace; 7954 else { 7955 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7956 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7957 << RHS.get()->getSourceRange(); 7958 return QualType(); 7959 } 7960 7961 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7962 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7963 lhQual.removeCVRQualifiers(); 7964 rhQual.removeCVRQualifiers(); 7965 7966 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7967 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7968 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7969 // qual types are compatible iff 7970 // * corresponded types are compatible 7971 // * CVR qualifiers are equal 7972 // * address spaces are equal 7973 // Thus for conditional operator we merge CVR and address space unqualified 7974 // pointees and if there is a composite type we return a pointer to it with 7975 // merged qualifiers. 7976 LHSCastKind = 7977 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7978 RHSCastKind = 7979 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7980 lhQual.removeAddressSpace(); 7981 rhQual.removeAddressSpace(); 7982 7983 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7984 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7985 7986 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7987 7988 if (CompositeTy.isNull()) { 7989 // In this situation, we assume void* type. No especially good 7990 // reason, but this is what gcc does, and we do have to pick 7991 // to get a consistent AST. 7992 QualType incompatTy; 7993 incompatTy = S.Context.getPointerType( 7994 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7995 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7996 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7997 7998 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7999 // for casts between types with incompatible address space qualifiers. 8000 // For the following code the compiler produces casts between global and 8001 // local address spaces of the corresponded innermost pointees: 8002 // local int *global *a; 8003 // global int *global *b; 8004 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 8005 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 8006 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8007 << RHS.get()->getSourceRange(); 8008 8009 return incompatTy; 8010 } 8011 8012 // The pointer types are compatible. 8013 // In case of OpenCL ResultTy should have the address space qualifier 8014 // which is a superset of address spaces of both the 2nd and the 3rd 8015 // operands of the conditional operator. 8016 QualType ResultTy = [&, ResultAddrSpace]() { 8017 if (S.getLangOpts().OpenCL) { 8018 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 8019 CompositeQuals.setAddressSpace(ResultAddrSpace); 8020 return S.Context 8021 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 8022 .withCVRQualifiers(MergedCVRQual); 8023 } 8024 return CompositeTy.withCVRQualifiers(MergedCVRQual); 8025 }(); 8026 if (IsBlockPointer) 8027 ResultTy = S.Context.getBlockPointerType(ResultTy); 8028 else 8029 ResultTy = S.Context.getPointerType(ResultTy); 8030 8031 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 8032 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 8033 return ResultTy; 8034 } 8035 8036 /// Return the resulting type when the operands are both block pointers. 8037 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 8038 ExprResult &LHS, 8039 ExprResult &RHS, 8040 SourceLocation Loc) { 8041 QualType LHSTy = LHS.get()->getType(); 8042 QualType RHSTy = RHS.get()->getType(); 8043 8044 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 8045 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 8046 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 8047 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8048 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8049 return destType; 8050 } 8051 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 8052 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8053 << RHS.get()->getSourceRange(); 8054 return QualType(); 8055 } 8056 8057 // We have 2 block pointer types. 8058 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8059 } 8060 8061 /// Return the resulting type when the operands are both pointers. 8062 static QualType 8063 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8064 ExprResult &RHS, 8065 SourceLocation Loc) { 8066 // get the pointer types 8067 QualType LHSTy = LHS.get()->getType(); 8068 QualType RHSTy = RHS.get()->getType(); 8069 8070 // get the "pointed to" types 8071 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8072 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8073 8074 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8075 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8076 // Figure out necessary qualifiers (C99 6.5.15p6) 8077 QualType destPointee 8078 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8079 QualType destType = S.Context.getPointerType(destPointee); 8080 // Add qualifiers if necessary. 8081 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8082 // Promote to void*. 8083 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8084 return destType; 8085 } 8086 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8087 QualType destPointee 8088 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8089 QualType destType = S.Context.getPointerType(destPointee); 8090 // Add qualifiers if necessary. 8091 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8092 // Promote to void*. 8093 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8094 return destType; 8095 } 8096 8097 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8098 } 8099 8100 /// Return false if the first expression is not an integer and the second 8101 /// expression is not a pointer, true otherwise. 8102 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8103 Expr* PointerExpr, SourceLocation Loc, 8104 bool IsIntFirstExpr) { 8105 if (!PointerExpr->getType()->isPointerType() || 8106 !Int.get()->getType()->isIntegerType()) 8107 return false; 8108 8109 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8110 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8111 8112 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8113 << Expr1->getType() << Expr2->getType() 8114 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8115 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8116 CK_IntegralToPointer); 8117 return true; 8118 } 8119 8120 /// Simple conversion between integer and floating point types. 8121 /// 8122 /// Used when handling the OpenCL conditional operator where the 8123 /// condition is a vector while the other operands are scalar. 8124 /// 8125 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8126 /// types are either integer or floating type. Between the two 8127 /// operands, the type with the higher rank is defined as the "result 8128 /// type". The other operand needs to be promoted to the same type. No 8129 /// other type promotion is allowed. We cannot use 8130 /// UsualArithmeticConversions() for this purpose, since it always 8131 /// promotes promotable types. 8132 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8133 ExprResult &RHS, 8134 SourceLocation QuestionLoc) { 8135 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8136 if (LHS.isInvalid()) 8137 return QualType(); 8138 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8139 if (RHS.isInvalid()) 8140 return QualType(); 8141 8142 // For conversion purposes, we ignore any qualifiers. 8143 // For example, "const float" and "float" are equivalent. 8144 QualType LHSType = 8145 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8146 QualType RHSType = 8147 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8148 8149 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8150 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8151 << LHSType << LHS.get()->getSourceRange(); 8152 return QualType(); 8153 } 8154 8155 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8156 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8157 << RHSType << RHS.get()->getSourceRange(); 8158 return QualType(); 8159 } 8160 8161 // If both types are identical, no conversion is needed. 8162 if (LHSType == RHSType) 8163 return LHSType; 8164 8165 // Now handle "real" floating types (i.e. float, double, long double). 8166 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8167 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8168 /*IsCompAssign = */ false); 8169 8170 // Finally, we have two differing integer types. 8171 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8172 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8173 } 8174 8175 /// Convert scalar operands to a vector that matches the 8176 /// condition in length. 8177 /// 8178 /// Used when handling the OpenCL conditional operator where the 8179 /// condition is a vector while the other operands are scalar. 8180 /// 8181 /// We first compute the "result type" for the scalar operands 8182 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8183 /// into a vector of that type where the length matches the condition 8184 /// vector type. s6.11.6 requires that the element types of the result 8185 /// and the condition must have the same number of bits. 8186 static QualType 8187 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8188 QualType CondTy, SourceLocation QuestionLoc) { 8189 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8190 if (ResTy.isNull()) return QualType(); 8191 8192 const VectorType *CV = CondTy->getAs<VectorType>(); 8193 assert(CV); 8194 8195 // Determine the vector result type 8196 unsigned NumElements = CV->getNumElements(); 8197 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8198 8199 // Ensure that all types have the same number of bits 8200 if (S.Context.getTypeSize(CV->getElementType()) 8201 != S.Context.getTypeSize(ResTy)) { 8202 // Since VectorTy is created internally, it does not pretty print 8203 // with an OpenCL name. Instead, we just print a description. 8204 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8205 SmallString<64> Str; 8206 llvm::raw_svector_ostream OS(Str); 8207 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8208 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8209 << CondTy << OS.str(); 8210 return QualType(); 8211 } 8212 8213 // Convert operands to the vector result type 8214 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8215 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8216 8217 return VectorTy; 8218 } 8219 8220 /// Return false if this is a valid OpenCL condition vector 8221 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8222 SourceLocation QuestionLoc) { 8223 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8224 // integral type. 8225 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8226 assert(CondTy); 8227 QualType EleTy = CondTy->getElementType(); 8228 if (EleTy->isIntegerType()) return false; 8229 8230 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8231 << Cond->getType() << Cond->getSourceRange(); 8232 return true; 8233 } 8234 8235 /// Return false if the vector condition type and the vector 8236 /// result type are compatible. 8237 /// 8238 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8239 /// number of elements, and their element types have the same number 8240 /// of bits. 8241 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8242 SourceLocation QuestionLoc) { 8243 const VectorType *CV = CondTy->getAs<VectorType>(); 8244 const VectorType *RV = VecResTy->getAs<VectorType>(); 8245 assert(CV && RV); 8246 8247 if (CV->getNumElements() != RV->getNumElements()) { 8248 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8249 << CondTy << VecResTy; 8250 return true; 8251 } 8252 8253 QualType CVE = CV->getElementType(); 8254 QualType RVE = RV->getElementType(); 8255 8256 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8257 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8258 << CondTy << VecResTy; 8259 return true; 8260 } 8261 8262 return false; 8263 } 8264 8265 /// Return the resulting type for the conditional operator in 8266 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8267 /// s6.3.i) when the condition is a vector type. 8268 static QualType 8269 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8270 ExprResult &LHS, ExprResult &RHS, 8271 SourceLocation QuestionLoc) { 8272 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8273 if (Cond.isInvalid()) 8274 return QualType(); 8275 QualType CondTy = Cond.get()->getType(); 8276 8277 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8278 return QualType(); 8279 8280 // If either operand is a vector then find the vector type of the 8281 // result as specified in OpenCL v1.1 s6.3.i. 8282 if (LHS.get()->getType()->isVectorType() || 8283 RHS.get()->getType()->isVectorType()) { 8284 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8285 /*isCompAssign*/false, 8286 /*AllowBothBool*/true, 8287 /*AllowBoolConversions*/false); 8288 if (VecResTy.isNull()) return QualType(); 8289 // The result type must match the condition type as specified in 8290 // OpenCL v1.1 s6.11.6. 8291 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8292 return QualType(); 8293 return VecResTy; 8294 } 8295 8296 // Both operands are scalar. 8297 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8298 } 8299 8300 /// Return true if the Expr is block type 8301 static bool checkBlockType(Sema &S, const Expr *E) { 8302 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8303 QualType Ty = CE->getCallee()->getType(); 8304 if (Ty->isBlockPointerType()) { 8305 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8306 return true; 8307 } 8308 } 8309 return false; 8310 } 8311 8312 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8313 /// In that case, LHS = cond. 8314 /// C99 6.5.15 8315 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8316 ExprResult &RHS, ExprValueKind &VK, 8317 ExprObjectKind &OK, 8318 SourceLocation QuestionLoc) { 8319 8320 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8321 if (!LHSResult.isUsable()) return QualType(); 8322 LHS = LHSResult; 8323 8324 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8325 if (!RHSResult.isUsable()) return QualType(); 8326 RHS = RHSResult; 8327 8328 // C++ is sufficiently different to merit its own checker. 8329 if (getLangOpts().CPlusPlus) 8330 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8331 8332 VK = VK_PRValue; 8333 OK = OK_Ordinary; 8334 8335 if (Context.isDependenceAllowed() && 8336 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8337 RHS.get()->isTypeDependent())) { 8338 assert(!getLangOpts().CPlusPlus); 8339 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8340 RHS.get()->containsErrors()) && 8341 "should only occur in error-recovery path."); 8342 return Context.DependentTy; 8343 } 8344 8345 // The OpenCL operator with a vector condition is sufficiently 8346 // different to merit its own checker. 8347 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8348 Cond.get()->getType()->isExtVectorType()) 8349 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8350 8351 // First, check the condition. 8352 Cond = UsualUnaryConversions(Cond.get()); 8353 if (Cond.isInvalid()) 8354 return QualType(); 8355 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8356 return QualType(); 8357 8358 // Now check the two expressions. 8359 if (LHS.get()->getType()->isVectorType() || 8360 RHS.get()->getType()->isVectorType()) 8361 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8362 /*AllowBothBool*/true, 8363 /*AllowBoolConversions*/false); 8364 8365 QualType ResTy = 8366 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8367 if (LHS.isInvalid() || RHS.isInvalid()) 8368 return QualType(); 8369 8370 QualType LHSTy = LHS.get()->getType(); 8371 QualType RHSTy = RHS.get()->getType(); 8372 8373 // Diagnose attempts to convert between __ibm128, __float128 and long double 8374 // where such conversions currently can't be handled. 8375 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8376 Diag(QuestionLoc, 8377 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8378 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8379 return QualType(); 8380 } 8381 8382 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8383 // selection operator (?:). 8384 if (getLangOpts().OpenCL && 8385 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) { 8386 return QualType(); 8387 } 8388 8389 // If both operands have arithmetic type, do the usual arithmetic conversions 8390 // to find a common type: C99 6.5.15p3,5. 8391 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8392 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8393 // different sizes, or between ExtInts and other types. 8394 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8395 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8396 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8397 << RHS.get()->getSourceRange(); 8398 return QualType(); 8399 } 8400 8401 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8402 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8403 8404 return ResTy; 8405 } 8406 8407 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8408 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8409 return LHSTy; 8410 } 8411 8412 // If both operands are the same structure or union type, the result is that 8413 // type. 8414 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8415 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8416 if (LHSRT->getDecl() == RHSRT->getDecl()) 8417 // "If both the operands have structure or union type, the result has 8418 // that type." This implies that CV qualifiers are dropped. 8419 return LHSTy.getUnqualifiedType(); 8420 // FIXME: Type of conditional expression must be complete in C mode. 8421 } 8422 8423 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8424 // The following || allows only one side to be void (a GCC-ism). 8425 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8426 return checkConditionalVoidType(*this, LHS, RHS); 8427 } 8428 8429 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8430 // the type of the other operand." 8431 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8432 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8433 8434 // All objective-c pointer type analysis is done here. 8435 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8436 QuestionLoc); 8437 if (LHS.isInvalid() || RHS.isInvalid()) 8438 return QualType(); 8439 if (!compositeType.isNull()) 8440 return compositeType; 8441 8442 8443 // Handle block pointer types. 8444 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8445 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8446 QuestionLoc); 8447 8448 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8449 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8450 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8451 QuestionLoc); 8452 8453 // GCC compatibility: soften pointer/integer mismatch. Note that 8454 // null pointers have been filtered out by this point. 8455 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8456 /*IsIntFirstExpr=*/true)) 8457 return RHSTy; 8458 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8459 /*IsIntFirstExpr=*/false)) 8460 return LHSTy; 8461 8462 // Allow ?: operations in which both operands have the same 8463 // built-in sizeless type. 8464 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) 8465 return LHSTy; 8466 8467 // Emit a better diagnostic if one of the expressions is a null pointer 8468 // constant and the other is not a pointer type. In this case, the user most 8469 // likely forgot to take the address of the other expression. 8470 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8471 return QualType(); 8472 8473 // Otherwise, the operands are not compatible. 8474 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8475 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8476 << RHS.get()->getSourceRange(); 8477 return QualType(); 8478 } 8479 8480 /// FindCompositeObjCPointerType - Helper method to find composite type of 8481 /// two objective-c pointer types of the two input expressions. 8482 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8483 SourceLocation QuestionLoc) { 8484 QualType LHSTy = LHS.get()->getType(); 8485 QualType RHSTy = RHS.get()->getType(); 8486 8487 // Handle things like Class and struct objc_class*. Here we case the result 8488 // to the pseudo-builtin, because that will be implicitly cast back to the 8489 // redefinition type if an attempt is made to access its fields. 8490 if (LHSTy->isObjCClassType() && 8491 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8492 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8493 return LHSTy; 8494 } 8495 if (RHSTy->isObjCClassType() && 8496 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8497 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8498 return RHSTy; 8499 } 8500 // And the same for struct objc_object* / id 8501 if (LHSTy->isObjCIdType() && 8502 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8503 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8504 return LHSTy; 8505 } 8506 if (RHSTy->isObjCIdType() && 8507 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8508 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8509 return RHSTy; 8510 } 8511 // And the same for struct objc_selector* / SEL 8512 if (Context.isObjCSelType(LHSTy) && 8513 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8514 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8515 return LHSTy; 8516 } 8517 if (Context.isObjCSelType(RHSTy) && 8518 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8519 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8520 return RHSTy; 8521 } 8522 // Check constraints for Objective-C object pointers types. 8523 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8524 8525 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8526 // Two identical object pointer types are always compatible. 8527 return LHSTy; 8528 } 8529 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8530 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8531 QualType compositeType = LHSTy; 8532 8533 // If both operands are interfaces and either operand can be 8534 // assigned to the other, use that type as the composite 8535 // type. This allows 8536 // xxx ? (A*) a : (B*) b 8537 // where B is a subclass of A. 8538 // 8539 // Additionally, as for assignment, if either type is 'id' 8540 // allow silent coercion. Finally, if the types are 8541 // incompatible then make sure to use 'id' as the composite 8542 // type so the result is acceptable for sending messages to. 8543 8544 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8545 // It could return the composite type. 8546 if (!(compositeType = 8547 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8548 // Nothing more to do. 8549 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8550 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8551 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8552 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8553 } else if ((LHSOPT->isObjCQualifiedIdType() || 8554 RHSOPT->isObjCQualifiedIdType()) && 8555 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8556 true)) { 8557 // Need to handle "id<xx>" explicitly. 8558 // GCC allows qualified id and any Objective-C type to devolve to 8559 // id. Currently localizing to here until clear this should be 8560 // part of ObjCQualifiedIdTypesAreCompatible. 8561 compositeType = Context.getObjCIdType(); 8562 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8563 compositeType = Context.getObjCIdType(); 8564 } else { 8565 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8566 << LHSTy << RHSTy 8567 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8568 QualType incompatTy = Context.getObjCIdType(); 8569 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8570 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8571 return incompatTy; 8572 } 8573 // The object pointer types are compatible. 8574 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8575 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8576 return compositeType; 8577 } 8578 // Check Objective-C object pointer types and 'void *' 8579 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8580 if (getLangOpts().ObjCAutoRefCount) { 8581 // ARC forbids the implicit conversion of object pointers to 'void *', 8582 // so these types are not compatible. 8583 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8584 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8585 LHS = RHS = true; 8586 return QualType(); 8587 } 8588 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8589 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8590 QualType destPointee 8591 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8592 QualType destType = Context.getPointerType(destPointee); 8593 // Add qualifiers if necessary. 8594 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8595 // Promote to void*. 8596 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8597 return destType; 8598 } 8599 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8600 if (getLangOpts().ObjCAutoRefCount) { 8601 // ARC forbids the implicit conversion of object pointers to 'void *', 8602 // so these types are not compatible. 8603 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8604 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8605 LHS = RHS = true; 8606 return QualType(); 8607 } 8608 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8609 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8610 QualType destPointee 8611 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8612 QualType destType = Context.getPointerType(destPointee); 8613 // Add qualifiers if necessary. 8614 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8615 // Promote to void*. 8616 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8617 return destType; 8618 } 8619 return QualType(); 8620 } 8621 8622 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8623 /// ParenRange in parentheses. 8624 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8625 const PartialDiagnostic &Note, 8626 SourceRange ParenRange) { 8627 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8628 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8629 EndLoc.isValid()) { 8630 Self.Diag(Loc, Note) 8631 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8632 << FixItHint::CreateInsertion(EndLoc, ")"); 8633 } else { 8634 // We can't display the parentheses, so just show the bare note. 8635 Self.Diag(Loc, Note) << ParenRange; 8636 } 8637 } 8638 8639 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8640 return BinaryOperator::isAdditiveOp(Opc) || 8641 BinaryOperator::isMultiplicativeOp(Opc) || 8642 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8643 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8644 // not any of the logical operators. Bitwise-xor is commonly used as a 8645 // logical-xor because there is no logical-xor operator. The logical 8646 // operators, including uses of xor, have a high false positive rate for 8647 // precedence warnings. 8648 } 8649 8650 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8651 /// expression, either using a built-in or overloaded operator, 8652 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8653 /// expression. 8654 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8655 Expr **RHSExprs) { 8656 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8657 E = E->IgnoreImpCasts(); 8658 E = E->IgnoreConversionOperatorSingleStep(); 8659 E = E->IgnoreImpCasts(); 8660 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8661 E = MTE->getSubExpr(); 8662 E = E->IgnoreImpCasts(); 8663 } 8664 8665 // Built-in binary operator. 8666 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8667 if (IsArithmeticOp(OP->getOpcode())) { 8668 *Opcode = OP->getOpcode(); 8669 *RHSExprs = OP->getRHS(); 8670 return true; 8671 } 8672 } 8673 8674 // Overloaded operator. 8675 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8676 if (Call->getNumArgs() != 2) 8677 return false; 8678 8679 // Make sure this is really a binary operator that is safe to pass into 8680 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8681 OverloadedOperatorKind OO = Call->getOperator(); 8682 if (OO < OO_Plus || OO > OO_Arrow || 8683 OO == OO_PlusPlus || OO == OO_MinusMinus) 8684 return false; 8685 8686 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8687 if (IsArithmeticOp(OpKind)) { 8688 *Opcode = OpKind; 8689 *RHSExprs = Call->getArg(1); 8690 return true; 8691 } 8692 } 8693 8694 return false; 8695 } 8696 8697 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8698 /// or is a logical expression such as (x==y) which has int type, but is 8699 /// commonly interpreted as boolean. 8700 static bool ExprLooksBoolean(Expr *E) { 8701 E = E->IgnoreParenImpCasts(); 8702 8703 if (E->getType()->isBooleanType()) 8704 return true; 8705 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8706 return OP->isComparisonOp() || OP->isLogicalOp(); 8707 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8708 return OP->getOpcode() == UO_LNot; 8709 if (E->getType()->isPointerType()) 8710 return true; 8711 // FIXME: What about overloaded operator calls returning "unspecified boolean 8712 // type"s (commonly pointer-to-members)? 8713 8714 return false; 8715 } 8716 8717 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8718 /// and binary operator are mixed in a way that suggests the programmer assumed 8719 /// the conditional operator has higher precedence, for example: 8720 /// "int x = a + someBinaryCondition ? 1 : 2". 8721 static void DiagnoseConditionalPrecedence(Sema &Self, 8722 SourceLocation OpLoc, 8723 Expr *Condition, 8724 Expr *LHSExpr, 8725 Expr *RHSExpr) { 8726 BinaryOperatorKind CondOpcode; 8727 Expr *CondRHS; 8728 8729 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8730 return; 8731 if (!ExprLooksBoolean(CondRHS)) 8732 return; 8733 8734 // The condition is an arithmetic binary expression, with a right- 8735 // hand side that looks boolean, so warn. 8736 8737 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8738 ? diag::warn_precedence_bitwise_conditional 8739 : diag::warn_precedence_conditional; 8740 8741 Self.Diag(OpLoc, DiagID) 8742 << Condition->getSourceRange() 8743 << BinaryOperator::getOpcodeStr(CondOpcode); 8744 8745 SuggestParentheses( 8746 Self, OpLoc, 8747 Self.PDiag(diag::note_precedence_silence) 8748 << BinaryOperator::getOpcodeStr(CondOpcode), 8749 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8750 8751 SuggestParentheses(Self, OpLoc, 8752 Self.PDiag(diag::note_precedence_conditional_first), 8753 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8754 } 8755 8756 /// Compute the nullability of a conditional expression. 8757 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8758 QualType LHSTy, QualType RHSTy, 8759 ASTContext &Ctx) { 8760 if (!ResTy->isAnyPointerType()) 8761 return ResTy; 8762 8763 auto GetNullability = [&Ctx](QualType Ty) { 8764 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8765 if (Kind) { 8766 // For our purposes, treat _Nullable_result as _Nullable. 8767 if (*Kind == NullabilityKind::NullableResult) 8768 return NullabilityKind::Nullable; 8769 return *Kind; 8770 } 8771 return NullabilityKind::Unspecified; 8772 }; 8773 8774 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8775 NullabilityKind MergedKind; 8776 8777 // Compute nullability of a binary conditional expression. 8778 if (IsBin) { 8779 if (LHSKind == NullabilityKind::NonNull) 8780 MergedKind = NullabilityKind::NonNull; 8781 else 8782 MergedKind = RHSKind; 8783 // Compute nullability of a normal conditional expression. 8784 } else { 8785 if (LHSKind == NullabilityKind::Nullable || 8786 RHSKind == NullabilityKind::Nullable) 8787 MergedKind = NullabilityKind::Nullable; 8788 else if (LHSKind == NullabilityKind::NonNull) 8789 MergedKind = RHSKind; 8790 else if (RHSKind == NullabilityKind::NonNull) 8791 MergedKind = LHSKind; 8792 else 8793 MergedKind = NullabilityKind::Unspecified; 8794 } 8795 8796 // Return if ResTy already has the correct nullability. 8797 if (GetNullability(ResTy) == MergedKind) 8798 return ResTy; 8799 8800 // Strip all nullability from ResTy. 8801 while (ResTy->getNullability(Ctx)) 8802 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8803 8804 // Create a new AttributedType with the new nullability kind. 8805 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8806 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8807 } 8808 8809 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8810 /// in the case of a the GNU conditional expr extension. 8811 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8812 SourceLocation ColonLoc, 8813 Expr *CondExpr, Expr *LHSExpr, 8814 Expr *RHSExpr) { 8815 if (!Context.isDependenceAllowed()) { 8816 // C cannot handle TypoExpr nodes in the condition because it 8817 // doesn't handle dependent types properly, so make sure any TypoExprs have 8818 // been dealt with before checking the operands. 8819 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8820 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8821 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8822 8823 if (!CondResult.isUsable()) 8824 return ExprError(); 8825 8826 if (LHSExpr) { 8827 if (!LHSResult.isUsable()) 8828 return ExprError(); 8829 } 8830 8831 if (!RHSResult.isUsable()) 8832 return ExprError(); 8833 8834 CondExpr = CondResult.get(); 8835 LHSExpr = LHSResult.get(); 8836 RHSExpr = RHSResult.get(); 8837 } 8838 8839 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8840 // was the condition. 8841 OpaqueValueExpr *opaqueValue = nullptr; 8842 Expr *commonExpr = nullptr; 8843 if (!LHSExpr) { 8844 commonExpr = CondExpr; 8845 // Lower out placeholder types first. This is important so that we don't 8846 // try to capture a placeholder. This happens in few cases in C++; such 8847 // as Objective-C++'s dictionary subscripting syntax. 8848 if (commonExpr->hasPlaceholderType()) { 8849 ExprResult result = CheckPlaceholderExpr(commonExpr); 8850 if (!result.isUsable()) return ExprError(); 8851 commonExpr = result.get(); 8852 } 8853 // We usually want to apply unary conversions *before* saving, except 8854 // in the special case of a C++ l-value conditional. 8855 if (!(getLangOpts().CPlusPlus 8856 && !commonExpr->isTypeDependent() 8857 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8858 && commonExpr->isGLValue() 8859 && commonExpr->isOrdinaryOrBitFieldObject() 8860 && RHSExpr->isOrdinaryOrBitFieldObject() 8861 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8862 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8863 if (commonRes.isInvalid()) 8864 return ExprError(); 8865 commonExpr = commonRes.get(); 8866 } 8867 8868 // If the common expression is a class or array prvalue, materialize it 8869 // so that we can safely refer to it multiple times. 8870 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 8871 commonExpr->getType()->isArrayType())) { 8872 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8873 if (MatExpr.isInvalid()) 8874 return ExprError(); 8875 commonExpr = MatExpr.get(); 8876 } 8877 8878 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8879 commonExpr->getType(), 8880 commonExpr->getValueKind(), 8881 commonExpr->getObjectKind(), 8882 commonExpr); 8883 LHSExpr = CondExpr = opaqueValue; 8884 } 8885 8886 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8887 ExprValueKind VK = VK_PRValue; 8888 ExprObjectKind OK = OK_Ordinary; 8889 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8890 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8891 VK, OK, QuestionLoc); 8892 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8893 RHS.isInvalid()) 8894 return ExprError(); 8895 8896 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8897 RHS.get()); 8898 8899 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8900 8901 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8902 Context); 8903 8904 if (!commonExpr) 8905 return new (Context) 8906 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8907 RHS.get(), result, VK, OK); 8908 8909 return new (Context) BinaryConditionalOperator( 8910 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8911 ColonLoc, result, VK, OK); 8912 } 8913 8914 // Check if we have a conversion between incompatible cmse function pointer 8915 // types, that is, a conversion between a function pointer with the 8916 // cmse_nonsecure_call attribute and one without. 8917 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8918 QualType ToType) { 8919 if (const auto *ToFn = 8920 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8921 if (const auto *FromFn = 8922 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8923 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8924 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8925 8926 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8927 } 8928 } 8929 return false; 8930 } 8931 8932 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8933 // being closely modeled after the C99 spec:-). The odd characteristic of this 8934 // routine is it effectively iqnores the qualifiers on the top level pointee. 8935 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8936 // FIXME: add a couple examples in this comment. 8937 static Sema::AssignConvertType 8938 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8939 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8940 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8941 8942 // get the "pointed to" type (ignoring qualifiers at the top level) 8943 const Type *lhptee, *rhptee; 8944 Qualifiers lhq, rhq; 8945 std::tie(lhptee, lhq) = 8946 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8947 std::tie(rhptee, rhq) = 8948 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8949 8950 Sema::AssignConvertType ConvTy = Sema::Compatible; 8951 8952 // C99 6.5.16.1p1: This following citation is common to constraints 8953 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8954 // qualifiers of the type *pointed to* by the right; 8955 8956 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8957 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8958 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8959 // Ignore lifetime for further calculation. 8960 lhq.removeObjCLifetime(); 8961 rhq.removeObjCLifetime(); 8962 } 8963 8964 if (!lhq.compatiblyIncludes(rhq)) { 8965 // Treat address-space mismatches as fatal. 8966 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8967 return Sema::IncompatiblePointerDiscardsQualifiers; 8968 8969 // It's okay to add or remove GC or lifetime qualifiers when converting to 8970 // and from void*. 8971 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8972 .compatiblyIncludes( 8973 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8974 && (lhptee->isVoidType() || rhptee->isVoidType())) 8975 ; // keep old 8976 8977 // Treat lifetime mismatches as fatal. 8978 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8979 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8980 8981 // For GCC/MS compatibility, other qualifier mismatches are treated 8982 // as still compatible in C. 8983 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8984 } 8985 8986 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8987 // incomplete type and the other is a pointer to a qualified or unqualified 8988 // version of void... 8989 if (lhptee->isVoidType()) { 8990 if (rhptee->isIncompleteOrObjectType()) 8991 return ConvTy; 8992 8993 // As an extension, we allow cast to/from void* to function pointer. 8994 assert(rhptee->isFunctionType()); 8995 return Sema::FunctionVoidPointer; 8996 } 8997 8998 if (rhptee->isVoidType()) { 8999 if (lhptee->isIncompleteOrObjectType()) 9000 return ConvTy; 9001 9002 // As an extension, we allow cast to/from void* to function pointer. 9003 assert(lhptee->isFunctionType()); 9004 return Sema::FunctionVoidPointer; 9005 } 9006 9007 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 9008 // unqualified versions of compatible types, ... 9009 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 9010 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 9011 // Check if the pointee types are compatible ignoring the sign. 9012 // We explicitly check for char so that we catch "char" vs 9013 // "unsigned char" on systems where "char" is unsigned. 9014 if (lhptee->isCharType()) 9015 ltrans = S.Context.UnsignedCharTy; 9016 else if (lhptee->hasSignedIntegerRepresentation()) 9017 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 9018 9019 if (rhptee->isCharType()) 9020 rtrans = S.Context.UnsignedCharTy; 9021 else if (rhptee->hasSignedIntegerRepresentation()) 9022 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 9023 9024 if (ltrans == rtrans) { 9025 // Types are compatible ignoring the sign. Qualifier incompatibility 9026 // takes priority over sign incompatibility because the sign 9027 // warning can be disabled. 9028 if (ConvTy != Sema::Compatible) 9029 return ConvTy; 9030 9031 return Sema::IncompatiblePointerSign; 9032 } 9033 9034 // If we are a multi-level pointer, it's possible that our issue is simply 9035 // one of qualification - e.g. char ** -> const char ** is not allowed. If 9036 // the eventual target type is the same and the pointers have the same 9037 // level of indirection, this must be the issue. 9038 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 9039 do { 9040 std::tie(lhptee, lhq) = 9041 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 9042 std::tie(rhptee, rhq) = 9043 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 9044 9045 // Inconsistent address spaces at this point is invalid, even if the 9046 // address spaces would be compatible. 9047 // FIXME: This doesn't catch address space mismatches for pointers of 9048 // different nesting levels, like: 9049 // __local int *** a; 9050 // int ** b = a; 9051 // It's not clear how to actually determine when such pointers are 9052 // invalidly incompatible. 9053 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 9054 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 9055 9056 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 9057 9058 if (lhptee == rhptee) 9059 return Sema::IncompatibleNestedPointerQualifiers; 9060 } 9061 9062 // General pointer incompatibility takes priority over qualifiers. 9063 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9064 return Sema::IncompatibleFunctionPointer; 9065 return Sema::IncompatiblePointer; 9066 } 9067 if (!S.getLangOpts().CPlusPlus && 9068 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9069 return Sema::IncompatibleFunctionPointer; 9070 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9071 return Sema::IncompatibleFunctionPointer; 9072 return ConvTy; 9073 } 9074 9075 /// checkBlockPointerTypesForAssignment - This routine determines whether two 9076 /// block pointer types are compatible or whether a block and normal pointer 9077 /// are compatible. It is more restrict than comparing two function pointer 9078 // types. 9079 static Sema::AssignConvertType 9080 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9081 QualType RHSType) { 9082 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9083 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9084 9085 QualType lhptee, rhptee; 9086 9087 // get the "pointed to" type (ignoring qualifiers at the top level) 9088 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9089 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9090 9091 // In C++, the types have to match exactly. 9092 if (S.getLangOpts().CPlusPlus) 9093 return Sema::IncompatibleBlockPointer; 9094 9095 Sema::AssignConvertType ConvTy = Sema::Compatible; 9096 9097 // For blocks we enforce that qualifiers are identical. 9098 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9099 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9100 if (S.getLangOpts().OpenCL) { 9101 LQuals.removeAddressSpace(); 9102 RQuals.removeAddressSpace(); 9103 } 9104 if (LQuals != RQuals) 9105 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9106 9107 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9108 // assignment. 9109 // The current behavior is similar to C++ lambdas. A block might be 9110 // assigned to a variable iff its return type and parameters are compatible 9111 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9112 // an assignment. Presumably it should behave in way that a function pointer 9113 // assignment does in C, so for each parameter and return type: 9114 // * CVR and address space of LHS should be a superset of CVR and address 9115 // space of RHS. 9116 // * unqualified types should be compatible. 9117 if (S.getLangOpts().OpenCL) { 9118 if (!S.Context.typesAreBlockPointerCompatible( 9119 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9120 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9121 return Sema::IncompatibleBlockPointer; 9122 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9123 return Sema::IncompatibleBlockPointer; 9124 9125 return ConvTy; 9126 } 9127 9128 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9129 /// for assignment compatibility. 9130 static Sema::AssignConvertType 9131 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9132 QualType RHSType) { 9133 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9134 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9135 9136 if (LHSType->isObjCBuiltinType()) { 9137 // Class is not compatible with ObjC object pointers. 9138 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9139 !RHSType->isObjCQualifiedClassType()) 9140 return Sema::IncompatiblePointer; 9141 return Sema::Compatible; 9142 } 9143 if (RHSType->isObjCBuiltinType()) { 9144 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9145 !LHSType->isObjCQualifiedClassType()) 9146 return Sema::IncompatiblePointer; 9147 return Sema::Compatible; 9148 } 9149 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9150 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9151 9152 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9153 // make an exception for id<P> 9154 !LHSType->isObjCQualifiedIdType()) 9155 return Sema::CompatiblePointerDiscardsQualifiers; 9156 9157 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9158 return Sema::Compatible; 9159 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9160 return Sema::IncompatibleObjCQualifiedId; 9161 return Sema::IncompatiblePointer; 9162 } 9163 9164 Sema::AssignConvertType 9165 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9166 QualType LHSType, QualType RHSType) { 9167 // Fake up an opaque expression. We don't actually care about what 9168 // cast operations are required, so if CheckAssignmentConstraints 9169 // adds casts to this they'll be wasted, but fortunately that doesn't 9170 // usually happen on valid code. 9171 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 9172 ExprResult RHSPtr = &RHSExpr; 9173 CastKind K; 9174 9175 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9176 } 9177 9178 /// This helper function returns true if QT is a vector type that has element 9179 /// type ElementType. 9180 static bool isVector(QualType QT, QualType ElementType) { 9181 if (const VectorType *VT = QT->getAs<VectorType>()) 9182 return VT->getElementType().getCanonicalType() == ElementType; 9183 return false; 9184 } 9185 9186 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9187 /// has code to accommodate several GCC extensions when type checking 9188 /// pointers. Here are some objectionable examples that GCC considers warnings: 9189 /// 9190 /// int a, *pint; 9191 /// short *pshort; 9192 /// struct foo *pfoo; 9193 /// 9194 /// pint = pshort; // warning: assignment from incompatible pointer type 9195 /// a = pint; // warning: assignment makes integer from pointer without a cast 9196 /// pint = a; // warning: assignment makes pointer from integer without a cast 9197 /// pint = pfoo; // warning: assignment from incompatible pointer type 9198 /// 9199 /// As a result, the code for dealing with pointers is more complex than the 9200 /// C99 spec dictates. 9201 /// 9202 /// Sets 'Kind' for any result kind except Incompatible. 9203 Sema::AssignConvertType 9204 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9205 CastKind &Kind, bool ConvertRHS) { 9206 QualType RHSType = RHS.get()->getType(); 9207 QualType OrigLHSType = LHSType; 9208 9209 // Get canonical types. We're not formatting these types, just comparing 9210 // them. 9211 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9212 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9213 9214 // Common case: no conversion required. 9215 if (LHSType == RHSType) { 9216 Kind = CK_NoOp; 9217 return Compatible; 9218 } 9219 9220 // If we have an atomic type, try a non-atomic assignment, then just add an 9221 // atomic qualification step. 9222 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9223 Sema::AssignConvertType result = 9224 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9225 if (result != Compatible) 9226 return result; 9227 if (Kind != CK_NoOp && ConvertRHS) 9228 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9229 Kind = CK_NonAtomicToAtomic; 9230 return Compatible; 9231 } 9232 9233 // If the left-hand side is a reference type, then we are in a 9234 // (rare!) case where we've allowed the use of references in C, 9235 // e.g., as a parameter type in a built-in function. In this case, 9236 // just make sure that the type referenced is compatible with the 9237 // right-hand side type. The caller is responsible for adjusting 9238 // LHSType so that the resulting expression does not have reference 9239 // type. 9240 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9241 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9242 Kind = CK_LValueBitCast; 9243 return Compatible; 9244 } 9245 return Incompatible; 9246 } 9247 9248 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9249 // to the same ExtVector type. 9250 if (LHSType->isExtVectorType()) { 9251 if (RHSType->isExtVectorType()) 9252 return Incompatible; 9253 if (RHSType->isArithmeticType()) { 9254 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9255 if (ConvertRHS) 9256 RHS = prepareVectorSplat(LHSType, RHS.get()); 9257 Kind = CK_VectorSplat; 9258 return Compatible; 9259 } 9260 } 9261 9262 // Conversions to or from vector type. 9263 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9264 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9265 // Allow assignments of an AltiVec vector type to an equivalent GCC 9266 // vector type and vice versa 9267 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9268 Kind = CK_BitCast; 9269 return Compatible; 9270 } 9271 9272 // If we are allowing lax vector conversions, and LHS and RHS are both 9273 // vectors, the total size only needs to be the same. This is a bitcast; 9274 // no bits are changed but the result type is different. 9275 if (isLaxVectorConversion(RHSType, LHSType)) { 9276 Kind = CK_BitCast; 9277 return IncompatibleVectors; 9278 } 9279 } 9280 9281 // When the RHS comes from another lax conversion (e.g. binops between 9282 // scalars and vectors) the result is canonicalized as a vector. When the 9283 // LHS is also a vector, the lax is allowed by the condition above. Handle 9284 // the case where LHS is a scalar. 9285 if (LHSType->isScalarType()) { 9286 const VectorType *VecType = RHSType->getAs<VectorType>(); 9287 if (VecType && VecType->getNumElements() == 1 && 9288 isLaxVectorConversion(RHSType, LHSType)) { 9289 ExprResult *VecExpr = &RHS; 9290 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9291 Kind = CK_BitCast; 9292 return Compatible; 9293 } 9294 } 9295 9296 // Allow assignments between fixed-length and sizeless SVE vectors. 9297 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9298 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9299 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9300 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9301 Kind = CK_BitCast; 9302 return Compatible; 9303 } 9304 9305 return Incompatible; 9306 } 9307 9308 // Diagnose attempts to convert between __ibm128, __float128 and long double 9309 // where such conversions currently can't be handled. 9310 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9311 return Incompatible; 9312 9313 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9314 // discards the imaginary part. 9315 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9316 !LHSType->getAs<ComplexType>()) 9317 return Incompatible; 9318 9319 // Arithmetic conversions. 9320 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9321 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9322 if (ConvertRHS) 9323 Kind = PrepareScalarCast(RHS, LHSType); 9324 return Compatible; 9325 } 9326 9327 // Conversions to normal pointers. 9328 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9329 // U* -> T* 9330 if (isa<PointerType>(RHSType)) { 9331 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9332 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9333 if (AddrSpaceL != AddrSpaceR) 9334 Kind = CK_AddressSpaceConversion; 9335 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9336 Kind = CK_NoOp; 9337 else 9338 Kind = CK_BitCast; 9339 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9340 } 9341 9342 // int -> T* 9343 if (RHSType->isIntegerType()) { 9344 Kind = CK_IntegralToPointer; // FIXME: null? 9345 return IntToPointer; 9346 } 9347 9348 // C pointers are not compatible with ObjC object pointers, 9349 // with two exceptions: 9350 if (isa<ObjCObjectPointerType>(RHSType)) { 9351 // - conversions to void* 9352 if (LHSPointer->getPointeeType()->isVoidType()) { 9353 Kind = CK_BitCast; 9354 return Compatible; 9355 } 9356 9357 // - conversions from 'Class' to the redefinition type 9358 if (RHSType->isObjCClassType() && 9359 Context.hasSameType(LHSType, 9360 Context.getObjCClassRedefinitionType())) { 9361 Kind = CK_BitCast; 9362 return Compatible; 9363 } 9364 9365 Kind = CK_BitCast; 9366 return IncompatiblePointer; 9367 } 9368 9369 // U^ -> void* 9370 if (RHSType->getAs<BlockPointerType>()) { 9371 if (LHSPointer->getPointeeType()->isVoidType()) { 9372 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9373 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9374 ->getPointeeType() 9375 .getAddressSpace(); 9376 Kind = 9377 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9378 return Compatible; 9379 } 9380 } 9381 9382 return Incompatible; 9383 } 9384 9385 // Conversions to block pointers. 9386 if (isa<BlockPointerType>(LHSType)) { 9387 // U^ -> T^ 9388 if (RHSType->isBlockPointerType()) { 9389 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9390 ->getPointeeType() 9391 .getAddressSpace(); 9392 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9393 ->getPointeeType() 9394 .getAddressSpace(); 9395 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9396 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9397 } 9398 9399 // int or null -> T^ 9400 if (RHSType->isIntegerType()) { 9401 Kind = CK_IntegralToPointer; // FIXME: null 9402 return IntToBlockPointer; 9403 } 9404 9405 // id -> T^ 9406 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9407 Kind = CK_AnyPointerToBlockPointerCast; 9408 return Compatible; 9409 } 9410 9411 // void* -> T^ 9412 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9413 if (RHSPT->getPointeeType()->isVoidType()) { 9414 Kind = CK_AnyPointerToBlockPointerCast; 9415 return Compatible; 9416 } 9417 9418 return Incompatible; 9419 } 9420 9421 // Conversions to Objective-C pointers. 9422 if (isa<ObjCObjectPointerType>(LHSType)) { 9423 // A* -> B* 9424 if (RHSType->isObjCObjectPointerType()) { 9425 Kind = CK_BitCast; 9426 Sema::AssignConvertType result = 9427 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9428 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9429 result == Compatible && 9430 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9431 result = IncompatibleObjCWeakRef; 9432 return result; 9433 } 9434 9435 // int or null -> A* 9436 if (RHSType->isIntegerType()) { 9437 Kind = CK_IntegralToPointer; // FIXME: null 9438 return IntToPointer; 9439 } 9440 9441 // In general, C pointers are not compatible with ObjC object pointers, 9442 // with two exceptions: 9443 if (isa<PointerType>(RHSType)) { 9444 Kind = CK_CPointerToObjCPointerCast; 9445 9446 // - conversions from 'void*' 9447 if (RHSType->isVoidPointerType()) { 9448 return Compatible; 9449 } 9450 9451 // - conversions to 'Class' from its redefinition type 9452 if (LHSType->isObjCClassType() && 9453 Context.hasSameType(RHSType, 9454 Context.getObjCClassRedefinitionType())) { 9455 return Compatible; 9456 } 9457 9458 return IncompatiblePointer; 9459 } 9460 9461 // Only under strict condition T^ is compatible with an Objective-C pointer. 9462 if (RHSType->isBlockPointerType() && 9463 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9464 if (ConvertRHS) 9465 maybeExtendBlockObject(RHS); 9466 Kind = CK_BlockPointerToObjCPointerCast; 9467 return Compatible; 9468 } 9469 9470 return Incompatible; 9471 } 9472 9473 // Conversions from pointers that are not covered by the above. 9474 if (isa<PointerType>(RHSType)) { 9475 // T* -> _Bool 9476 if (LHSType == Context.BoolTy) { 9477 Kind = CK_PointerToBoolean; 9478 return Compatible; 9479 } 9480 9481 // T* -> int 9482 if (LHSType->isIntegerType()) { 9483 Kind = CK_PointerToIntegral; 9484 return PointerToInt; 9485 } 9486 9487 return Incompatible; 9488 } 9489 9490 // Conversions from Objective-C pointers that are not covered by the above. 9491 if (isa<ObjCObjectPointerType>(RHSType)) { 9492 // T* -> _Bool 9493 if (LHSType == Context.BoolTy) { 9494 Kind = CK_PointerToBoolean; 9495 return Compatible; 9496 } 9497 9498 // T* -> int 9499 if (LHSType->isIntegerType()) { 9500 Kind = CK_PointerToIntegral; 9501 return PointerToInt; 9502 } 9503 9504 return Incompatible; 9505 } 9506 9507 // struct A -> struct B 9508 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9509 if (Context.typesAreCompatible(LHSType, RHSType)) { 9510 Kind = CK_NoOp; 9511 return Compatible; 9512 } 9513 } 9514 9515 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9516 Kind = CK_IntToOCLSampler; 9517 return Compatible; 9518 } 9519 9520 return Incompatible; 9521 } 9522 9523 /// Constructs a transparent union from an expression that is 9524 /// used to initialize the transparent union. 9525 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9526 ExprResult &EResult, QualType UnionType, 9527 FieldDecl *Field) { 9528 // Build an initializer list that designates the appropriate member 9529 // of the transparent union. 9530 Expr *E = EResult.get(); 9531 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9532 E, SourceLocation()); 9533 Initializer->setType(UnionType); 9534 Initializer->setInitializedFieldInUnion(Field); 9535 9536 // Build a compound literal constructing a value of the transparent 9537 // union type from this initializer list. 9538 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9539 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9540 VK_PRValue, Initializer, false); 9541 } 9542 9543 Sema::AssignConvertType 9544 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9545 ExprResult &RHS) { 9546 QualType RHSType = RHS.get()->getType(); 9547 9548 // If the ArgType is a Union type, we want to handle a potential 9549 // transparent_union GCC extension. 9550 const RecordType *UT = ArgType->getAsUnionType(); 9551 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9552 return Incompatible; 9553 9554 // The field to initialize within the transparent union. 9555 RecordDecl *UD = UT->getDecl(); 9556 FieldDecl *InitField = nullptr; 9557 // It's compatible if the expression matches any of the fields. 9558 for (auto *it : UD->fields()) { 9559 if (it->getType()->isPointerType()) { 9560 // If the transparent union contains a pointer type, we allow: 9561 // 1) void pointer 9562 // 2) null pointer constant 9563 if (RHSType->isPointerType()) 9564 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9565 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9566 InitField = it; 9567 break; 9568 } 9569 9570 if (RHS.get()->isNullPointerConstant(Context, 9571 Expr::NPC_ValueDependentIsNull)) { 9572 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9573 CK_NullToPointer); 9574 InitField = it; 9575 break; 9576 } 9577 } 9578 9579 CastKind Kind; 9580 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9581 == Compatible) { 9582 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9583 InitField = it; 9584 break; 9585 } 9586 } 9587 9588 if (!InitField) 9589 return Incompatible; 9590 9591 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9592 return Compatible; 9593 } 9594 9595 Sema::AssignConvertType 9596 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9597 bool Diagnose, 9598 bool DiagnoseCFAudited, 9599 bool ConvertRHS) { 9600 // We need to be able to tell the caller whether we diagnosed a problem, if 9601 // they ask us to issue diagnostics. 9602 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9603 9604 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9605 // we can't avoid *all* modifications at the moment, so we need some somewhere 9606 // to put the updated value. 9607 ExprResult LocalRHS = CallerRHS; 9608 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9609 9610 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9611 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9612 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9613 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9614 Diag(RHS.get()->getExprLoc(), 9615 diag::warn_noderef_to_dereferenceable_pointer) 9616 << RHS.get()->getSourceRange(); 9617 } 9618 } 9619 } 9620 9621 if (getLangOpts().CPlusPlus) { 9622 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9623 // C++ 5.17p3: If the left operand is not of class type, the 9624 // expression is implicitly converted (C++ 4) to the 9625 // cv-unqualified type of the left operand. 9626 QualType RHSType = RHS.get()->getType(); 9627 if (Diagnose) { 9628 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9629 AA_Assigning); 9630 } else { 9631 ImplicitConversionSequence ICS = 9632 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9633 /*SuppressUserConversions=*/false, 9634 AllowedExplicit::None, 9635 /*InOverloadResolution=*/false, 9636 /*CStyle=*/false, 9637 /*AllowObjCWritebackConversion=*/false); 9638 if (ICS.isFailure()) 9639 return Incompatible; 9640 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9641 ICS, AA_Assigning); 9642 } 9643 if (RHS.isInvalid()) 9644 return Incompatible; 9645 Sema::AssignConvertType result = Compatible; 9646 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9647 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9648 result = IncompatibleObjCWeakRef; 9649 return result; 9650 } 9651 9652 // FIXME: Currently, we fall through and treat C++ classes like C 9653 // structures. 9654 // FIXME: We also fall through for atomics; not sure what should 9655 // happen there, though. 9656 } else if (RHS.get()->getType() == Context.OverloadTy) { 9657 // As a set of extensions to C, we support overloading on functions. These 9658 // functions need to be resolved here. 9659 DeclAccessPair DAP; 9660 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9661 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9662 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9663 else 9664 return Incompatible; 9665 } 9666 9667 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9668 // a null pointer constant. 9669 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9670 LHSType->isBlockPointerType()) && 9671 RHS.get()->isNullPointerConstant(Context, 9672 Expr::NPC_ValueDependentIsNull)) { 9673 if (Diagnose || ConvertRHS) { 9674 CastKind Kind; 9675 CXXCastPath Path; 9676 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9677 /*IgnoreBaseAccess=*/false, Diagnose); 9678 if (ConvertRHS) 9679 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 9680 } 9681 return Compatible; 9682 } 9683 9684 // OpenCL queue_t type assignment. 9685 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9686 Context, Expr::NPC_ValueDependentIsNull)) { 9687 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9688 return Compatible; 9689 } 9690 9691 // This check seems unnatural, however it is necessary to ensure the proper 9692 // conversion of functions/arrays. If the conversion were done for all 9693 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9694 // expressions that suppress this implicit conversion (&, sizeof). 9695 // 9696 // Suppress this for references: C++ 8.5.3p5. 9697 if (!LHSType->isReferenceType()) { 9698 // FIXME: We potentially allocate here even if ConvertRHS is false. 9699 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9700 if (RHS.isInvalid()) 9701 return Incompatible; 9702 } 9703 CastKind Kind; 9704 Sema::AssignConvertType result = 9705 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9706 9707 // C99 6.5.16.1p2: The value of the right operand is converted to the 9708 // type of the assignment expression. 9709 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9710 // so that we can use references in built-in functions even in C. 9711 // The getNonReferenceType() call makes sure that the resulting expression 9712 // does not have reference type. 9713 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9714 QualType Ty = LHSType.getNonLValueExprType(Context); 9715 Expr *E = RHS.get(); 9716 9717 // Check for various Objective-C errors. If we are not reporting 9718 // diagnostics and just checking for errors, e.g., during overload 9719 // resolution, return Incompatible to indicate the failure. 9720 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9721 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9722 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9723 if (!Diagnose) 9724 return Incompatible; 9725 } 9726 if (getLangOpts().ObjC && 9727 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9728 E->getType(), E, Diagnose) || 9729 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9730 if (!Diagnose) 9731 return Incompatible; 9732 // Replace the expression with a corrected version and continue so we 9733 // can find further errors. 9734 RHS = E; 9735 return Compatible; 9736 } 9737 9738 if (ConvertRHS) 9739 RHS = ImpCastExprToType(E, Ty, Kind); 9740 } 9741 9742 return result; 9743 } 9744 9745 namespace { 9746 /// The original operand to an operator, prior to the application of the usual 9747 /// arithmetic conversions and converting the arguments of a builtin operator 9748 /// candidate. 9749 struct OriginalOperand { 9750 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9751 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9752 Op = MTE->getSubExpr(); 9753 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9754 Op = BTE->getSubExpr(); 9755 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9756 Orig = ICE->getSubExprAsWritten(); 9757 Conversion = ICE->getConversionFunction(); 9758 } 9759 } 9760 9761 QualType getType() const { return Orig->getType(); } 9762 9763 Expr *Orig; 9764 NamedDecl *Conversion; 9765 }; 9766 } 9767 9768 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9769 ExprResult &RHS) { 9770 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9771 9772 Diag(Loc, diag::err_typecheck_invalid_operands) 9773 << OrigLHS.getType() << OrigRHS.getType() 9774 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9775 9776 // If a user-defined conversion was applied to either of the operands prior 9777 // to applying the built-in operator rules, tell the user about it. 9778 if (OrigLHS.Conversion) { 9779 Diag(OrigLHS.Conversion->getLocation(), 9780 diag::note_typecheck_invalid_operands_converted) 9781 << 0 << LHS.get()->getType(); 9782 } 9783 if (OrigRHS.Conversion) { 9784 Diag(OrigRHS.Conversion->getLocation(), 9785 diag::note_typecheck_invalid_operands_converted) 9786 << 1 << RHS.get()->getType(); 9787 } 9788 9789 return QualType(); 9790 } 9791 9792 // Diagnose cases where a scalar was implicitly converted to a vector and 9793 // diagnose the underlying types. Otherwise, diagnose the error 9794 // as invalid vector logical operands for non-C++ cases. 9795 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9796 ExprResult &RHS) { 9797 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9798 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9799 9800 bool LHSNatVec = LHSType->isVectorType(); 9801 bool RHSNatVec = RHSType->isVectorType(); 9802 9803 if (!(LHSNatVec && RHSNatVec)) { 9804 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9805 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9806 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9807 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9808 << Vector->getSourceRange(); 9809 return QualType(); 9810 } 9811 9812 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9813 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9814 << RHS.get()->getSourceRange(); 9815 9816 return QualType(); 9817 } 9818 9819 /// Try to convert a value of non-vector type to a vector type by converting 9820 /// the type to the element type of the vector and then performing a splat. 9821 /// If the language is OpenCL, we only use conversions that promote scalar 9822 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9823 /// for float->int. 9824 /// 9825 /// OpenCL V2.0 6.2.6.p2: 9826 /// An error shall occur if any scalar operand type has greater rank 9827 /// than the type of the vector element. 9828 /// 9829 /// \param scalar - if non-null, actually perform the conversions 9830 /// \return true if the operation fails (but without diagnosing the failure) 9831 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9832 QualType scalarTy, 9833 QualType vectorEltTy, 9834 QualType vectorTy, 9835 unsigned &DiagID) { 9836 // The conversion to apply to the scalar before splatting it, 9837 // if necessary. 9838 CastKind scalarCast = CK_NoOp; 9839 9840 if (vectorEltTy->isIntegralType(S.Context)) { 9841 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9842 (scalarTy->isIntegerType() && 9843 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9844 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9845 return true; 9846 } 9847 if (!scalarTy->isIntegralType(S.Context)) 9848 return true; 9849 scalarCast = CK_IntegralCast; 9850 } else if (vectorEltTy->isRealFloatingType()) { 9851 if (scalarTy->isRealFloatingType()) { 9852 if (S.getLangOpts().OpenCL && 9853 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9854 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9855 return true; 9856 } 9857 scalarCast = CK_FloatingCast; 9858 } 9859 else if (scalarTy->isIntegralType(S.Context)) 9860 scalarCast = CK_IntegralToFloating; 9861 else 9862 return true; 9863 } else { 9864 return true; 9865 } 9866 9867 // Adjust scalar if desired. 9868 if (scalar) { 9869 if (scalarCast != CK_NoOp) 9870 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9871 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9872 } 9873 return false; 9874 } 9875 9876 /// Convert vector E to a vector with the same number of elements but different 9877 /// element type. 9878 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9879 const auto *VecTy = E->getType()->getAs<VectorType>(); 9880 assert(VecTy && "Expression E must be a vector"); 9881 QualType NewVecTy = S.Context.getVectorType(ElementType, 9882 VecTy->getNumElements(), 9883 VecTy->getVectorKind()); 9884 9885 // Look through the implicit cast. Return the subexpression if its type is 9886 // NewVecTy. 9887 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9888 if (ICE->getSubExpr()->getType() == NewVecTy) 9889 return ICE->getSubExpr(); 9890 9891 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9892 return S.ImpCastExprToType(E, NewVecTy, Cast); 9893 } 9894 9895 /// Test if a (constant) integer Int can be casted to another integer type 9896 /// IntTy without losing precision. 9897 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9898 QualType OtherIntTy) { 9899 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9900 9901 // Reject cases where the value of the Int is unknown as that would 9902 // possibly cause truncation, but accept cases where the scalar can be 9903 // demoted without loss of precision. 9904 Expr::EvalResult EVResult; 9905 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9906 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9907 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9908 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9909 9910 if (CstInt) { 9911 // If the scalar is constant and is of a higher order and has more active 9912 // bits that the vector element type, reject it. 9913 llvm::APSInt Result = EVResult.Val.getInt(); 9914 unsigned NumBits = IntSigned 9915 ? (Result.isNegative() ? Result.getMinSignedBits() 9916 : Result.getActiveBits()) 9917 : Result.getActiveBits(); 9918 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9919 return true; 9920 9921 // If the signedness of the scalar type and the vector element type 9922 // differs and the number of bits is greater than that of the vector 9923 // element reject it. 9924 return (IntSigned != OtherIntSigned && 9925 NumBits > S.Context.getIntWidth(OtherIntTy)); 9926 } 9927 9928 // Reject cases where the value of the scalar is not constant and it's 9929 // order is greater than that of the vector element type. 9930 return (Order < 0); 9931 } 9932 9933 /// Test if a (constant) integer Int can be casted to floating point type 9934 /// FloatTy without losing precision. 9935 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9936 QualType FloatTy) { 9937 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9938 9939 // Determine if the integer constant can be expressed as a floating point 9940 // number of the appropriate type. 9941 Expr::EvalResult EVResult; 9942 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9943 9944 uint64_t Bits = 0; 9945 if (CstInt) { 9946 // Reject constants that would be truncated if they were converted to 9947 // the floating point type. Test by simple to/from conversion. 9948 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9949 // could be avoided if there was a convertFromAPInt method 9950 // which could signal back if implicit truncation occurred. 9951 llvm::APSInt Result = EVResult.Val.getInt(); 9952 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9953 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9954 llvm::APFloat::rmTowardZero); 9955 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9956 !IntTy->hasSignedIntegerRepresentation()); 9957 bool Ignored = false; 9958 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9959 &Ignored); 9960 if (Result != ConvertBack) 9961 return true; 9962 } else { 9963 // Reject types that cannot be fully encoded into the mantissa of 9964 // the float. 9965 Bits = S.Context.getTypeSize(IntTy); 9966 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9967 S.Context.getFloatTypeSemantics(FloatTy)); 9968 if (Bits > FloatPrec) 9969 return true; 9970 } 9971 9972 return false; 9973 } 9974 9975 /// Attempt to convert and splat Scalar into a vector whose types matches 9976 /// Vector following GCC conversion rules. The rule is that implicit 9977 /// conversion can occur when Scalar can be casted to match Vector's element 9978 /// type without causing truncation of Scalar. 9979 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9980 ExprResult *Vector) { 9981 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9982 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9983 const VectorType *VT = VectorTy->getAs<VectorType>(); 9984 9985 assert(!isa<ExtVectorType>(VT) && 9986 "ExtVectorTypes should not be handled here!"); 9987 9988 QualType VectorEltTy = VT->getElementType(); 9989 9990 // Reject cases where the vector element type or the scalar element type are 9991 // not integral or floating point types. 9992 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9993 return true; 9994 9995 // The conversion to apply to the scalar before splatting it, 9996 // if necessary. 9997 CastKind ScalarCast = CK_NoOp; 9998 9999 // Accept cases where the vector elements are integers and the scalar is 10000 // an integer. 10001 // FIXME: Notionally if the scalar was a floating point value with a precise 10002 // integral representation, we could cast it to an appropriate integer 10003 // type and then perform the rest of the checks here. GCC will perform 10004 // this conversion in some cases as determined by the input language. 10005 // We should accept it on a language independent basis. 10006 if (VectorEltTy->isIntegralType(S.Context) && 10007 ScalarTy->isIntegralType(S.Context) && 10008 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 10009 10010 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 10011 return true; 10012 10013 ScalarCast = CK_IntegralCast; 10014 } else if (VectorEltTy->isIntegralType(S.Context) && 10015 ScalarTy->isRealFloatingType()) { 10016 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 10017 ScalarCast = CK_FloatingToIntegral; 10018 else 10019 return true; 10020 } else if (VectorEltTy->isRealFloatingType()) { 10021 if (ScalarTy->isRealFloatingType()) { 10022 10023 // Reject cases where the scalar type is not a constant and has a higher 10024 // Order than the vector element type. 10025 llvm::APFloat Result(0.0); 10026 10027 // Determine whether this is a constant scalar. In the event that the 10028 // value is dependent (and thus cannot be evaluated by the constant 10029 // evaluator), skip the evaluation. This will then diagnose once the 10030 // expression is instantiated. 10031 bool CstScalar = Scalar->get()->isValueDependent() || 10032 Scalar->get()->EvaluateAsFloat(Result, S.Context); 10033 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 10034 if (!CstScalar && Order < 0) 10035 return true; 10036 10037 // If the scalar cannot be safely casted to the vector element type, 10038 // reject it. 10039 if (CstScalar) { 10040 bool Truncated = false; 10041 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 10042 llvm::APFloat::rmNearestTiesToEven, &Truncated); 10043 if (Truncated) 10044 return true; 10045 } 10046 10047 ScalarCast = CK_FloatingCast; 10048 } else if (ScalarTy->isIntegralType(S.Context)) { 10049 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 10050 return true; 10051 10052 ScalarCast = CK_IntegralToFloating; 10053 } else 10054 return true; 10055 } else if (ScalarTy->isEnumeralType()) 10056 return true; 10057 10058 // Adjust scalar if desired. 10059 if (Scalar) { 10060 if (ScalarCast != CK_NoOp) 10061 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 10062 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 10063 } 10064 return false; 10065 } 10066 10067 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 10068 SourceLocation Loc, bool IsCompAssign, 10069 bool AllowBothBool, 10070 bool AllowBoolConversions) { 10071 if (!IsCompAssign) { 10072 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10073 if (LHS.isInvalid()) 10074 return QualType(); 10075 } 10076 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10077 if (RHS.isInvalid()) 10078 return QualType(); 10079 10080 // For conversion purposes, we ignore any qualifiers. 10081 // For example, "const float" and "float" are equivalent. 10082 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10083 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10084 10085 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10086 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10087 assert(LHSVecType || RHSVecType); 10088 10089 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10090 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10091 return InvalidOperands(Loc, LHS, RHS); 10092 10093 // AltiVec-style "vector bool op vector bool" combinations are allowed 10094 // for some operators but not others. 10095 if (!AllowBothBool && 10096 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10097 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10098 return InvalidOperands(Loc, LHS, RHS); 10099 10100 // If the vector types are identical, return. 10101 if (Context.hasSameType(LHSType, RHSType)) 10102 return LHSType; 10103 10104 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10105 if (LHSVecType && RHSVecType && 10106 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10107 if (isa<ExtVectorType>(LHSVecType)) { 10108 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10109 return LHSType; 10110 } 10111 10112 if (!IsCompAssign) 10113 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10114 return RHSType; 10115 } 10116 10117 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10118 // can be mixed, with the result being the non-bool type. The non-bool 10119 // operand must have integer element type. 10120 if (AllowBoolConversions && LHSVecType && RHSVecType && 10121 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10122 (Context.getTypeSize(LHSVecType->getElementType()) == 10123 Context.getTypeSize(RHSVecType->getElementType()))) { 10124 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10125 LHSVecType->getElementType()->isIntegerType() && 10126 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10127 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10128 return LHSType; 10129 } 10130 if (!IsCompAssign && 10131 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10132 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10133 RHSVecType->getElementType()->isIntegerType()) { 10134 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10135 return RHSType; 10136 } 10137 } 10138 10139 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10140 // since the ambiguity can affect the ABI. 10141 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10142 const VectorType *VecType = SecondType->getAs<VectorType>(); 10143 return FirstType->isSizelessBuiltinType() && VecType && 10144 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10145 VecType->getVectorKind() == 10146 VectorType::SveFixedLengthPredicateVector); 10147 }; 10148 10149 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10150 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10151 return QualType(); 10152 } 10153 10154 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10155 // since the ambiguity can affect the ABI. 10156 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10157 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10158 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10159 10160 if (FirstVecType && SecondVecType) 10161 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10162 (SecondVecType->getVectorKind() == 10163 VectorType::SveFixedLengthDataVector || 10164 SecondVecType->getVectorKind() == 10165 VectorType::SveFixedLengthPredicateVector); 10166 10167 return FirstType->isSizelessBuiltinType() && SecondVecType && 10168 SecondVecType->getVectorKind() == VectorType::GenericVector; 10169 }; 10170 10171 if (IsSveGnuConversion(LHSType, RHSType) || 10172 IsSveGnuConversion(RHSType, LHSType)) { 10173 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10174 return QualType(); 10175 } 10176 10177 // If there's a vector type and a scalar, try to convert the scalar to 10178 // the vector element type and splat. 10179 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10180 if (!RHSVecType) { 10181 if (isa<ExtVectorType>(LHSVecType)) { 10182 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10183 LHSVecType->getElementType(), LHSType, 10184 DiagID)) 10185 return LHSType; 10186 } else { 10187 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10188 return LHSType; 10189 } 10190 } 10191 if (!LHSVecType) { 10192 if (isa<ExtVectorType>(RHSVecType)) { 10193 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10194 LHSType, RHSVecType->getElementType(), 10195 RHSType, DiagID)) 10196 return RHSType; 10197 } else { 10198 if (LHS.get()->isLValue() || 10199 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10200 return RHSType; 10201 } 10202 } 10203 10204 // FIXME: The code below also handles conversion between vectors and 10205 // non-scalars, we should break this down into fine grained specific checks 10206 // and emit proper diagnostics. 10207 QualType VecType = LHSVecType ? LHSType : RHSType; 10208 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10209 QualType OtherType = LHSVecType ? RHSType : LHSType; 10210 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10211 if (isLaxVectorConversion(OtherType, VecType)) { 10212 // If we're allowing lax vector conversions, only the total (data) size 10213 // needs to be the same. For non compound assignment, if one of the types is 10214 // scalar, the result is always the vector type. 10215 if (!IsCompAssign) { 10216 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10217 return VecType; 10218 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10219 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10220 // type. Note that this is already done by non-compound assignments in 10221 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10222 // <1 x T> -> T. The result is also a vector type. 10223 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10224 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10225 ExprResult *RHSExpr = &RHS; 10226 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10227 return VecType; 10228 } 10229 } 10230 10231 // Okay, the expression is invalid. 10232 10233 // If there's a non-vector, non-real operand, diagnose that. 10234 if ((!RHSVecType && !RHSType->isRealType()) || 10235 (!LHSVecType && !LHSType->isRealType())) { 10236 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10237 << LHSType << RHSType 10238 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10239 return QualType(); 10240 } 10241 10242 // OpenCL V1.1 6.2.6.p1: 10243 // If the operands are of more than one vector type, then an error shall 10244 // occur. Implicit conversions between vector types are not permitted, per 10245 // section 6.2.1. 10246 if (getLangOpts().OpenCL && 10247 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10248 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10249 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10250 << RHSType; 10251 return QualType(); 10252 } 10253 10254 10255 // If there is a vector type that is not a ExtVector and a scalar, we reach 10256 // this point if scalar could not be converted to the vector's element type 10257 // without truncation. 10258 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10259 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10260 QualType Scalar = LHSVecType ? RHSType : LHSType; 10261 QualType Vector = LHSVecType ? LHSType : RHSType; 10262 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10263 Diag(Loc, 10264 diag::err_typecheck_vector_not_convertable_implict_truncation) 10265 << ScalarOrVector << Scalar << Vector; 10266 10267 return QualType(); 10268 } 10269 10270 // Otherwise, use the generic diagnostic. 10271 Diag(Loc, DiagID) 10272 << LHSType << RHSType 10273 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10274 return QualType(); 10275 } 10276 10277 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10278 // expression. These are mainly cases where the null pointer is used as an 10279 // integer instead of a pointer. 10280 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10281 SourceLocation Loc, bool IsCompare) { 10282 // The canonical way to check for a GNU null is with isNullPointerConstant, 10283 // but we use a bit of a hack here for speed; this is a relatively 10284 // hot path, and isNullPointerConstant is slow. 10285 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10286 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10287 10288 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10289 10290 // Avoid analyzing cases where the result will either be invalid (and 10291 // diagnosed as such) or entirely valid and not something to warn about. 10292 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10293 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10294 return; 10295 10296 // Comparison operations would not make sense with a null pointer no matter 10297 // what the other expression is. 10298 if (!IsCompare) { 10299 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10300 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10301 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10302 return; 10303 } 10304 10305 // The rest of the operations only make sense with a null pointer 10306 // if the other expression is a pointer. 10307 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10308 NonNullType->canDecayToPointerType()) 10309 return; 10310 10311 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10312 << LHSNull /* LHS is NULL */ << NonNullType 10313 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10314 } 10315 10316 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10317 SourceLocation Loc) { 10318 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10319 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10320 if (!LUE || !RUE) 10321 return; 10322 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10323 RUE->getKind() != UETT_SizeOf) 10324 return; 10325 10326 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10327 QualType LHSTy = LHSArg->getType(); 10328 QualType RHSTy; 10329 10330 if (RUE->isArgumentType()) 10331 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10332 else 10333 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10334 10335 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10336 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10337 return; 10338 10339 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10340 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10341 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10342 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10343 << LHSArgDecl; 10344 } 10345 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10346 QualType ArrayElemTy = ArrayTy->getElementType(); 10347 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10348 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10349 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10350 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10351 return; 10352 S.Diag(Loc, diag::warn_division_sizeof_array) 10353 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10354 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10355 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10356 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10357 << LHSArgDecl; 10358 } 10359 10360 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10361 } 10362 } 10363 10364 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10365 ExprResult &RHS, 10366 SourceLocation Loc, bool IsDiv) { 10367 // Check for division/remainder by zero. 10368 Expr::EvalResult RHSValue; 10369 if (!RHS.get()->isValueDependent() && 10370 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10371 RHSValue.Val.getInt() == 0) 10372 S.DiagRuntimeBehavior(Loc, RHS.get(), 10373 S.PDiag(diag::warn_remainder_division_by_zero) 10374 << IsDiv << RHS.get()->getSourceRange()); 10375 } 10376 10377 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10378 SourceLocation Loc, 10379 bool IsCompAssign, bool IsDiv) { 10380 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10381 10382 QualType LHSTy = LHS.get()->getType(); 10383 QualType RHSTy = RHS.get()->getType(); 10384 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10385 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10386 /*AllowBothBool*/getLangOpts().AltiVec, 10387 /*AllowBoolConversions*/false); 10388 if (!IsDiv && 10389 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10390 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10391 // For division, only matrix-by-scalar is supported. Other combinations with 10392 // matrix types are invalid. 10393 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10394 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10395 10396 QualType compType = UsualArithmeticConversions( 10397 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10398 if (LHS.isInvalid() || RHS.isInvalid()) 10399 return QualType(); 10400 10401 10402 if (compType.isNull() || !compType->isArithmeticType()) 10403 return InvalidOperands(Loc, LHS, RHS); 10404 if (IsDiv) { 10405 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10406 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10407 } 10408 return compType; 10409 } 10410 10411 QualType Sema::CheckRemainderOperands( 10412 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10413 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10414 10415 if (LHS.get()->getType()->isVectorType() || 10416 RHS.get()->getType()->isVectorType()) { 10417 if (LHS.get()->getType()->hasIntegerRepresentation() && 10418 RHS.get()->getType()->hasIntegerRepresentation()) 10419 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10420 /*AllowBothBool*/getLangOpts().AltiVec, 10421 /*AllowBoolConversions*/false); 10422 return InvalidOperands(Loc, LHS, RHS); 10423 } 10424 10425 QualType compType = UsualArithmeticConversions( 10426 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10427 if (LHS.isInvalid() || RHS.isInvalid()) 10428 return QualType(); 10429 10430 if (compType.isNull() || !compType->isIntegerType()) 10431 return InvalidOperands(Loc, LHS, RHS); 10432 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10433 return compType; 10434 } 10435 10436 /// Diagnose invalid arithmetic on two void pointers. 10437 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10438 Expr *LHSExpr, Expr *RHSExpr) { 10439 S.Diag(Loc, S.getLangOpts().CPlusPlus 10440 ? diag::err_typecheck_pointer_arith_void_type 10441 : diag::ext_gnu_void_ptr) 10442 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10443 << RHSExpr->getSourceRange(); 10444 } 10445 10446 /// Diagnose invalid arithmetic on a void pointer. 10447 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10448 Expr *Pointer) { 10449 S.Diag(Loc, S.getLangOpts().CPlusPlus 10450 ? diag::err_typecheck_pointer_arith_void_type 10451 : diag::ext_gnu_void_ptr) 10452 << 0 /* one pointer */ << Pointer->getSourceRange(); 10453 } 10454 10455 /// Diagnose invalid arithmetic on a null pointer. 10456 /// 10457 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10458 /// idiom, which we recognize as a GNU extension. 10459 /// 10460 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10461 Expr *Pointer, bool IsGNUIdiom) { 10462 if (IsGNUIdiom) 10463 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10464 << Pointer->getSourceRange(); 10465 else 10466 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10467 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10468 } 10469 10470 /// Diagnose invalid subraction on a null pointer. 10471 /// 10472 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, 10473 Expr *Pointer, bool BothNull) { 10474 // Null - null is valid in C++ [expr.add]p7 10475 if (BothNull && S.getLangOpts().CPlusPlus) 10476 return; 10477 10478 // Is this s a macro from a system header? 10479 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) 10480 return; 10481 10482 S.Diag(Loc, diag::warn_pointer_sub_null_ptr) 10483 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10484 } 10485 10486 /// Diagnose invalid arithmetic on two function pointers. 10487 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10488 Expr *LHS, Expr *RHS) { 10489 assert(LHS->getType()->isAnyPointerType()); 10490 assert(RHS->getType()->isAnyPointerType()); 10491 S.Diag(Loc, S.getLangOpts().CPlusPlus 10492 ? diag::err_typecheck_pointer_arith_function_type 10493 : diag::ext_gnu_ptr_func_arith) 10494 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10495 // We only show the second type if it differs from the first. 10496 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10497 RHS->getType()) 10498 << RHS->getType()->getPointeeType() 10499 << LHS->getSourceRange() << RHS->getSourceRange(); 10500 } 10501 10502 /// Diagnose invalid arithmetic on a function pointer. 10503 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10504 Expr *Pointer) { 10505 assert(Pointer->getType()->isAnyPointerType()); 10506 S.Diag(Loc, S.getLangOpts().CPlusPlus 10507 ? diag::err_typecheck_pointer_arith_function_type 10508 : diag::ext_gnu_ptr_func_arith) 10509 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10510 << 0 /* one pointer, so only one type */ 10511 << Pointer->getSourceRange(); 10512 } 10513 10514 /// Emit error if Operand is incomplete pointer type 10515 /// 10516 /// \returns True if pointer has incomplete type 10517 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10518 Expr *Operand) { 10519 QualType ResType = Operand->getType(); 10520 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10521 ResType = ResAtomicType->getValueType(); 10522 10523 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10524 QualType PointeeTy = ResType->getPointeeType(); 10525 return S.RequireCompleteSizedType( 10526 Loc, PointeeTy, 10527 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10528 Operand->getSourceRange()); 10529 } 10530 10531 /// Check the validity of an arithmetic pointer operand. 10532 /// 10533 /// If the operand has pointer type, this code will check for pointer types 10534 /// which are invalid in arithmetic operations. These will be diagnosed 10535 /// appropriately, including whether or not the use is supported as an 10536 /// extension. 10537 /// 10538 /// \returns True when the operand is valid to use (even if as an extension). 10539 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10540 Expr *Operand) { 10541 QualType ResType = Operand->getType(); 10542 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10543 ResType = ResAtomicType->getValueType(); 10544 10545 if (!ResType->isAnyPointerType()) return true; 10546 10547 QualType PointeeTy = ResType->getPointeeType(); 10548 if (PointeeTy->isVoidType()) { 10549 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10550 return !S.getLangOpts().CPlusPlus; 10551 } 10552 if (PointeeTy->isFunctionType()) { 10553 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10554 return !S.getLangOpts().CPlusPlus; 10555 } 10556 10557 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10558 10559 return true; 10560 } 10561 10562 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10563 /// operands. 10564 /// 10565 /// This routine will diagnose any invalid arithmetic on pointer operands much 10566 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10567 /// for emitting a single diagnostic even for operations where both LHS and RHS 10568 /// are (potentially problematic) pointers. 10569 /// 10570 /// \returns True when the operand is valid to use (even if as an extension). 10571 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10572 Expr *LHSExpr, Expr *RHSExpr) { 10573 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10574 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10575 if (!isLHSPointer && !isRHSPointer) return true; 10576 10577 QualType LHSPointeeTy, RHSPointeeTy; 10578 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10579 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10580 10581 // if both are pointers check if operation is valid wrt address spaces 10582 if (isLHSPointer && isRHSPointer) { 10583 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10584 S.Diag(Loc, 10585 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10586 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10587 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10588 return false; 10589 } 10590 } 10591 10592 // Check for arithmetic on pointers to incomplete types. 10593 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10594 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10595 if (isLHSVoidPtr || isRHSVoidPtr) { 10596 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10597 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10598 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10599 10600 return !S.getLangOpts().CPlusPlus; 10601 } 10602 10603 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10604 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10605 if (isLHSFuncPtr || isRHSFuncPtr) { 10606 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10607 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10608 RHSExpr); 10609 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10610 10611 return !S.getLangOpts().CPlusPlus; 10612 } 10613 10614 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10615 return false; 10616 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10617 return false; 10618 10619 return true; 10620 } 10621 10622 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10623 /// literal. 10624 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10625 Expr *LHSExpr, Expr *RHSExpr) { 10626 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10627 Expr* IndexExpr = RHSExpr; 10628 if (!StrExpr) { 10629 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10630 IndexExpr = LHSExpr; 10631 } 10632 10633 bool IsStringPlusInt = StrExpr && 10634 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10635 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10636 return; 10637 10638 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10639 Self.Diag(OpLoc, diag::warn_string_plus_int) 10640 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10641 10642 // Only print a fixit for "str" + int, not for int + "str". 10643 if (IndexExpr == RHSExpr) { 10644 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10645 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10646 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10647 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10648 << FixItHint::CreateInsertion(EndLoc, "]"); 10649 } else 10650 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10651 } 10652 10653 /// Emit a warning when adding a char literal to a string. 10654 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10655 Expr *LHSExpr, Expr *RHSExpr) { 10656 const Expr *StringRefExpr = LHSExpr; 10657 const CharacterLiteral *CharExpr = 10658 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10659 10660 if (!CharExpr) { 10661 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10662 StringRefExpr = RHSExpr; 10663 } 10664 10665 if (!CharExpr || !StringRefExpr) 10666 return; 10667 10668 const QualType StringType = StringRefExpr->getType(); 10669 10670 // Return if not a PointerType. 10671 if (!StringType->isAnyPointerType()) 10672 return; 10673 10674 // Return if not a CharacterType. 10675 if (!StringType->getPointeeType()->isAnyCharacterType()) 10676 return; 10677 10678 ASTContext &Ctx = Self.getASTContext(); 10679 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10680 10681 const QualType CharType = CharExpr->getType(); 10682 if (!CharType->isAnyCharacterType() && 10683 CharType->isIntegerType() && 10684 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10685 Self.Diag(OpLoc, diag::warn_string_plus_char) 10686 << DiagRange << Ctx.CharTy; 10687 } else { 10688 Self.Diag(OpLoc, diag::warn_string_plus_char) 10689 << DiagRange << CharExpr->getType(); 10690 } 10691 10692 // Only print a fixit for str + char, not for char + str. 10693 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10694 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10695 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10696 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10697 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10698 << FixItHint::CreateInsertion(EndLoc, "]"); 10699 } else { 10700 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10701 } 10702 } 10703 10704 /// Emit error when two pointers are incompatible. 10705 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10706 Expr *LHSExpr, Expr *RHSExpr) { 10707 assert(LHSExpr->getType()->isAnyPointerType()); 10708 assert(RHSExpr->getType()->isAnyPointerType()); 10709 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10710 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10711 << RHSExpr->getSourceRange(); 10712 } 10713 10714 // C99 6.5.6 10715 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10716 SourceLocation Loc, BinaryOperatorKind Opc, 10717 QualType* CompLHSTy) { 10718 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10719 10720 if (LHS.get()->getType()->isVectorType() || 10721 RHS.get()->getType()->isVectorType()) { 10722 QualType compType = CheckVectorOperands( 10723 LHS, RHS, Loc, CompLHSTy, 10724 /*AllowBothBool*/getLangOpts().AltiVec, 10725 /*AllowBoolConversions*/getLangOpts().ZVector); 10726 if (CompLHSTy) *CompLHSTy = compType; 10727 return compType; 10728 } 10729 10730 if (LHS.get()->getType()->isConstantMatrixType() || 10731 RHS.get()->getType()->isConstantMatrixType()) { 10732 QualType compType = 10733 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10734 if (CompLHSTy) 10735 *CompLHSTy = compType; 10736 return compType; 10737 } 10738 10739 QualType compType = UsualArithmeticConversions( 10740 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10741 if (LHS.isInvalid() || RHS.isInvalid()) 10742 return QualType(); 10743 10744 // Diagnose "string literal" '+' int and string '+' "char literal". 10745 if (Opc == BO_Add) { 10746 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10747 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10748 } 10749 10750 // handle the common case first (both operands are arithmetic). 10751 if (!compType.isNull() && compType->isArithmeticType()) { 10752 if (CompLHSTy) *CompLHSTy = compType; 10753 return compType; 10754 } 10755 10756 // Type-checking. Ultimately the pointer's going to be in PExp; 10757 // note that we bias towards the LHS being the pointer. 10758 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10759 10760 bool isObjCPointer; 10761 if (PExp->getType()->isPointerType()) { 10762 isObjCPointer = false; 10763 } else if (PExp->getType()->isObjCObjectPointerType()) { 10764 isObjCPointer = true; 10765 } else { 10766 std::swap(PExp, IExp); 10767 if (PExp->getType()->isPointerType()) { 10768 isObjCPointer = false; 10769 } else if (PExp->getType()->isObjCObjectPointerType()) { 10770 isObjCPointer = true; 10771 } else { 10772 return InvalidOperands(Loc, LHS, RHS); 10773 } 10774 } 10775 assert(PExp->getType()->isAnyPointerType()); 10776 10777 if (!IExp->getType()->isIntegerType()) 10778 return InvalidOperands(Loc, LHS, RHS); 10779 10780 // Adding to a null pointer results in undefined behavior. 10781 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10782 Context, Expr::NPC_ValueDependentIsNotNull)) { 10783 // In C++ adding zero to a null pointer is defined. 10784 Expr::EvalResult KnownVal; 10785 if (!getLangOpts().CPlusPlus || 10786 (!IExp->isValueDependent() && 10787 (!IExp->EvaluateAsInt(KnownVal, Context) || 10788 KnownVal.Val.getInt() != 0))) { 10789 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10790 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10791 Context, BO_Add, PExp, IExp); 10792 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10793 } 10794 } 10795 10796 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10797 return QualType(); 10798 10799 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10800 return QualType(); 10801 10802 // Check array bounds for pointer arithemtic 10803 CheckArrayAccess(PExp, IExp); 10804 10805 if (CompLHSTy) { 10806 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10807 if (LHSTy.isNull()) { 10808 LHSTy = LHS.get()->getType(); 10809 if (LHSTy->isPromotableIntegerType()) 10810 LHSTy = Context.getPromotedIntegerType(LHSTy); 10811 } 10812 *CompLHSTy = LHSTy; 10813 } 10814 10815 return PExp->getType(); 10816 } 10817 10818 // C99 6.5.6 10819 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10820 SourceLocation Loc, 10821 QualType* CompLHSTy) { 10822 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10823 10824 if (LHS.get()->getType()->isVectorType() || 10825 RHS.get()->getType()->isVectorType()) { 10826 QualType compType = CheckVectorOperands( 10827 LHS, RHS, Loc, CompLHSTy, 10828 /*AllowBothBool*/getLangOpts().AltiVec, 10829 /*AllowBoolConversions*/getLangOpts().ZVector); 10830 if (CompLHSTy) *CompLHSTy = compType; 10831 return compType; 10832 } 10833 10834 if (LHS.get()->getType()->isConstantMatrixType() || 10835 RHS.get()->getType()->isConstantMatrixType()) { 10836 QualType compType = 10837 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10838 if (CompLHSTy) 10839 *CompLHSTy = compType; 10840 return compType; 10841 } 10842 10843 QualType compType = UsualArithmeticConversions( 10844 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10845 if (LHS.isInvalid() || RHS.isInvalid()) 10846 return QualType(); 10847 10848 // Enforce type constraints: C99 6.5.6p3. 10849 10850 // Handle the common case first (both operands are arithmetic). 10851 if (!compType.isNull() && compType->isArithmeticType()) { 10852 if (CompLHSTy) *CompLHSTy = compType; 10853 return compType; 10854 } 10855 10856 // Either ptr - int or ptr - ptr. 10857 if (LHS.get()->getType()->isAnyPointerType()) { 10858 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10859 10860 // Diagnose bad cases where we step over interface counts. 10861 if (LHS.get()->getType()->isObjCObjectPointerType() && 10862 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10863 return QualType(); 10864 10865 // The result type of a pointer-int computation is the pointer type. 10866 if (RHS.get()->getType()->isIntegerType()) { 10867 // Subtracting from a null pointer should produce a warning. 10868 // The last argument to the diagnose call says this doesn't match the 10869 // GNU int-to-pointer idiom. 10870 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10871 Expr::NPC_ValueDependentIsNotNull)) { 10872 // In C++ adding zero to a null pointer is defined. 10873 Expr::EvalResult KnownVal; 10874 if (!getLangOpts().CPlusPlus || 10875 (!RHS.get()->isValueDependent() && 10876 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10877 KnownVal.Val.getInt() != 0))) { 10878 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10879 } 10880 } 10881 10882 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10883 return QualType(); 10884 10885 // Check array bounds for pointer arithemtic 10886 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10887 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10888 10889 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10890 return LHS.get()->getType(); 10891 } 10892 10893 // Handle pointer-pointer subtractions. 10894 if (const PointerType *RHSPTy 10895 = RHS.get()->getType()->getAs<PointerType>()) { 10896 QualType rpointee = RHSPTy->getPointeeType(); 10897 10898 if (getLangOpts().CPlusPlus) { 10899 // Pointee types must be the same: C++ [expr.add] 10900 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10901 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10902 } 10903 } else { 10904 // Pointee types must be compatible C99 6.5.6p3 10905 if (!Context.typesAreCompatible( 10906 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10907 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10908 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10909 return QualType(); 10910 } 10911 } 10912 10913 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10914 LHS.get(), RHS.get())) 10915 return QualType(); 10916 10917 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10918 Context, Expr::NPC_ValueDependentIsNotNull); 10919 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10920 Context, Expr::NPC_ValueDependentIsNotNull); 10921 10922 // Subtracting nullptr or from nullptr is suspect 10923 if (LHSIsNullPtr) 10924 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); 10925 if (RHSIsNullPtr) 10926 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); 10927 10928 // The pointee type may have zero size. As an extension, a structure or 10929 // union may have zero size or an array may have zero length. In this 10930 // case subtraction does not make sense. 10931 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10932 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10933 if (ElementSize.isZero()) { 10934 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10935 << rpointee.getUnqualifiedType() 10936 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10937 } 10938 } 10939 10940 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10941 return Context.getPointerDiffType(); 10942 } 10943 } 10944 10945 return InvalidOperands(Loc, LHS, RHS); 10946 } 10947 10948 static bool isScopedEnumerationType(QualType T) { 10949 if (const EnumType *ET = T->getAs<EnumType>()) 10950 return ET->getDecl()->isScoped(); 10951 return false; 10952 } 10953 10954 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10955 SourceLocation Loc, BinaryOperatorKind Opc, 10956 QualType LHSType) { 10957 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10958 // so skip remaining warnings as we don't want to modify values within Sema. 10959 if (S.getLangOpts().OpenCL) 10960 return; 10961 10962 // Check right/shifter operand 10963 Expr::EvalResult RHSResult; 10964 if (RHS.get()->isValueDependent() || 10965 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10966 return; 10967 llvm::APSInt Right = RHSResult.Val.getInt(); 10968 10969 if (Right.isNegative()) { 10970 S.DiagRuntimeBehavior(Loc, RHS.get(), 10971 S.PDiag(diag::warn_shift_negative) 10972 << RHS.get()->getSourceRange()); 10973 return; 10974 } 10975 10976 QualType LHSExprType = LHS.get()->getType(); 10977 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10978 if (LHSExprType->isExtIntType()) 10979 LeftSize = S.Context.getIntWidth(LHSExprType); 10980 else if (LHSExprType->isFixedPointType()) { 10981 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10982 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10983 } 10984 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10985 if (Right.uge(LeftBits)) { 10986 S.DiagRuntimeBehavior(Loc, RHS.get(), 10987 S.PDiag(diag::warn_shift_gt_typewidth) 10988 << RHS.get()->getSourceRange()); 10989 return; 10990 } 10991 10992 // FIXME: We probably need to handle fixed point types specially here. 10993 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10994 return; 10995 10996 // When left shifting an ICE which is signed, we can check for overflow which 10997 // according to C++ standards prior to C++2a has undefined behavior 10998 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10999 // more than the maximum value representable in the result type, so never 11000 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 11001 // expression is still probably a bug.) 11002 Expr::EvalResult LHSResult; 11003 if (LHS.get()->isValueDependent() || 11004 LHSType->hasUnsignedIntegerRepresentation() || 11005 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 11006 return; 11007 llvm::APSInt Left = LHSResult.Val.getInt(); 11008 11009 // If LHS does not have a signed type and non-negative value 11010 // then, the behavior is undefined before C++2a. Warn about it. 11011 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 11012 !S.getLangOpts().CPlusPlus20) { 11013 S.DiagRuntimeBehavior(Loc, LHS.get(), 11014 S.PDiag(diag::warn_shift_lhs_negative) 11015 << LHS.get()->getSourceRange()); 11016 return; 11017 } 11018 11019 llvm::APInt ResultBits = 11020 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 11021 if (LeftBits.uge(ResultBits)) 11022 return; 11023 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 11024 Result = Result.shl(Right); 11025 11026 // Print the bit representation of the signed integer as an unsigned 11027 // hexadecimal number. 11028 SmallString<40> HexResult; 11029 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 11030 11031 // If we are only missing a sign bit, this is less likely to result in actual 11032 // bugs -- if the result is cast back to an unsigned type, it will have the 11033 // expected value. Thus we place this behind a different warning that can be 11034 // turned off separately if needed. 11035 if (LeftBits == ResultBits - 1) { 11036 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 11037 << HexResult << LHSType 11038 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11039 return; 11040 } 11041 11042 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 11043 << HexResult.str() << Result.getMinSignedBits() << LHSType 11044 << Left.getBitWidth() << LHS.get()->getSourceRange() 11045 << RHS.get()->getSourceRange(); 11046 } 11047 11048 /// Return the resulting type when a vector is shifted 11049 /// by a scalar or vector shift amount. 11050 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 11051 SourceLocation Loc, bool IsCompAssign) { 11052 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 11053 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 11054 !LHS.get()->getType()->isVectorType()) { 11055 S.Diag(Loc, diag::err_shift_rhs_only_vector) 11056 << RHS.get()->getType() << LHS.get()->getType() 11057 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11058 return QualType(); 11059 } 11060 11061 if (!IsCompAssign) { 11062 LHS = S.UsualUnaryConversions(LHS.get()); 11063 if (LHS.isInvalid()) return QualType(); 11064 } 11065 11066 RHS = S.UsualUnaryConversions(RHS.get()); 11067 if (RHS.isInvalid()) return QualType(); 11068 11069 QualType LHSType = LHS.get()->getType(); 11070 // Note that LHS might be a scalar because the routine calls not only in 11071 // OpenCL case. 11072 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 11073 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 11074 11075 // Note that RHS might not be a vector. 11076 QualType RHSType = RHS.get()->getType(); 11077 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 11078 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 11079 11080 // The operands need to be integers. 11081 if (!LHSEleType->isIntegerType()) { 11082 S.Diag(Loc, diag::err_typecheck_expect_int) 11083 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11084 return QualType(); 11085 } 11086 11087 if (!RHSEleType->isIntegerType()) { 11088 S.Diag(Loc, diag::err_typecheck_expect_int) 11089 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11090 return QualType(); 11091 } 11092 11093 if (!LHSVecTy) { 11094 assert(RHSVecTy); 11095 if (IsCompAssign) 11096 return RHSType; 11097 if (LHSEleType != RHSEleType) { 11098 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 11099 LHSEleType = RHSEleType; 11100 } 11101 QualType VecTy = 11102 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11103 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11104 LHSType = VecTy; 11105 } else if (RHSVecTy) { 11106 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11107 // are applied component-wise. So if RHS is a vector, then ensure 11108 // that the number of elements is the same as LHS... 11109 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11110 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11111 << LHS.get()->getType() << RHS.get()->getType() 11112 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11113 return QualType(); 11114 } 11115 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11116 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11117 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11118 if (LHSBT != RHSBT && 11119 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11120 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11121 << LHS.get()->getType() << RHS.get()->getType() 11122 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11123 } 11124 } 11125 } else { 11126 // ...else expand RHS to match the number of elements in LHS. 11127 QualType VecTy = 11128 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11129 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11130 } 11131 11132 return LHSType; 11133 } 11134 11135 // C99 6.5.7 11136 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11137 SourceLocation Loc, BinaryOperatorKind Opc, 11138 bool IsCompAssign) { 11139 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11140 11141 // Vector shifts promote their scalar inputs to vector type. 11142 if (LHS.get()->getType()->isVectorType() || 11143 RHS.get()->getType()->isVectorType()) { 11144 if (LangOpts.ZVector) { 11145 // The shift operators for the z vector extensions work basically 11146 // like general shifts, except that neither the LHS nor the RHS is 11147 // allowed to be a "vector bool". 11148 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11149 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11150 return InvalidOperands(Loc, LHS, RHS); 11151 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11152 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11153 return InvalidOperands(Loc, LHS, RHS); 11154 } 11155 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11156 } 11157 11158 // Shifts don't perform usual arithmetic conversions, they just do integer 11159 // promotions on each operand. C99 6.5.7p3 11160 11161 // For the LHS, do usual unary conversions, but then reset them away 11162 // if this is a compound assignment. 11163 ExprResult OldLHS = LHS; 11164 LHS = UsualUnaryConversions(LHS.get()); 11165 if (LHS.isInvalid()) 11166 return QualType(); 11167 QualType LHSType = LHS.get()->getType(); 11168 if (IsCompAssign) LHS = OldLHS; 11169 11170 // The RHS is simpler. 11171 RHS = UsualUnaryConversions(RHS.get()); 11172 if (RHS.isInvalid()) 11173 return QualType(); 11174 QualType RHSType = RHS.get()->getType(); 11175 11176 // C99 6.5.7p2: Each of the operands shall have integer type. 11177 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11178 if ((!LHSType->isFixedPointOrIntegerType() && 11179 !LHSType->hasIntegerRepresentation()) || 11180 !RHSType->hasIntegerRepresentation()) 11181 return InvalidOperands(Loc, LHS, RHS); 11182 11183 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11184 // hasIntegerRepresentation() above instead of this. 11185 if (isScopedEnumerationType(LHSType) || 11186 isScopedEnumerationType(RHSType)) { 11187 return InvalidOperands(Loc, LHS, RHS); 11188 } 11189 // Sanity-check shift operands 11190 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11191 11192 // "The type of the result is that of the promoted left operand." 11193 return LHSType; 11194 } 11195 11196 /// Diagnose bad pointer comparisons. 11197 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11198 ExprResult &LHS, ExprResult &RHS, 11199 bool IsError) { 11200 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11201 : diag::ext_typecheck_comparison_of_distinct_pointers) 11202 << LHS.get()->getType() << RHS.get()->getType() 11203 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11204 } 11205 11206 /// Returns false if the pointers are converted to a composite type, 11207 /// true otherwise. 11208 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11209 ExprResult &LHS, ExprResult &RHS) { 11210 // C++ [expr.rel]p2: 11211 // [...] Pointer conversions (4.10) and qualification 11212 // conversions (4.4) are performed on pointer operands (or on 11213 // a pointer operand and a null pointer constant) to bring 11214 // them to their composite pointer type. [...] 11215 // 11216 // C++ [expr.eq]p1 uses the same notion for (in)equality 11217 // comparisons of pointers. 11218 11219 QualType LHSType = LHS.get()->getType(); 11220 QualType RHSType = RHS.get()->getType(); 11221 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11222 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11223 11224 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11225 if (T.isNull()) { 11226 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11227 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11228 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11229 else 11230 S.InvalidOperands(Loc, LHS, RHS); 11231 return true; 11232 } 11233 11234 return false; 11235 } 11236 11237 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11238 ExprResult &LHS, 11239 ExprResult &RHS, 11240 bool IsError) { 11241 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11242 : diag::ext_typecheck_comparison_of_fptr_to_void) 11243 << LHS.get()->getType() << RHS.get()->getType() 11244 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11245 } 11246 11247 static bool isObjCObjectLiteral(ExprResult &E) { 11248 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11249 case Stmt::ObjCArrayLiteralClass: 11250 case Stmt::ObjCDictionaryLiteralClass: 11251 case Stmt::ObjCStringLiteralClass: 11252 case Stmt::ObjCBoxedExprClass: 11253 return true; 11254 default: 11255 // Note that ObjCBoolLiteral is NOT an object literal! 11256 return false; 11257 } 11258 } 11259 11260 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11261 const ObjCObjectPointerType *Type = 11262 LHS->getType()->getAs<ObjCObjectPointerType>(); 11263 11264 // If this is not actually an Objective-C object, bail out. 11265 if (!Type) 11266 return false; 11267 11268 // Get the LHS object's interface type. 11269 QualType InterfaceType = Type->getPointeeType(); 11270 11271 // If the RHS isn't an Objective-C object, bail out. 11272 if (!RHS->getType()->isObjCObjectPointerType()) 11273 return false; 11274 11275 // Try to find the -isEqual: method. 11276 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11277 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11278 InterfaceType, 11279 /*IsInstance=*/true); 11280 if (!Method) { 11281 if (Type->isObjCIdType()) { 11282 // For 'id', just check the global pool. 11283 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11284 /*receiverId=*/true); 11285 } else { 11286 // Check protocols. 11287 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11288 /*IsInstance=*/true); 11289 } 11290 } 11291 11292 if (!Method) 11293 return false; 11294 11295 QualType T = Method->parameters()[0]->getType(); 11296 if (!T->isObjCObjectPointerType()) 11297 return false; 11298 11299 QualType R = Method->getReturnType(); 11300 if (!R->isScalarType()) 11301 return false; 11302 11303 return true; 11304 } 11305 11306 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11307 FromE = FromE->IgnoreParenImpCasts(); 11308 switch (FromE->getStmtClass()) { 11309 default: 11310 break; 11311 case Stmt::ObjCStringLiteralClass: 11312 // "string literal" 11313 return LK_String; 11314 case Stmt::ObjCArrayLiteralClass: 11315 // "array literal" 11316 return LK_Array; 11317 case Stmt::ObjCDictionaryLiteralClass: 11318 // "dictionary literal" 11319 return LK_Dictionary; 11320 case Stmt::BlockExprClass: 11321 return LK_Block; 11322 case Stmt::ObjCBoxedExprClass: { 11323 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11324 switch (Inner->getStmtClass()) { 11325 case Stmt::IntegerLiteralClass: 11326 case Stmt::FloatingLiteralClass: 11327 case Stmt::CharacterLiteralClass: 11328 case Stmt::ObjCBoolLiteralExprClass: 11329 case Stmt::CXXBoolLiteralExprClass: 11330 // "numeric literal" 11331 return LK_Numeric; 11332 case Stmt::ImplicitCastExprClass: { 11333 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11334 // Boolean literals can be represented by implicit casts. 11335 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11336 return LK_Numeric; 11337 break; 11338 } 11339 default: 11340 break; 11341 } 11342 return LK_Boxed; 11343 } 11344 } 11345 return LK_None; 11346 } 11347 11348 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11349 ExprResult &LHS, ExprResult &RHS, 11350 BinaryOperator::Opcode Opc){ 11351 Expr *Literal; 11352 Expr *Other; 11353 if (isObjCObjectLiteral(LHS)) { 11354 Literal = LHS.get(); 11355 Other = RHS.get(); 11356 } else { 11357 Literal = RHS.get(); 11358 Other = LHS.get(); 11359 } 11360 11361 // Don't warn on comparisons against nil. 11362 Other = Other->IgnoreParenCasts(); 11363 if (Other->isNullPointerConstant(S.getASTContext(), 11364 Expr::NPC_ValueDependentIsNotNull)) 11365 return; 11366 11367 // This should be kept in sync with warn_objc_literal_comparison. 11368 // LK_String should always be after the other literals, since it has its own 11369 // warning flag. 11370 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11371 assert(LiteralKind != Sema::LK_Block); 11372 if (LiteralKind == Sema::LK_None) { 11373 llvm_unreachable("Unknown Objective-C object literal kind"); 11374 } 11375 11376 if (LiteralKind == Sema::LK_String) 11377 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11378 << Literal->getSourceRange(); 11379 else 11380 S.Diag(Loc, diag::warn_objc_literal_comparison) 11381 << LiteralKind << Literal->getSourceRange(); 11382 11383 if (BinaryOperator::isEqualityOp(Opc) && 11384 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11385 SourceLocation Start = LHS.get()->getBeginLoc(); 11386 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11387 CharSourceRange OpRange = 11388 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11389 11390 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11391 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11392 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11393 << FixItHint::CreateInsertion(End, "]"); 11394 } 11395 } 11396 11397 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11398 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11399 ExprResult &RHS, SourceLocation Loc, 11400 BinaryOperatorKind Opc) { 11401 // Check that left hand side is !something. 11402 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11403 if (!UO || UO->getOpcode() != UO_LNot) return; 11404 11405 // Only check if the right hand side is non-bool arithmetic type. 11406 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11407 11408 // Make sure that the something in !something is not bool. 11409 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11410 if (SubExpr->isKnownToHaveBooleanValue()) return; 11411 11412 // Emit warning. 11413 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11414 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11415 << Loc << IsBitwiseOp; 11416 11417 // First note suggest !(x < y) 11418 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11419 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11420 FirstClose = S.getLocForEndOfToken(FirstClose); 11421 if (FirstClose.isInvalid()) 11422 FirstOpen = SourceLocation(); 11423 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11424 << IsBitwiseOp 11425 << FixItHint::CreateInsertion(FirstOpen, "(") 11426 << FixItHint::CreateInsertion(FirstClose, ")"); 11427 11428 // Second note suggests (!x) < y 11429 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11430 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11431 SecondClose = S.getLocForEndOfToken(SecondClose); 11432 if (SecondClose.isInvalid()) 11433 SecondOpen = SourceLocation(); 11434 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11435 << FixItHint::CreateInsertion(SecondOpen, "(") 11436 << FixItHint::CreateInsertion(SecondClose, ")"); 11437 } 11438 11439 // Returns true if E refers to a non-weak array. 11440 static bool checkForArray(const Expr *E) { 11441 const ValueDecl *D = nullptr; 11442 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11443 D = DR->getDecl(); 11444 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11445 if (Mem->isImplicitAccess()) 11446 D = Mem->getMemberDecl(); 11447 } 11448 if (!D) 11449 return false; 11450 return D->getType()->isArrayType() && !D->isWeak(); 11451 } 11452 11453 /// Diagnose some forms of syntactically-obvious tautological comparison. 11454 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11455 Expr *LHS, Expr *RHS, 11456 BinaryOperatorKind Opc) { 11457 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11458 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11459 11460 QualType LHSType = LHS->getType(); 11461 QualType RHSType = RHS->getType(); 11462 if (LHSType->hasFloatingRepresentation() || 11463 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11464 S.inTemplateInstantiation()) 11465 return; 11466 11467 // Comparisons between two array types are ill-formed for operator<=>, so 11468 // we shouldn't emit any additional warnings about it. 11469 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11470 return; 11471 11472 // For non-floating point types, check for self-comparisons of the form 11473 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11474 // often indicate logic errors in the program. 11475 // 11476 // NOTE: Don't warn about comparison expressions resulting from macro 11477 // expansion. Also don't warn about comparisons which are only self 11478 // comparisons within a template instantiation. The warnings should catch 11479 // obvious cases in the definition of the template anyways. The idea is to 11480 // warn when the typed comparison operator will always evaluate to the same 11481 // result. 11482 11483 // Used for indexing into %select in warn_comparison_always 11484 enum { 11485 AlwaysConstant, 11486 AlwaysTrue, 11487 AlwaysFalse, 11488 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11489 }; 11490 11491 // C++2a [depr.array.comp]: 11492 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11493 // operands of array type are deprecated. 11494 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11495 RHSStripped->getType()->isArrayType()) { 11496 S.Diag(Loc, diag::warn_depr_array_comparison) 11497 << LHS->getSourceRange() << RHS->getSourceRange() 11498 << LHSStripped->getType() << RHSStripped->getType(); 11499 // Carry on to produce the tautological comparison warning, if this 11500 // expression is potentially-evaluated, we can resolve the array to a 11501 // non-weak declaration, and so on. 11502 } 11503 11504 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11505 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11506 unsigned Result; 11507 switch (Opc) { 11508 case BO_EQ: 11509 case BO_LE: 11510 case BO_GE: 11511 Result = AlwaysTrue; 11512 break; 11513 case BO_NE: 11514 case BO_LT: 11515 case BO_GT: 11516 Result = AlwaysFalse; 11517 break; 11518 case BO_Cmp: 11519 Result = AlwaysEqual; 11520 break; 11521 default: 11522 Result = AlwaysConstant; 11523 break; 11524 } 11525 S.DiagRuntimeBehavior(Loc, nullptr, 11526 S.PDiag(diag::warn_comparison_always) 11527 << 0 /*self-comparison*/ 11528 << Result); 11529 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11530 // What is it always going to evaluate to? 11531 unsigned Result; 11532 switch (Opc) { 11533 case BO_EQ: // e.g. array1 == array2 11534 Result = AlwaysFalse; 11535 break; 11536 case BO_NE: // e.g. array1 != array2 11537 Result = AlwaysTrue; 11538 break; 11539 default: // e.g. array1 <= array2 11540 // The best we can say is 'a constant' 11541 Result = AlwaysConstant; 11542 break; 11543 } 11544 S.DiagRuntimeBehavior(Loc, nullptr, 11545 S.PDiag(diag::warn_comparison_always) 11546 << 1 /*array comparison*/ 11547 << Result); 11548 } 11549 } 11550 11551 if (isa<CastExpr>(LHSStripped)) 11552 LHSStripped = LHSStripped->IgnoreParenCasts(); 11553 if (isa<CastExpr>(RHSStripped)) 11554 RHSStripped = RHSStripped->IgnoreParenCasts(); 11555 11556 // Warn about comparisons against a string constant (unless the other 11557 // operand is null); the user probably wants string comparison function. 11558 Expr *LiteralString = nullptr; 11559 Expr *LiteralStringStripped = nullptr; 11560 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11561 !RHSStripped->isNullPointerConstant(S.Context, 11562 Expr::NPC_ValueDependentIsNull)) { 11563 LiteralString = LHS; 11564 LiteralStringStripped = LHSStripped; 11565 } else if ((isa<StringLiteral>(RHSStripped) || 11566 isa<ObjCEncodeExpr>(RHSStripped)) && 11567 !LHSStripped->isNullPointerConstant(S.Context, 11568 Expr::NPC_ValueDependentIsNull)) { 11569 LiteralString = RHS; 11570 LiteralStringStripped = RHSStripped; 11571 } 11572 11573 if (LiteralString) { 11574 S.DiagRuntimeBehavior(Loc, nullptr, 11575 S.PDiag(diag::warn_stringcompare) 11576 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11577 << LiteralString->getSourceRange()); 11578 } 11579 } 11580 11581 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11582 switch (CK) { 11583 default: { 11584 #ifndef NDEBUG 11585 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11586 << "\n"; 11587 #endif 11588 llvm_unreachable("unhandled cast kind"); 11589 } 11590 case CK_UserDefinedConversion: 11591 return ICK_Identity; 11592 case CK_LValueToRValue: 11593 return ICK_Lvalue_To_Rvalue; 11594 case CK_ArrayToPointerDecay: 11595 return ICK_Array_To_Pointer; 11596 case CK_FunctionToPointerDecay: 11597 return ICK_Function_To_Pointer; 11598 case CK_IntegralCast: 11599 return ICK_Integral_Conversion; 11600 case CK_FloatingCast: 11601 return ICK_Floating_Conversion; 11602 case CK_IntegralToFloating: 11603 case CK_FloatingToIntegral: 11604 return ICK_Floating_Integral; 11605 case CK_IntegralComplexCast: 11606 case CK_FloatingComplexCast: 11607 case CK_FloatingComplexToIntegralComplex: 11608 case CK_IntegralComplexToFloatingComplex: 11609 return ICK_Complex_Conversion; 11610 case CK_FloatingComplexToReal: 11611 case CK_FloatingRealToComplex: 11612 case CK_IntegralComplexToReal: 11613 case CK_IntegralRealToComplex: 11614 return ICK_Complex_Real; 11615 } 11616 } 11617 11618 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11619 QualType FromType, 11620 SourceLocation Loc) { 11621 // Check for a narrowing implicit conversion. 11622 StandardConversionSequence SCS; 11623 SCS.setAsIdentityConversion(); 11624 SCS.setToType(0, FromType); 11625 SCS.setToType(1, ToType); 11626 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11627 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11628 11629 APValue PreNarrowingValue; 11630 QualType PreNarrowingType; 11631 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11632 PreNarrowingType, 11633 /*IgnoreFloatToIntegralConversion*/ true)) { 11634 case NK_Dependent_Narrowing: 11635 // Implicit conversion to a narrower type, but the expression is 11636 // value-dependent so we can't tell whether it's actually narrowing. 11637 case NK_Not_Narrowing: 11638 return false; 11639 11640 case NK_Constant_Narrowing: 11641 // Implicit conversion to a narrower type, and the value is not a constant 11642 // expression. 11643 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11644 << /*Constant*/ 1 11645 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11646 return true; 11647 11648 case NK_Variable_Narrowing: 11649 // Implicit conversion to a narrower type, and the value is not a constant 11650 // expression. 11651 case NK_Type_Narrowing: 11652 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11653 << /*Constant*/ 0 << FromType << ToType; 11654 // TODO: It's not a constant expression, but what if the user intended it 11655 // to be? Can we produce notes to help them figure out why it isn't? 11656 return true; 11657 } 11658 llvm_unreachable("unhandled case in switch"); 11659 } 11660 11661 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11662 ExprResult &LHS, 11663 ExprResult &RHS, 11664 SourceLocation Loc) { 11665 QualType LHSType = LHS.get()->getType(); 11666 QualType RHSType = RHS.get()->getType(); 11667 // Dig out the original argument type and expression before implicit casts 11668 // were applied. These are the types/expressions we need to check the 11669 // [expr.spaceship] requirements against. 11670 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11671 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11672 QualType LHSStrippedType = LHSStripped.get()->getType(); 11673 QualType RHSStrippedType = RHSStripped.get()->getType(); 11674 11675 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11676 // other is not, the program is ill-formed. 11677 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11678 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11679 return QualType(); 11680 } 11681 11682 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11683 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11684 RHSStrippedType->isEnumeralType(); 11685 if (NumEnumArgs == 1) { 11686 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11687 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11688 if (OtherTy->hasFloatingRepresentation()) { 11689 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11690 return QualType(); 11691 } 11692 } 11693 if (NumEnumArgs == 2) { 11694 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11695 // type E, the operator yields the result of converting the operands 11696 // to the underlying type of E and applying <=> to the converted operands. 11697 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11698 S.InvalidOperands(Loc, LHS, RHS); 11699 return QualType(); 11700 } 11701 QualType IntType = 11702 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11703 assert(IntType->isArithmeticType()); 11704 11705 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11706 // promote the boolean type, and all other promotable integer types, to 11707 // avoid this. 11708 if (IntType->isPromotableIntegerType()) 11709 IntType = S.Context.getPromotedIntegerType(IntType); 11710 11711 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11712 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11713 LHSType = RHSType = IntType; 11714 } 11715 11716 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11717 // usual arithmetic conversions are applied to the operands. 11718 QualType Type = 11719 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11720 if (LHS.isInvalid() || RHS.isInvalid()) 11721 return QualType(); 11722 if (Type.isNull()) 11723 return S.InvalidOperands(Loc, LHS, RHS); 11724 11725 Optional<ComparisonCategoryType> CCT = 11726 getComparisonCategoryForBuiltinCmp(Type); 11727 if (!CCT) 11728 return S.InvalidOperands(Loc, LHS, RHS); 11729 11730 bool HasNarrowing = checkThreeWayNarrowingConversion( 11731 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11732 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11733 RHS.get()->getBeginLoc()); 11734 if (HasNarrowing) 11735 return QualType(); 11736 11737 assert(!Type.isNull() && "composite type for <=> has not been set"); 11738 11739 return S.CheckComparisonCategoryType( 11740 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11741 } 11742 11743 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11744 ExprResult &RHS, 11745 SourceLocation Loc, 11746 BinaryOperatorKind Opc) { 11747 if (Opc == BO_Cmp) 11748 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11749 11750 // C99 6.5.8p3 / C99 6.5.9p4 11751 QualType Type = 11752 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11753 if (LHS.isInvalid() || RHS.isInvalid()) 11754 return QualType(); 11755 if (Type.isNull()) 11756 return S.InvalidOperands(Loc, LHS, RHS); 11757 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11758 11759 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11760 return S.InvalidOperands(Loc, LHS, RHS); 11761 11762 // Check for comparisons of floating point operands using != and ==. 11763 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11764 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11765 11766 // The result of comparisons is 'bool' in C++, 'int' in C. 11767 return S.Context.getLogicalOperationType(); 11768 } 11769 11770 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11771 if (!NullE.get()->getType()->isAnyPointerType()) 11772 return; 11773 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11774 if (!E.get()->getType()->isAnyPointerType() && 11775 E.get()->isNullPointerConstant(Context, 11776 Expr::NPC_ValueDependentIsNotNull) == 11777 Expr::NPCK_ZeroExpression) { 11778 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11779 if (CL->getValue() == 0) 11780 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11781 << NullValue 11782 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11783 NullValue ? "NULL" : "(void *)0"); 11784 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11785 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11786 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11787 if (T == Context.CharTy) 11788 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11789 << NullValue 11790 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11791 NullValue ? "NULL" : "(void *)0"); 11792 } 11793 } 11794 } 11795 11796 // C99 6.5.8, C++ [expr.rel] 11797 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11798 SourceLocation Loc, 11799 BinaryOperatorKind Opc) { 11800 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11801 bool IsThreeWay = Opc == BO_Cmp; 11802 bool IsOrdered = IsRelational || IsThreeWay; 11803 auto IsAnyPointerType = [](ExprResult E) { 11804 QualType Ty = E.get()->getType(); 11805 return Ty->isPointerType() || Ty->isMemberPointerType(); 11806 }; 11807 11808 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11809 // type, array-to-pointer, ..., conversions are performed on both operands to 11810 // bring them to their composite type. 11811 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11812 // any type-related checks. 11813 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11814 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11815 if (LHS.isInvalid()) 11816 return QualType(); 11817 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11818 if (RHS.isInvalid()) 11819 return QualType(); 11820 } else { 11821 LHS = DefaultLvalueConversion(LHS.get()); 11822 if (LHS.isInvalid()) 11823 return QualType(); 11824 RHS = DefaultLvalueConversion(RHS.get()); 11825 if (RHS.isInvalid()) 11826 return QualType(); 11827 } 11828 11829 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11830 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11831 CheckPtrComparisonWithNullChar(LHS, RHS); 11832 CheckPtrComparisonWithNullChar(RHS, LHS); 11833 } 11834 11835 // Handle vector comparisons separately. 11836 if (LHS.get()->getType()->isVectorType() || 11837 RHS.get()->getType()->isVectorType()) 11838 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11839 11840 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11841 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11842 11843 QualType LHSType = LHS.get()->getType(); 11844 QualType RHSType = RHS.get()->getType(); 11845 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11846 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11847 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11848 11849 const Expr::NullPointerConstantKind LHSNullKind = 11850 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11851 const Expr::NullPointerConstantKind RHSNullKind = 11852 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11853 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11854 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11855 11856 auto computeResultTy = [&]() { 11857 if (Opc != BO_Cmp) 11858 return Context.getLogicalOperationType(); 11859 assert(getLangOpts().CPlusPlus); 11860 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11861 11862 QualType CompositeTy = LHS.get()->getType(); 11863 assert(!CompositeTy->isReferenceType()); 11864 11865 Optional<ComparisonCategoryType> CCT = 11866 getComparisonCategoryForBuiltinCmp(CompositeTy); 11867 if (!CCT) 11868 return InvalidOperands(Loc, LHS, RHS); 11869 11870 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11871 // P0946R0: Comparisons between a null pointer constant and an object 11872 // pointer result in std::strong_equality, which is ill-formed under 11873 // P1959R0. 11874 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11875 << (LHSIsNull ? LHS.get()->getSourceRange() 11876 : RHS.get()->getSourceRange()); 11877 return QualType(); 11878 } 11879 11880 return CheckComparisonCategoryType( 11881 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11882 }; 11883 11884 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11885 bool IsEquality = Opc == BO_EQ; 11886 if (RHSIsNull) 11887 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11888 RHS.get()->getSourceRange()); 11889 else 11890 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11891 LHS.get()->getSourceRange()); 11892 } 11893 11894 if (IsOrdered && LHSType->isFunctionPointerType() && 11895 RHSType->isFunctionPointerType()) { 11896 // Valid unless a relational comparison of function pointers 11897 bool IsError = Opc == BO_Cmp; 11898 auto DiagID = 11899 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 11900 : getLangOpts().CPlusPlus 11901 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 11902 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 11903 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 11904 << RHS.get()->getSourceRange(); 11905 if (IsError) 11906 return QualType(); 11907 } 11908 11909 if ((LHSType->isIntegerType() && !LHSIsNull) || 11910 (RHSType->isIntegerType() && !RHSIsNull)) { 11911 // Skip normal pointer conversion checks in this case; we have better 11912 // diagnostics for this below. 11913 } else if (getLangOpts().CPlusPlus) { 11914 // Equality comparison of a function pointer to a void pointer is invalid, 11915 // but we allow it as an extension. 11916 // FIXME: If we really want to allow this, should it be part of composite 11917 // pointer type computation so it works in conditionals too? 11918 if (!IsOrdered && 11919 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11920 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11921 // This is a gcc extension compatibility comparison. 11922 // In a SFINAE context, we treat this as a hard error to maintain 11923 // conformance with the C++ standard. 11924 diagnoseFunctionPointerToVoidComparison( 11925 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11926 11927 if (isSFINAEContext()) 11928 return QualType(); 11929 11930 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11931 return computeResultTy(); 11932 } 11933 11934 // C++ [expr.eq]p2: 11935 // If at least one operand is a pointer [...] bring them to their 11936 // composite pointer type. 11937 // C++ [expr.spaceship]p6 11938 // If at least one of the operands is of pointer type, [...] bring them 11939 // to their composite pointer type. 11940 // C++ [expr.rel]p2: 11941 // If both operands are pointers, [...] bring them to their composite 11942 // pointer type. 11943 // For <=>, the only valid non-pointer types are arrays and functions, and 11944 // we already decayed those, so this is really the same as the relational 11945 // comparison rule. 11946 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11947 (IsOrdered ? 2 : 1) && 11948 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11949 RHSType->isObjCObjectPointerType()))) { 11950 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11951 return QualType(); 11952 return computeResultTy(); 11953 } 11954 } else if (LHSType->isPointerType() && 11955 RHSType->isPointerType()) { // C99 6.5.8p2 11956 // All of the following pointer-related warnings are GCC extensions, except 11957 // when handling null pointer constants. 11958 QualType LCanPointeeTy = 11959 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11960 QualType RCanPointeeTy = 11961 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11962 11963 // C99 6.5.9p2 and C99 6.5.8p2 11964 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11965 RCanPointeeTy.getUnqualifiedType())) { 11966 if (IsRelational) { 11967 // Pointers both need to point to complete or incomplete types 11968 if ((LCanPointeeTy->isIncompleteType() != 11969 RCanPointeeTy->isIncompleteType()) && 11970 !getLangOpts().C11) { 11971 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11972 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11973 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11974 << RCanPointeeTy->isIncompleteType(); 11975 } 11976 } 11977 } else if (!IsRelational && 11978 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11979 // Valid unless comparison between non-null pointer and function pointer 11980 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11981 && !LHSIsNull && !RHSIsNull) 11982 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11983 /*isError*/false); 11984 } else { 11985 // Invalid 11986 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11987 } 11988 if (LCanPointeeTy != RCanPointeeTy) { 11989 // Treat NULL constant as a special case in OpenCL. 11990 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11991 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11992 Diag(Loc, 11993 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11994 << LHSType << RHSType << 0 /* comparison */ 11995 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11996 } 11997 } 11998 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11999 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 12000 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 12001 : CK_BitCast; 12002 if (LHSIsNull && !RHSIsNull) 12003 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 12004 else 12005 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 12006 } 12007 return computeResultTy(); 12008 } 12009 12010 if (getLangOpts().CPlusPlus) { 12011 // C++ [expr.eq]p4: 12012 // Two operands of type std::nullptr_t or one operand of type 12013 // std::nullptr_t and the other a null pointer constant compare equal. 12014 if (!IsOrdered && LHSIsNull && RHSIsNull) { 12015 if (LHSType->isNullPtrType()) { 12016 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12017 return computeResultTy(); 12018 } 12019 if (RHSType->isNullPtrType()) { 12020 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12021 return computeResultTy(); 12022 } 12023 } 12024 12025 // Comparison of Objective-C pointers and block pointers against nullptr_t. 12026 // These aren't covered by the composite pointer type rules. 12027 if (!IsOrdered && RHSType->isNullPtrType() && 12028 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 12029 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12030 return computeResultTy(); 12031 } 12032 if (!IsOrdered && LHSType->isNullPtrType() && 12033 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 12034 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12035 return computeResultTy(); 12036 } 12037 12038 if (IsRelational && 12039 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 12040 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 12041 // HACK: Relational comparison of nullptr_t against a pointer type is 12042 // invalid per DR583, but we allow it within std::less<> and friends, 12043 // since otherwise common uses of it break. 12044 // FIXME: Consider removing this hack once LWG fixes std::less<> and 12045 // friends to have std::nullptr_t overload candidates. 12046 DeclContext *DC = CurContext; 12047 if (isa<FunctionDecl>(DC)) 12048 DC = DC->getParent(); 12049 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 12050 if (CTSD->isInStdNamespace() && 12051 llvm::StringSwitch<bool>(CTSD->getName()) 12052 .Cases("less", "less_equal", "greater", "greater_equal", true) 12053 .Default(false)) { 12054 if (RHSType->isNullPtrType()) 12055 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12056 else 12057 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12058 return computeResultTy(); 12059 } 12060 } 12061 } 12062 12063 // C++ [expr.eq]p2: 12064 // If at least one operand is a pointer to member, [...] bring them to 12065 // their composite pointer type. 12066 if (!IsOrdered && 12067 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 12068 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12069 return QualType(); 12070 else 12071 return computeResultTy(); 12072 } 12073 } 12074 12075 // Handle block pointer types. 12076 if (!IsOrdered && LHSType->isBlockPointerType() && 12077 RHSType->isBlockPointerType()) { 12078 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 12079 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 12080 12081 if (!LHSIsNull && !RHSIsNull && 12082 !Context.typesAreCompatible(lpointee, rpointee)) { 12083 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12084 << LHSType << RHSType << LHS.get()->getSourceRange() 12085 << RHS.get()->getSourceRange(); 12086 } 12087 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12088 return computeResultTy(); 12089 } 12090 12091 // Allow block pointers to be compared with null pointer constants. 12092 if (!IsOrdered 12093 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 12094 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 12095 if (!LHSIsNull && !RHSIsNull) { 12096 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 12097 ->getPointeeType()->isVoidType()) 12098 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12099 ->getPointeeType()->isVoidType()))) 12100 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12101 << LHSType << RHSType << LHS.get()->getSourceRange() 12102 << RHS.get()->getSourceRange(); 12103 } 12104 if (LHSIsNull && !RHSIsNull) 12105 LHS = ImpCastExprToType(LHS.get(), RHSType, 12106 RHSType->isPointerType() ? CK_BitCast 12107 : CK_AnyPointerToBlockPointerCast); 12108 else 12109 RHS = ImpCastExprToType(RHS.get(), LHSType, 12110 LHSType->isPointerType() ? CK_BitCast 12111 : CK_AnyPointerToBlockPointerCast); 12112 return computeResultTy(); 12113 } 12114 12115 if (LHSType->isObjCObjectPointerType() || 12116 RHSType->isObjCObjectPointerType()) { 12117 const PointerType *LPT = LHSType->getAs<PointerType>(); 12118 const PointerType *RPT = RHSType->getAs<PointerType>(); 12119 if (LPT || RPT) { 12120 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12121 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12122 12123 if (!LPtrToVoid && !RPtrToVoid && 12124 !Context.typesAreCompatible(LHSType, RHSType)) { 12125 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12126 /*isError*/false); 12127 } 12128 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12129 // the RHS, but we have test coverage for this behavior. 12130 // FIXME: Consider using convertPointersToCompositeType in C++. 12131 if (LHSIsNull && !RHSIsNull) { 12132 Expr *E = LHS.get(); 12133 if (getLangOpts().ObjCAutoRefCount) 12134 CheckObjCConversion(SourceRange(), RHSType, E, 12135 CCK_ImplicitConversion); 12136 LHS = ImpCastExprToType(E, RHSType, 12137 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12138 } 12139 else { 12140 Expr *E = RHS.get(); 12141 if (getLangOpts().ObjCAutoRefCount) 12142 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12143 /*Diagnose=*/true, 12144 /*DiagnoseCFAudited=*/false, Opc); 12145 RHS = ImpCastExprToType(E, LHSType, 12146 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12147 } 12148 return computeResultTy(); 12149 } 12150 if (LHSType->isObjCObjectPointerType() && 12151 RHSType->isObjCObjectPointerType()) { 12152 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12153 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12154 /*isError*/false); 12155 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12156 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12157 12158 if (LHSIsNull && !RHSIsNull) 12159 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12160 else 12161 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12162 return computeResultTy(); 12163 } 12164 12165 if (!IsOrdered && LHSType->isBlockPointerType() && 12166 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12167 LHS = ImpCastExprToType(LHS.get(), RHSType, 12168 CK_BlockPointerToObjCPointerCast); 12169 return computeResultTy(); 12170 } else if (!IsOrdered && 12171 LHSType->isBlockCompatibleObjCPointerType(Context) && 12172 RHSType->isBlockPointerType()) { 12173 RHS = ImpCastExprToType(RHS.get(), LHSType, 12174 CK_BlockPointerToObjCPointerCast); 12175 return computeResultTy(); 12176 } 12177 } 12178 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12179 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12180 unsigned DiagID = 0; 12181 bool isError = false; 12182 if (LangOpts.DebuggerSupport) { 12183 // Under a debugger, allow the comparison of pointers to integers, 12184 // since users tend to want to compare addresses. 12185 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12186 (RHSIsNull && RHSType->isIntegerType())) { 12187 if (IsOrdered) { 12188 isError = getLangOpts().CPlusPlus; 12189 DiagID = 12190 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12191 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12192 } 12193 } else if (getLangOpts().CPlusPlus) { 12194 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12195 isError = true; 12196 } else if (IsOrdered) 12197 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12198 else 12199 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12200 12201 if (DiagID) { 12202 Diag(Loc, DiagID) 12203 << LHSType << RHSType << LHS.get()->getSourceRange() 12204 << RHS.get()->getSourceRange(); 12205 if (isError) 12206 return QualType(); 12207 } 12208 12209 if (LHSType->isIntegerType()) 12210 LHS = ImpCastExprToType(LHS.get(), RHSType, 12211 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12212 else 12213 RHS = ImpCastExprToType(RHS.get(), LHSType, 12214 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12215 return computeResultTy(); 12216 } 12217 12218 // Handle block pointers. 12219 if (!IsOrdered && RHSIsNull 12220 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12221 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12222 return computeResultTy(); 12223 } 12224 if (!IsOrdered && LHSIsNull 12225 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12226 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12227 return computeResultTy(); 12228 } 12229 12230 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 12231 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12232 return computeResultTy(); 12233 } 12234 12235 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12236 return computeResultTy(); 12237 } 12238 12239 if (LHSIsNull && RHSType->isQueueT()) { 12240 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12241 return computeResultTy(); 12242 } 12243 12244 if (LHSType->isQueueT() && RHSIsNull) { 12245 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12246 return computeResultTy(); 12247 } 12248 } 12249 12250 return InvalidOperands(Loc, LHS, RHS); 12251 } 12252 12253 // Return a signed ext_vector_type that is of identical size and number of 12254 // elements. For floating point vectors, return an integer type of identical 12255 // size and number of elements. In the non ext_vector_type case, search from 12256 // the largest type to the smallest type to avoid cases where long long == long, 12257 // where long gets picked over long long. 12258 QualType Sema::GetSignedVectorType(QualType V) { 12259 const VectorType *VTy = V->castAs<VectorType>(); 12260 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12261 12262 if (isa<ExtVectorType>(VTy)) { 12263 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12264 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12265 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12266 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12267 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12268 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12269 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12270 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12271 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12272 "Unhandled vector element size in vector compare"); 12273 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12274 } 12275 12276 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12277 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12278 VectorType::GenericVector); 12279 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12280 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12281 VectorType::GenericVector); 12282 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12283 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12284 VectorType::GenericVector); 12285 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12286 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12287 VectorType::GenericVector); 12288 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12289 "Unhandled vector element size in vector compare"); 12290 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12291 VectorType::GenericVector); 12292 } 12293 12294 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12295 /// operates on extended vector types. Instead of producing an IntTy result, 12296 /// like a scalar comparison, a vector comparison produces a vector of integer 12297 /// types. 12298 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12299 SourceLocation Loc, 12300 BinaryOperatorKind Opc) { 12301 if (Opc == BO_Cmp) { 12302 Diag(Loc, diag::err_three_way_vector_comparison); 12303 return QualType(); 12304 } 12305 12306 // Check to make sure we're operating on vectors of the same type and width, 12307 // Allowing one side to be a scalar of element type. 12308 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12309 /*AllowBothBool*/true, 12310 /*AllowBoolConversions*/getLangOpts().ZVector); 12311 if (vType.isNull()) 12312 return vType; 12313 12314 QualType LHSType = LHS.get()->getType(); 12315 12316 // Determine the return type of a vector compare. By default clang will return 12317 // a scalar for all vector compares except vector bool and vector pixel. 12318 // With the gcc compiler we will always return a vector type and with the xl 12319 // compiler we will always return a scalar type. This switch allows choosing 12320 // which behavior is prefered. 12321 if (getLangOpts().AltiVec) { 12322 switch (getLangOpts().getAltivecSrcCompat()) { 12323 case LangOptions::AltivecSrcCompatKind::Mixed: 12324 // If AltiVec, the comparison results in a numeric type, i.e. 12325 // bool for C++, int for C 12326 if (vType->castAs<VectorType>()->getVectorKind() == 12327 VectorType::AltiVecVector) 12328 return Context.getLogicalOperationType(); 12329 else 12330 Diag(Loc, diag::warn_deprecated_altivec_src_compat); 12331 break; 12332 case LangOptions::AltivecSrcCompatKind::GCC: 12333 // For GCC we always return the vector type. 12334 break; 12335 case LangOptions::AltivecSrcCompatKind::XL: 12336 return Context.getLogicalOperationType(); 12337 break; 12338 } 12339 } 12340 12341 // For non-floating point types, check for self-comparisons of the form 12342 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12343 // often indicate logic errors in the program. 12344 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12345 12346 // Check for comparisons of floating point operands using != and ==. 12347 if (BinaryOperator::isEqualityOp(Opc) && 12348 LHSType->hasFloatingRepresentation()) { 12349 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12350 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12351 } 12352 12353 // Return a signed type for the vector. 12354 return GetSignedVectorType(vType); 12355 } 12356 12357 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12358 const ExprResult &XorRHS, 12359 const SourceLocation Loc) { 12360 // Do not diagnose macros. 12361 if (Loc.isMacroID()) 12362 return; 12363 12364 // Do not diagnose if both LHS and RHS are macros. 12365 if (XorLHS.get()->getExprLoc().isMacroID() && 12366 XorRHS.get()->getExprLoc().isMacroID()) 12367 return; 12368 12369 bool Negative = false; 12370 bool ExplicitPlus = false; 12371 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12372 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12373 12374 if (!LHSInt) 12375 return; 12376 if (!RHSInt) { 12377 // Check negative literals. 12378 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12379 UnaryOperatorKind Opc = UO->getOpcode(); 12380 if (Opc != UO_Minus && Opc != UO_Plus) 12381 return; 12382 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12383 if (!RHSInt) 12384 return; 12385 Negative = (Opc == UO_Minus); 12386 ExplicitPlus = !Negative; 12387 } else { 12388 return; 12389 } 12390 } 12391 12392 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12393 llvm::APInt RightSideValue = RHSInt->getValue(); 12394 if (LeftSideValue != 2 && LeftSideValue != 10) 12395 return; 12396 12397 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12398 return; 12399 12400 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12401 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12402 llvm::StringRef ExprStr = 12403 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12404 12405 CharSourceRange XorRange = 12406 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12407 llvm::StringRef XorStr = 12408 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12409 // Do not diagnose if xor keyword/macro is used. 12410 if (XorStr == "xor") 12411 return; 12412 12413 std::string LHSStr = std::string(Lexer::getSourceText( 12414 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12415 S.getSourceManager(), S.getLangOpts())); 12416 std::string RHSStr = std::string(Lexer::getSourceText( 12417 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12418 S.getSourceManager(), S.getLangOpts())); 12419 12420 if (Negative) { 12421 RightSideValue = -RightSideValue; 12422 RHSStr = "-" + RHSStr; 12423 } else if (ExplicitPlus) { 12424 RHSStr = "+" + RHSStr; 12425 } 12426 12427 StringRef LHSStrRef = LHSStr; 12428 StringRef RHSStrRef = RHSStr; 12429 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12430 // literals. 12431 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12432 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12433 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12434 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12435 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12436 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12437 LHSStrRef.contains('\'') || RHSStrRef.contains('\'')) 12438 return; 12439 12440 bool SuggestXor = 12441 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12442 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12443 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12444 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12445 std::string SuggestedExpr = "1 << " + RHSStr; 12446 bool Overflow = false; 12447 llvm::APInt One = (LeftSideValue - 1); 12448 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12449 if (Overflow) { 12450 if (RightSideIntValue < 64) 12451 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12452 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 12453 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12454 else if (RightSideIntValue == 64) 12455 S.Diag(Loc, diag::warn_xor_used_as_pow) 12456 << ExprStr << toString(XorValue, 10, true); 12457 else 12458 return; 12459 } else { 12460 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12461 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 12462 << toString(PowValue, 10, true) 12463 << FixItHint::CreateReplacement( 12464 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12465 } 12466 12467 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12468 << ("0x2 ^ " + RHSStr) << SuggestXor; 12469 } else if (LeftSideValue == 10) { 12470 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12471 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12472 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 12473 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12474 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12475 << ("0xA ^ " + RHSStr) << SuggestXor; 12476 } 12477 } 12478 12479 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12480 SourceLocation Loc) { 12481 // Ensure that either both operands are of the same vector type, or 12482 // one operand is of a vector type and the other is of its element type. 12483 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12484 /*AllowBothBool*/true, 12485 /*AllowBoolConversions*/false); 12486 if (vType.isNull()) 12487 return InvalidOperands(Loc, LHS, RHS); 12488 if (getLangOpts().OpenCL && 12489 getLangOpts().getOpenCLCompatibleVersion() < 120 && 12490 vType->hasFloatingRepresentation()) 12491 return InvalidOperands(Loc, LHS, RHS); 12492 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12493 // usage of the logical operators && and || with vectors in C. This 12494 // check could be notionally dropped. 12495 if (!getLangOpts().CPlusPlus && 12496 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12497 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12498 12499 return GetSignedVectorType(LHS.get()->getType()); 12500 } 12501 12502 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12503 SourceLocation Loc, 12504 bool IsCompAssign) { 12505 if (!IsCompAssign) { 12506 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12507 if (LHS.isInvalid()) 12508 return QualType(); 12509 } 12510 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12511 if (RHS.isInvalid()) 12512 return QualType(); 12513 12514 // For conversion purposes, we ignore any qualifiers. 12515 // For example, "const float" and "float" are equivalent. 12516 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12517 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12518 12519 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12520 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12521 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12522 12523 if (Context.hasSameType(LHSType, RHSType)) 12524 return LHSType; 12525 12526 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12527 // case we have to return InvalidOperands. 12528 ExprResult OriginalLHS = LHS; 12529 ExprResult OriginalRHS = RHS; 12530 if (LHSMatType && !RHSMatType) { 12531 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12532 if (!RHS.isInvalid()) 12533 return LHSType; 12534 12535 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12536 } 12537 12538 if (!LHSMatType && RHSMatType) { 12539 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12540 if (!LHS.isInvalid()) 12541 return RHSType; 12542 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12543 } 12544 12545 return InvalidOperands(Loc, LHS, RHS); 12546 } 12547 12548 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12549 SourceLocation Loc, 12550 bool IsCompAssign) { 12551 if (!IsCompAssign) { 12552 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12553 if (LHS.isInvalid()) 12554 return QualType(); 12555 } 12556 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12557 if (RHS.isInvalid()) 12558 return QualType(); 12559 12560 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12561 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12562 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12563 12564 if (LHSMatType && RHSMatType) { 12565 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12566 return InvalidOperands(Loc, LHS, RHS); 12567 12568 if (!Context.hasSameType(LHSMatType->getElementType(), 12569 RHSMatType->getElementType())) 12570 return InvalidOperands(Loc, LHS, RHS); 12571 12572 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12573 LHSMatType->getNumRows(), 12574 RHSMatType->getNumColumns()); 12575 } 12576 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12577 } 12578 12579 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12580 SourceLocation Loc, 12581 BinaryOperatorKind Opc) { 12582 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12583 12584 bool IsCompAssign = 12585 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12586 12587 if (LHS.get()->getType()->isVectorType() || 12588 RHS.get()->getType()->isVectorType()) { 12589 if (LHS.get()->getType()->hasIntegerRepresentation() && 12590 RHS.get()->getType()->hasIntegerRepresentation()) 12591 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12592 /*AllowBothBool*/true, 12593 /*AllowBoolConversions*/getLangOpts().ZVector); 12594 return InvalidOperands(Loc, LHS, RHS); 12595 } 12596 12597 if (Opc == BO_And) 12598 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12599 12600 if (LHS.get()->getType()->hasFloatingRepresentation() || 12601 RHS.get()->getType()->hasFloatingRepresentation()) 12602 return InvalidOperands(Loc, LHS, RHS); 12603 12604 ExprResult LHSResult = LHS, RHSResult = RHS; 12605 QualType compType = UsualArithmeticConversions( 12606 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12607 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12608 return QualType(); 12609 LHS = LHSResult.get(); 12610 RHS = RHSResult.get(); 12611 12612 if (Opc == BO_Xor) 12613 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12614 12615 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12616 return compType; 12617 return InvalidOperands(Loc, LHS, RHS); 12618 } 12619 12620 // C99 6.5.[13,14] 12621 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12622 SourceLocation Loc, 12623 BinaryOperatorKind Opc) { 12624 // Check vector operands differently. 12625 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12626 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12627 12628 bool EnumConstantInBoolContext = false; 12629 for (const ExprResult &HS : {LHS, RHS}) { 12630 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12631 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12632 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12633 EnumConstantInBoolContext = true; 12634 } 12635 } 12636 12637 if (EnumConstantInBoolContext) 12638 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12639 12640 // Diagnose cases where the user write a logical and/or but probably meant a 12641 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12642 // is a constant. 12643 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12644 !LHS.get()->getType()->isBooleanType() && 12645 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12646 // Don't warn in macros or template instantiations. 12647 !Loc.isMacroID() && !inTemplateInstantiation()) { 12648 // If the RHS can be constant folded, and if it constant folds to something 12649 // that isn't 0 or 1 (which indicate a potential logical operation that 12650 // happened to fold to true/false) then warn. 12651 // Parens on the RHS are ignored. 12652 Expr::EvalResult EVResult; 12653 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12654 llvm::APSInt Result = EVResult.Val.getInt(); 12655 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12656 !RHS.get()->getExprLoc().isMacroID()) || 12657 (Result != 0 && Result != 1)) { 12658 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12659 << RHS.get()->getSourceRange() 12660 << (Opc == BO_LAnd ? "&&" : "||"); 12661 // Suggest replacing the logical operator with the bitwise version 12662 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12663 << (Opc == BO_LAnd ? "&" : "|") 12664 << FixItHint::CreateReplacement(SourceRange( 12665 Loc, getLocForEndOfToken(Loc)), 12666 Opc == BO_LAnd ? "&" : "|"); 12667 if (Opc == BO_LAnd) 12668 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12669 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12670 << FixItHint::CreateRemoval( 12671 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12672 RHS.get()->getEndLoc())); 12673 } 12674 } 12675 } 12676 12677 if (!Context.getLangOpts().CPlusPlus) { 12678 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12679 // not operate on the built-in scalar and vector float types. 12680 if (Context.getLangOpts().OpenCL && 12681 Context.getLangOpts().OpenCLVersion < 120) { 12682 if (LHS.get()->getType()->isFloatingType() || 12683 RHS.get()->getType()->isFloatingType()) 12684 return InvalidOperands(Loc, LHS, RHS); 12685 } 12686 12687 LHS = UsualUnaryConversions(LHS.get()); 12688 if (LHS.isInvalid()) 12689 return QualType(); 12690 12691 RHS = UsualUnaryConversions(RHS.get()); 12692 if (RHS.isInvalid()) 12693 return QualType(); 12694 12695 if (!LHS.get()->getType()->isScalarType() || 12696 !RHS.get()->getType()->isScalarType()) 12697 return InvalidOperands(Loc, LHS, RHS); 12698 12699 return Context.IntTy; 12700 } 12701 12702 // The following is safe because we only use this method for 12703 // non-overloadable operands. 12704 12705 // C++ [expr.log.and]p1 12706 // C++ [expr.log.or]p1 12707 // The operands are both contextually converted to type bool. 12708 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12709 if (LHSRes.isInvalid()) 12710 return InvalidOperands(Loc, LHS, RHS); 12711 LHS = LHSRes; 12712 12713 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12714 if (RHSRes.isInvalid()) 12715 return InvalidOperands(Loc, LHS, RHS); 12716 RHS = RHSRes; 12717 12718 // C++ [expr.log.and]p2 12719 // C++ [expr.log.or]p2 12720 // The result is a bool. 12721 return Context.BoolTy; 12722 } 12723 12724 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12725 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12726 if (!ME) return false; 12727 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12728 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12729 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12730 if (!Base) return false; 12731 return Base->getMethodDecl() != nullptr; 12732 } 12733 12734 /// Is the given expression (which must be 'const') a reference to a 12735 /// variable which was originally non-const, but which has become 12736 /// 'const' due to being captured within a block? 12737 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12738 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12739 assert(E->isLValue() && E->getType().isConstQualified()); 12740 E = E->IgnoreParens(); 12741 12742 // Must be a reference to a declaration from an enclosing scope. 12743 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12744 if (!DRE) return NCCK_None; 12745 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12746 12747 // The declaration must be a variable which is not declared 'const'. 12748 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12749 if (!var) return NCCK_None; 12750 if (var->getType().isConstQualified()) return NCCK_None; 12751 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12752 12753 // Decide whether the first capture was for a block or a lambda. 12754 DeclContext *DC = S.CurContext, *Prev = nullptr; 12755 // Decide whether the first capture was for a block or a lambda. 12756 while (DC) { 12757 // For init-capture, it is possible that the variable belongs to the 12758 // template pattern of the current context. 12759 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12760 if (var->isInitCapture() && 12761 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12762 break; 12763 if (DC == var->getDeclContext()) 12764 break; 12765 Prev = DC; 12766 DC = DC->getParent(); 12767 } 12768 // Unless we have an init-capture, we've gone one step too far. 12769 if (!var->isInitCapture()) 12770 DC = Prev; 12771 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12772 } 12773 12774 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12775 Ty = Ty.getNonReferenceType(); 12776 if (IsDereference && Ty->isPointerType()) 12777 Ty = Ty->getPointeeType(); 12778 return !Ty.isConstQualified(); 12779 } 12780 12781 // Update err_typecheck_assign_const and note_typecheck_assign_const 12782 // when this enum is changed. 12783 enum { 12784 ConstFunction, 12785 ConstVariable, 12786 ConstMember, 12787 ConstMethod, 12788 NestedConstMember, 12789 ConstUnknown, // Keep as last element 12790 }; 12791 12792 /// Emit the "read-only variable not assignable" error and print notes to give 12793 /// more information about why the variable is not assignable, such as pointing 12794 /// to the declaration of a const variable, showing that a method is const, or 12795 /// that the function is returning a const reference. 12796 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12797 SourceLocation Loc) { 12798 SourceRange ExprRange = E->getSourceRange(); 12799 12800 // Only emit one error on the first const found. All other consts will emit 12801 // a note to the error. 12802 bool DiagnosticEmitted = false; 12803 12804 // Track if the current expression is the result of a dereference, and if the 12805 // next checked expression is the result of a dereference. 12806 bool IsDereference = false; 12807 bool NextIsDereference = false; 12808 12809 // Loop to process MemberExpr chains. 12810 while (true) { 12811 IsDereference = NextIsDereference; 12812 12813 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12814 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12815 NextIsDereference = ME->isArrow(); 12816 const ValueDecl *VD = ME->getMemberDecl(); 12817 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12818 // Mutable fields can be modified even if the class is const. 12819 if (Field->isMutable()) { 12820 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12821 break; 12822 } 12823 12824 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12825 if (!DiagnosticEmitted) { 12826 S.Diag(Loc, diag::err_typecheck_assign_const) 12827 << ExprRange << ConstMember << false /*static*/ << Field 12828 << Field->getType(); 12829 DiagnosticEmitted = true; 12830 } 12831 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12832 << ConstMember << false /*static*/ << Field << Field->getType() 12833 << Field->getSourceRange(); 12834 } 12835 E = ME->getBase(); 12836 continue; 12837 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12838 if (VDecl->getType().isConstQualified()) { 12839 if (!DiagnosticEmitted) { 12840 S.Diag(Loc, diag::err_typecheck_assign_const) 12841 << ExprRange << ConstMember << true /*static*/ << VDecl 12842 << VDecl->getType(); 12843 DiagnosticEmitted = true; 12844 } 12845 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12846 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12847 << VDecl->getSourceRange(); 12848 } 12849 // Static fields do not inherit constness from parents. 12850 break; 12851 } 12852 break; // End MemberExpr 12853 } else if (const ArraySubscriptExpr *ASE = 12854 dyn_cast<ArraySubscriptExpr>(E)) { 12855 E = ASE->getBase()->IgnoreParenImpCasts(); 12856 continue; 12857 } else if (const ExtVectorElementExpr *EVE = 12858 dyn_cast<ExtVectorElementExpr>(E)) { 12859 E = EVE->getBase()->IgnoreParenImpCasts(); 12860 continue; 12861 } 12862 break; 12863 } 12864 12865 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12866 // Function calls 12867 const FunctionDecl *FD = CE->getDirectCallee(); 12868 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12869 if (!DiagnosticEmitted) { 12870 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12871 << ConstFunction << FD; 12872 DiagnosticEmitted = true; 12873 } 12874 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12875 diag::note_typecheck_assign_const) 12876 << ConstFunction << FD << FD->getReturnType() 12877 << FD->getReturnTypeSourceRange(); 12878 } 12879 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12880 // Point to variable declaration. 12881 if (const ValueDecl *VD = DRE->getDecl()) { 12882 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12883 if (!DiagnosticEmitted) { 12884 S.Diag(Loc, diag::err_typecheck_assign_const) 12885 << ExprRange << ConstVariable << VD << VD->getType(); 12886 DiagnosticEmitted = true; 12887 } 12888 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12889 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12890 } 12891 } 12892 } else if (isa<CXXThisExpr>(E)) { 12893 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12894 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12895 if (MD->isConst()) { 12896 if (!DiagnosticEmitted) { 12897 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12898 << ConstMethod << MD; 12899 DiagnosticEmitted = true; 12900 } 12901 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12902 << ConstMethod << MD << MD->getSourceRange(); 12903 } 12904 } 12905 } 12906 } 12907 12908 if (DiagnosticEmitted) 12909 return; 12910 12911 // Can't determine a more specific message, so display the generic error. 12912 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12913 } 12914 12915 enum OriginalExprKind { 12916 OEK_Variable, 12917 OEK_Member, 12918 OEK_LValue 12919 }; 12920 12921 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12922 const RecordType *Ty, 12923 SourceLocation Loc, SourceRange Range, 12924 OriginalExprKind OEK, 12925 bool &DiagnosticEmitted) { 12926 std::vector<const RecordType *> RecordTypeList; 12927 RecordTypeList.push_back(Ty); 12928 unsigned NextToCheckIndex = 0; 12929 // We walk the record hierarchy breadth-first to ensure that we print 12930 // diagnostics in field nesting order. 12931 while (RecordTypeList.size() > NextToCheckIndex) { 12932 bool IsNested = NextToCheckIndex > 0; 12933 for (const FieldDecl *Field : 12934 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12935 // First, check every field for constness. 12936 QualType FieldTy = Field->getType(); 12937 if (FieldTy.isConstQualified()) { 12938 if (!DiagnosticEmitted) { 12939 S.Diag(Loc, diag::err_typecheck_assign_const) 12940 << Range << NestedConstMember << OEK << VD 12941 << IsNested << Field; 12942 DiagnosticEmitted = true; 12943 } 12944 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12945 << NestedConstMember << IsNested << Field 12946 << FieldTy << Field->getSourceRange(); 12947 } 12948 12949 // Then we append it to the list to check next in order. 12950 FieldTy = FieldTy.getCanonicalType(); 12951 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12952 if (!llvm::is_contained(RecordTypeList, FieldRecTy)) 12953 RecordTypeList.push_back(FieldRecTy); 12954 } 12955 } 12956 ++NextToCheckIndex; 12957 } 12958 } 12959 12960 /// Emit an error for the case where a record we are trying to assign to has a 12961 /// const-qualified field somewhere in its hierarchy. 12962 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12963 SourceLocation Loc) { 12964 QualType Ty = E->getType(); 12965 assert(Ty->isRecordType() && "lvalue was not record?"); 12966 SourceRange Range = E->getSourceRange(); 12967 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12968 bool DiagEmitted = false; 12969 12970 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12971 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12972 Range, OEK_Member, DiagEmitted); 12973 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12974 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12975 Range, OEK_Variable, DiagEmitted); 12976 else 12977 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12978 Range, OEK_LValue, DiagEmitted); 12979 if (!DiagEmitted) 12980 DiagnoseConstAssignment(S, E, Loc); 12981 } 12982 12983 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12984 /// emit an error and return true. If so, return false. 12985 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12986 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12987 12988 S.CheckShadowingDeclModification(E, Loc); 12989 12990 SourceLocation OrigLoc = Loc; 12991 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12992 &Loc); 12993 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12994 IsLV = Expr::MLV_InvalidMessageExpression; 12995 if (IsLV == Expr::MLV_Valid) 12996 return false; 12997 12998 unsigned DiagID = 0; 12999 bool NeedType = false; 13000 switch (IsLV) { // C99 6.5.16p2 13001 case Expr::MLV_ConstQualified: 13002 // Use a specialized diagnostic when we're assigning to an object 13003 // from an enclosing function or block. 13004 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 13005 if (NCCK == NCCK_Block) 13006 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 13007 else 13008 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 13009 break; 13010 } 13011 13012 // In ARC, use some specialized diagnostics for occasions where we 13013 // infer 'const'. These are always pseudo-strong variables. 13014 if (S.getLangOpts().ObjCAutoRefCount) { 13015 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 13016 if (declRef && isa<VarDecl>(declRef->getDecl())) { 13017 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 13018 13019 // Use the normal diagnostic if it's pseudo-__strong but the 13020 // user actually wrote 'const'. 13021 if (var->isARCPseudoStrong() && 13022 (!var->getTypeSourceInfo() || 13023 !var->getTypeSourceInfo()->getType().isConstQualified())) { 13024 // There are three pseudo-strong cases: 13025 // - self 13026 ObjCMethodDecl *method = S.getCurMethodDecl(); 13027 if (method && var == method->getSelfDecl()) { 13028 DiagID = method->isClassMethod() 13029 ? diag::err_typecheck_arc_assign_self_class_method 13030 : diag::err_typecheck_arc_assign_self; 13031 13032 // - Objective-C externally_retained attribute. 13033 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 13034 isa<ParmVarDecl>(var)) { 13035 DiagID = diag::err_typecheck_arc_assign_externally_retained; 13036 13037 // - fast enumeration variables 13038 } else { 13039 DiagID = diag::err_typecheck_arr_assign_enumeration; 13040 } 13041 13042 SourceRange Assign; 13043 if (Loc != OrigLoc) 13044 Assign = SourceRange(OrigLoc, OrigLoc); 13045 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13046 // We need to preserve the AST regardless, so migration tool 13047 // can do its job. 13048 return false; 13049 } 13050 } 13051 } 13052 13053 // If none of the special cases above are triggered, then this is a 13054 // simple const assignment. 13055 if (DiagID == 0) { 13056 DiagnoseConstAssignment(S, E, Loc); 13057 return true; 13058 } 13059 13060 break; 13061 case Expr::MLV_ConstAddrSpace: 13062 DiagnoseConstAssignment(S, E, Loc); 13063 return true; 13064 case Expr::MLV_ConstQualifiedField: 13065 DiagnoseRecursiveConstFields(S, E, Loc); 13066 return true; 13067 case Expr::MLV_ArrayType: 13068 case Expr::MLV_ArrayTemporary: 13069 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 13070 NeedType = true; 13071 break; 13072 case Expr::MLV_NotObjectType: 13073 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 13074 NeedType = true; 13075 break; 13076 case Expr::MLV_LValueCast: 13077 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 13078 break; 13079 case Expr::MLV_Valid: 13080 llvm_unreachable("did not take early return for MLV_Valid"); 13081 case Expr::MLV_InvalidExpression: 13082 case Expr::MLV_MemberFunction: 13083 case Expr::MLV_ClassTemporary: 13084 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 13085 break; 13086 case Expr::MLV_IncompleteType: 13087 case Expr::MLV_IncompleteVoidType: 13088 return S.RequireCompleteType(Loc, E->getType(), 13089 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 13090 case Expr::MLV_DuplicateVectorComponents: 13091 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 13092 break; 13093 case Expr::MLV_NoSetterProperty: 13094 llvm_unreachable("readonly properties should be processed differently"); 13095 case Expr::MLV_InvalidMessageExpression: 13096 DiagID = diag::err_readonly_message_assignment; 13097 break; 13098 case Expr::MLV_SubObjCPropertySetting: 13099 DiagID = diag::err_no_subobject_property_setting; 13100 break; 13101 } 13102 13103 SourceRange Assign; 13104 if (Loc != OrigLoc) 13105 Assign = SourceRange(OrigLoc, OrigLoc); 13106 if (NeedType) 13107 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 13108 else 13109 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13110 return true; 13111 } 13112 13113 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 13114 SourceLocation Loc, 13115 Sema &Sema) { 13116 if (Sema.inTemplateInstantiation()) 13117 return; 13118 if (Sema.isUnevaluatedContext()) 13119 return; 13120 if (Loc.isInvalid() || Loc.isMacroID()) 13121 return; 13122 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 13123 return; 13124 13125 // C / C++ fields 13126 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 13127 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 13128 if (ML && MR) { 13129 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 13130 return; 13131 const ValueDecl *LHSDecl = 13132 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 13133 const ValueDecl *RHSDecl = 13134 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13135 if (LHSDecl != RHSDecl) 13136 return; 13137 if (LHSDecl->getType().isVolatileQualified()) 13138 return; 13139 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13140 if (RefTy->getPointeeType().isVolatileQualified()) 13141 return; 13142 13143 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13144 } 13145 13146 // Objective-C instance variables 13147 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13148 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13149 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13150 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13151 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13152 if (RL && RR && RL->getDecl() == RR->getDecl()) 13153 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13154 } 13155 } 13156 13157 // C99 6.5.16.1 13158 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13159 SourceLocation Loc, 13160 QualType CompoundType) { 13161 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13162 13163 // Verify that LHS is a modifiable lvalue, and emit error if not. 13164 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13165 return QualType(); 13166 13167 QualType LHSType = LHSExpr->getType(); 13168 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13169 CompoundType; 13170 // OpenCL v1.2 s6.1.1.1 p2: 13171 // The half data type can only be used to declare a pointer to a buffer that 13172 // contains half values 13173 if (getLangOpts().OpenCL && 13174 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13175 LHSType->isHalfType()) { 13176 Diag(Loc, diag::err_opencl_half_load_store) << 1 13177 << LHSType.getUnqualifiedType(); 13178 return QualType(); 13179 } 13180 13181 AssignConvertType ConvTy; 13182 if (CompoundType.isNull()) { 13183 Expr *RHSCheck = RHS.get(); 13184 13185 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13186 13187 QualType LHSTy(LHSType); 13188 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13189 if (RHS.isInvalid()) 13190 return QualType(); 13191 // Special case of NSObject attributes on c-style pointer types. 13192 if (ConvTy == IncompatiblePointer && 13193 ((Context.isObjCNSObjectType(LHSType) && 13194 RHSType->isObjCObjectPointerType()) || 13195 (Context.isObjCNSObjectType(RHSType) && 13196 LHSType->isObjCObjectPointerType()))) 13197 ConvTy = Compatible; 13198 13199 if (ConvTy == Compatible && 13200 LHSType->isObjCObjectType()) 13201 Diag(Loc, diag::err_objc_object_assignment) 13202 << LHSType; 13203 13204 // If the RHS is a unary plus or minus, check to see if they = and + are 13205 // right next to each other. If so, the user may have typo'd "x =+ 4" 13206 // instead of "x += 4". 13207 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13208 RHSCheck = ICE->getSubExpr(); 13209 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13210 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13211 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13212 // Only if the two operators are exactly adjacent. 13213 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13214 // And there is a space or other character before the subexpr of the 13215 // unary +/-. We don't want to warn on "x=-1". 13216 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13217 UO->getSubExpr()->getBeginLoc().isFileID()) { 13218 Diag(Loc, diag::warn_not_compound_assign) 13219 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13220 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13221 } 13222 } 13223 13224 if (ConvTy == Compatible) { 13225 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13226 // Warn about retain cycles where a block captures the LHS, but 13227 // not if the LHS is a simple variable into which the block is 13228 // being stored...unless that variable can be captured by reference! 13229 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13230 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13231 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13232 checkRetainCycles(LHSExpr, RHS.get()); 13233 } 13234 13235 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13236 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13237 // It is safe to assign a weak reference into a strong variable. 13238 // Although this code can still have problems: 13239 // id x = self.weakProp; 13240 // id y = self.weakProp; 13241 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13242 // paths through the function. This should be revisited if 13243 // -Wrepeated-use-of-weak is made flow-sensitive. 13244 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13245 // variable, which will be valid for the current autorelease scope. 13246 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13247 RHS.get()->getBeginLoc())) 13248 getCurFunction()->markSafeWeakUse(RHS.get()); 13249 13250 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13251 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13252 } 13253 } 13254 } else { 13255 // Compound assignment "x += y" 13256 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13257 } 13258 13259 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13260 RHS.get(), AA_Assigning)) 13261 return QualType(); 13262 13263 CheckForNullPointerDereference(*this, LHSExpr); 13264 13265 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13266 if (CompoundType.isNull()) { 13267 // C++2a [expr.ass]p5: 13268 // A simple-assignment whose left operand is of a volatile-qualified 13269 // type is deprecated unless the assignment is either a discarded-value 13270 // expression or an unevaluated operand 13271 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13272 } else { 13273 // C++2a [expr.ass]p6: 13274 // [Compound-assignment] expressions are deprecated if E1 has 13275 // volatile-qualified type 13276 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13277 } 13278 } 13279 13280 // C99 6.5.16p3: The type of an assignment expression is the type of the 13281 // left operand unless the left operand has qualified type, in which case 13282 // it is the unqualified version of the type of the left operand. 13283 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13284 // is converted to the type of the assignment expression (above). 13285 // C++ 5.17p1: the type of the assignment expression is that of its left 13286 // operand. 13287 return (getLangOpts().CPlusPlus 13288 ? LHSType : LHSType.getUnqualifiedType()); 13289 } 13290 13291 // Only ignore explicit casts to void. 13292 static bool IgnoreCommaOperand(const Expr *E) { 13293 E = E->IgnoreParens(); 13294 13295 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13296 if (CE->getCastKind() == CK_ToVoid) { 13297 return true; 13298 } 13299 13300 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13301 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13302 CE->getSubExpr()->getType()->isDependentType()) { 13303 return true; 13304 } 13305 } 13306 13307 return false; 13308 } 13309 13310 // Look for instances where it is likely the comma operator is confused with 13311 // another operator. There is an explicit list of acceptable expressions for 13312 // the left hand side of the comma operator, otherwise emit a warning. 13313 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13314 // No warnings in macros 13315 if (Loc.isMacroID()) 13316 return; 13317 13318 // Don't warn in template instantiations. 13319 if (inTemplateInstantiation()) 13320 return; 13321 13322 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13323 // instead, skip more than needed, then call back into here with the 13324 // CommaVisitor in SemaStmt.cpp. 13325 // The listed locations are the initialization and increment portions 13326 // of a for loop. The additional checks are on the condition of 13327 // if statements, do/while loops, and for loops. 13328 // Differences in scope flags for C89 mode requires the extra logic. 13329 const unsigned ForIncrementFlags = 13330 getLangOpts().C99 || getLangOpts().CPlusPlus 13331 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13332 : Scope::ContinueScope | Scope::BreakScope; 13333 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13334 const unsigned ScopeFlags = getCurScope()->getFlags(); 13335 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13336 (ScopeFlags & ForInitFlags) == ForInitFlags) 13337 return; 13338 13339 // If there are multiple comma operators used together, get the RHS of the 13340 // of the comma operator as the LHS. 13341 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13342 if (BO->getOpcode() != BO_Comma) 13343 break; 13344 LHS = BO->getRHS(); 13345 } 13346 13347 // Only allow some expressions on LHS to not warn. 13348 if (IgnoreCommaOperand(LHS)) 13349 return; 13350 13351 Diag(Loc, diag::warn_comma_operator); 13352 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13353 << LHS->getSourceRange() 13354 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13355 LangOpts.CPlusPlus ? "static_cast<void>(" 13356 : "(void)(") 13357 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13358 ")"); 13359 } 13360 13361 // C99 6.5.17 13362 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13363 SourceLocation Loc) { 13364 LHS = S.CheckPlaceholderExpr(LHS.get()); 13365 RHS = S.CheckPlaceholderExpr(RHS.get()); 13366 if (LHS.isInvalid() || RHS.isInvalid()) 13367 return QualType(); 13368 13369 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13370 // operands, but not unary promotions. 13371 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13372 13373 // So we treat the LHS as a ignored value, and in C++ we allow the 13374 // containing site to determine what should be done with the RHS. 13375 LHS = S.IgnoredValueConversions(LHS.get()); 13376 if (LHS.isInvalid()) 13377 return QualType(); 13378 13379 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand); 13380 13381 if (!S.getLangOpts().CPlusPlus) { 13382 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13383 if (RHS.isInvalid()) 13384 return QualType(); 13385 if (!RHS.get()->getType()->isVoidType()) 13386 S.RequireCompleteType(Loc, RHS.get()->getType(), 13387 diag::err_incomplete_type); 13388 } 13389 13390 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13391 S.DiagnoseCommaOperator(LHS.get(), Loc); 13392 13393 return RHS.get()->getType(); 13394 } 13395 13396 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13397 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13398 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13399 ExprValueKind &VK, 13400 ExprObjectKind &OK, 13401 SourceLocation OpLoc, 13402 bool IsInc, bool IsPrefix) { 13403 if (Op->isTypeDependent()) 13404 return S.Context.DependentTy; 13405 13406 QualType ResType = Op->getType(); 13407 // Atomic types can be used for increment / decrement where the non-atomic 13408 // versions can, so ignore the _Atomic() specifier for the purpose of 13409 // checking. 13410 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13411 ResType = ResAtomicType->getValueType(); 13412 13413 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13414 13415 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13416 // Decrement of bool is not allowed. 13417 if (!IsInc) { 13418 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13419 return QualType(); 13420 } 13421 // Increment of bool sets it to true, but is deprecated. 13422 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13423 : diag::warn_increment_bool) 13424 << Op->getSourceRange(); 13425 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13426 // Error on enum increments and decrements in C++ mode 13427 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13428 return QualType(); 13429 } else if (ResType->isRealType()) { 13430 // OK! 13431 } else if (ResType->isPointerType()) { 13432 // C99 6.5.2.4p2, 6.5.6p2 13433 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13434 return QualType(); 13435 } else if (ResType->isObjCObjectPointerType()) { 13436 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13437 // Otherwise, we just need a complete type. 13438 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13439 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13440 return QualType(); 13441 } else if (ResType->isAnyComplexType()) { 13442 // C99 does not support ++/-- on complex types, we allow as an extension. 13443 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13444 << ResType << Op->getSourceRange(); 13445 } else if (ResType->isPlaceholderType()) { 13446 ExprResult PR = S.CheckPlaceholderExpr(Op); 13447 if (PR.isInvalid()) return QualType(); 13448 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13449 IsInc, IsPrefix); 13450 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13451 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13452 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13453 (ResType->castAs<VectorType>()->getVectorKind() != 13454 VectorType::AltiVecBool)) { 13455 // The z vector extensions allow ++ and -- for non-bool vectors. 13456 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13457 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13458 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13459 } else { 13460 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13461 << ResType << int(IsInc) << Op->getSourceRange(); 13462 return QualType(); 13463 } 13464 // At this point, we know we have a real, complex or pointer type. 13465 // Now make sure the operand is a modifiable lvalue. 13466 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13467 return QualType(); 13468 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13469 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13470 // An operand with volatile-qualified type is deprecated 13471 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13472 << IsInc << ResType; 13473 } 13474 // In C++, a prefix increment is the same type as the operand. Otherwise 13475 // (in C or with postfix), the increment is the unqualified type of the 13476 // operand. 13477 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13478 VK = VK_LValue; 13479 OK = Op->getObjectKind(); 13480 return ResType; 13481 } else { 13482 VK = VK_PRValue; 13483 return ResType.getUnqualifiedType(); 13484 } 13485 } 13486 13487 13488 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13489 /// This routine allows us to typecheck complex/recursive expressions 13490 /// where the declaration is needed for type checking. We only need to 13491 /// handle cases when the expression references a function designator 13492 /// or is an lvalue. Here are some examples: 13493 /// - &(x) => x 13494 /// - &*****f => f for f a function designator. 13495 /// - &s.xx => s 13496 /// - &s.zz[1].yy -> s, if zz is an array 13497 /// - *(x + 1) -> x, if x is an array 13498 /// - &"123"[2] -> 0 13499 /// - & __real__ x -> x 13500 /// 13501 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13502 /// members. 13503 static ValueDecl *getPrimaryDecl(Expr *E) { 13504 switch (E->getStmtClass()) { 13505 case Stmt::DeclRefExprClass: 13506 return cast<DeclRefExpr>(E)->getDecl(); 13507 case Stmt::MemberExprClass: 13508 // If this is an arrow operator, the address is an offset from 13509 // the base's value, so the object the base refers to is 13510 // irrelevant. 13511 if (cast<MemberExpr>(E)->isArrow()) 13512 return nullptr; 13513 // Otherwise, the expression refers to a part of the base 13514 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13515 case Stmt::ArraySubscriptExprClass: { 13516 // FIXME: This code shouldn't be necessary! We should catch the implicit 13517 // promotion of register arrays earlier. 13518 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13519 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13520 if (ICE->getSubExpr()->getType()->isArrayType()) 13521 return getPrimaryDecl(ICE->getSubExpr()); 13522 } 13523 return nullptr; 13524 } 13525 case Stmt::UnaryOperatorClass: { 13526 UnaryOperator *UO = cast<UnaryOperator>(E); 13527 13528 switch(UO->getOpcode()) { 13529 case UO_Real: 13530 case UO_Imag: 13531 case UO_Extension: 13532 return getPrimaryDecl(UO->getSubExpr()); 13533 default: 13534 return nullptr; 13535 } 13536 } 13537 case Stmt::ParenExprClass: 13538 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13539 case Stmt::ImplicitCastExprClass: 13540 // If the result of an implicit cast is an l-value, we care about 13541 // the sub-expression; otherwise, the result here doesn't matter. 13542 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13543 case Stmt::CXXUuidofExprClass: 13544 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13545 default: 13546 return nullptr; 13547 } 13548 } 13549 13550 namespace { 13551 enum { 13552 AO_Bit_Field = 0, 13553 AO_Vector_Element = 1, 13554 AO_Property_Expansion = 2, 13555 AO_Register_Variable = 3, 13556 AO_Matrix_Element = 4, 13557 AO_No_Error = 5 13558 }; 13559 } 13560 /// Diagnose invalid operand for address of operations. 13561 /// 13562 /// \param Type The type of operand which cannot have its address taken. 13563 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13564 Expr *E, unsigned Type) { 13565 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13566 } 13567 13568 /// CheckAddressOfOperand - The operand of & must be either a function 13569 /// designator or an lvalue designating an object. If it is an lvalue, the 13570 /// object cannot be declared with storage class register or be a bit field. 13571 /// Note: The usual conversions are *not* applied to the operand of the & 13572 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13573 /// In C++, the operand might be an overloaded function name, in which case 13574 /// we allow the '&' but retain the overloaded-function type. 13575 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13576 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13577 if (PTy->getKind() == BuiltinType::Overload) { 13578 Expr *E = OrigOp.get()->IgnoreParens(); 13579 if (!isa<OverloadExpr>(E)) { 13580 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13581 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13582 << OrigOp.get()->getSourceRange(); 13583 return QualType(); 13584 } 13585 13586 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13587 if (isa<UnresolvedMemberExpr>(Ovl)) 13588 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13589 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13590 << OrigOp.get()->getSourceRange(); 13591 return QualType(); 13592 } 13593 13594 return Context.OverloadTy; 13595 } 13596 13597 if (PTy->getKind() == BuiltinType::UnknownAny) 13598 return Context.UnknownAnyTy; 13599 13600 if (PTy->getKind() == BuiltinType::BoundMember) { 13601 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13602 << OrigOp.get()->getSourceRange(); 13603 return QualType(); 13604 } 13605 13606 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13607 if (OrigOp.isInvalid()) return QualType(); 13608 } 13609 13610 if (OrigOp.get()->isTypeDependent()) 13611 return Context.DependentTy; 13612 13613 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13614 13615 // Make sure to ignore parentheses in subsequent checks 13616 Expr *op = OrigOp.get()->IgnoreParens(); 13617 13618 // In OpenCL captures for blocks called as lambda functions 13619 // are located in the private address space. Blocks used in 13620 // enqueue_kernel can be located in a different address space 13621 // depending on a vendor implementation. Thus preventing 13622 // taking an address of the capture to avoid invalid AS casts. 13623 if (LangOpts.OpenCL) { 13624 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13625 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13626 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13627 return QualType(); 13628 } 13629 } 13630 13631 if (getLangOpts().C99) { 13632 // Implement C99-only parts of addressof rules. 13633 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13634 if (uOp->getOpcode() == UO_Deref) 13635 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13636 // (assuming the deref expression is valid). 13637 return uOp->getSubExpr()->getType(); 13638 } 13639 // Technically, there should be a check for array subscript 13640 // expressions here, but the result of one is always an lvalue anyway. 13641 } 13642 ValueDecl *dcl = getPrimaryDecl(op); 13643 13644 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13645 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13646 op->getBeginLoc())) 13647 return QualType(); 13648 13649 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13650 unsigned AddressOfError = AO_No_Error; 13651 13652 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13653 bool sfinae = (bool)isSFINAEContext(); 13654 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13655 : diag::ext_typecheck_addrof_temporary) 13656 << op->getType() << op->getSourceRange(); 13657 if (sfinae) 13658 return QualType(); 13659 // Materialize the temporary as an lvalue so that we can take its address. 13660 OrigOp = op = 13661 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13662 } else if (isa<ObjCSelectorExpr>(op)) { 13663 return Context.getPointerType(op->getType()); 13664 } else if (lval == Expr::LV_MemberFunction) { 13665 // If it's an instance method, make a member pointer. 13666 // The expression must have exactly the form &A::foo. 13667 13668 // If the underlying expression isn't a decl ref, give up. 13669 if (!isa<DeclRefExpr>(op)) { 13670 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13671 << OrigOp.get()->getSourceRange(); 13672 return QualType(); 13673 } 13674 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13675 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13676 13677 // The id-expression was parenthesized. 13678 if (OrigOp.get() != DRE) { 13679 Diag(OpLoc, diag::err_parens_pointer_member_function) 13680 << OrigOp.get()->getSourceRange(); 13681 13682 // The method was named without a qualifier. 13683 } else if (!DRE->getQualifier()) { 13684 if (MD->getParent()->getName().empty()) 13685 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13686 << op->getSourceRange(); 13687 else { 13688 SmallString<32> Str; 13689 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13690 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13691 << op->getSourceRange() 13692 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13693 } 13694 } 13695 13696 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13697 if (isa<CXXDestructorDecl>(MD)) 13698 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13699 13700 QualType MPTy = Context.getMemberPointerType( 13701 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13702 // Under the MS ABI, lock down the inheritance model now. 13703 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13704 (void)isCompleteType(OpLoc, MPTy); 13705 return MPTy; 13706 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13707 // C99 6.5.3.2p1 13708 // The operand must be either an l-value or a function designator 13709 if (!op->getType()->isFunctionType()) { 13710 // Use a special diagnostic for loads from property references. 13711 if (isa<PseudoObjectExpr>(op)) { 13712 AddressOfError = AO_Property_Expansion; 13713 } else { 13714 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13715 << op->getType() << op->getSourceRange(); 13716 return QualType(); 13717 } 13718 } 13719 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13720 // The operand cannot be a bit-field 13721 AddressOfError = AO_Bit_Field; 13722 } else if (op->getObjectKind() == OK_VectorComponent) { 13723 // The operand cannot be an element of a vector 13724 AddressOfError = AO_Vector_Element; 13725 } else if (op->getObjectKind() == OK_MatrixComponent) { 13726 // The operand cannot be an element of a matrix. 13727 AddressOfError = AO_Matrix_Element; 13728 } else if (dcl) { // C99 6.5.3.2p1 13729 // We have an lvalue with a decl. Make sure the decl is not declared 13730 // with the register storage-class specifier. 13731 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13732 // in C++ it is not error to take address of a register 13733 // variable (c++03 7.1.1P3) 13734 if (vd->getStorageClass() == SC_Register && 13735 !getLangOpts().CPlusPlus) { 13736 AddressOfError = AO_Register_Variable; 13737 } 13738 } else if (isa<MSPropertyDecl>(dcl)) { 13739 AddressOfError = AO_Property_Expansion; 13740 } else if (isa<FunctionTemplateDecl>(dcl)) { 13741 return Context.OverloadTy; 13742 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13743 // Okay: we can take the address of a field. 13744 // Could be a pointer to member, though, if there is an explicit 13745 // scope qualifier for the class. 13746 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13747 DeclContext *Ctx = dcl->getDeclContext(); 13748 if (Ctx && Ctx->isRecord()) { 13749 if (dcl->getType()->isReferenceType()) { 13750 Diag(OpLoc, 13751 diag::err_cannot_form_pointer_to_member_of_reference_type) 13752 << dcl->getDeclName() << dcl->getType(); 13753 return QualType(); 13754 } 13755 13756 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13757 Ctx = Ctx->getParent(); 13758 13759 QualType MPTy = Context.getMemberPointerType( 13760 op->getType(), 13761 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13762 // Under the MS ABI, lock down the inheritance model now. 13763 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13764 (void)isCompleteType(OpLoc, MPTy); 13765 return MPTy; 13766 } 13767 } 13768 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13769 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13770 llvm_unreachable("Unknown/unexpected decl type"); 13771 } 13772 13773 if (AddressOfError != AO_No_Error) { 13774 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13775 return QualType(); 13776 } 13777 13778 if (lval == Expr::LV_IncompleteVoidType) { 13779 // Taking the address of a void variable is technically illegal, but we 13780 // allow it in cases which are otherwise valid. 13781 // Example: "extern void x; void* y = &x;". 13782 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13783 } 13784 13785 // If the operand has type "type", the result has type "pointer to type". 13786 if (op->getType()->isObjCObjectType()) 13787 return Context.getObjCObjectPointerType(op->getType()); 13788 13789 CheckAddressOfPackedMember(op); 13790 13791 return Context.getPointerType(op->getType()); 13792 } 13793 13794 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13795 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13796 if (!DRE) 13797 return; 13798 const Decl *D = DRE->getDecl(); 13799 if (!D) 13800 return; 13801 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13802 if (!Param) 13803 return; 13804 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13805 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13806 return; 13807 if (FunctionScopeInfo *FD = S.getCurFunction()) 13808 if (!FD->ModifiedNonNullParams.count(Param)) 13809 FD->ModifiedNonNullParams.insert(Param); 13810 } 13811 13812 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13813 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13814 SourceLocation OpLoc) { 13815 if (Op->isTypeDependent()) 13816 return S.Context.DependentTy; 13817 13818 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13819 if (ConvResult.isInvalid()) 13820 return QualType(); 13821 Op = ConvResult.get(); 13822 QualType OpTy = Op->getType(); 13823 QualType Result; 13824 13825 if (isa<CXXReinterpretCastExpr>(Op)) { 13826 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13827 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13828 Op->getSourceRange()); 13829 } 13830 13831 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13832 { 13833 Result = PT->getPointeeType(); 13834 } 13835 else if (const ObjCObjectPointerType *OPT = 13836 OpTy->getAs<ObjCObjectPointerType>()) 13837 Result = OPT->getPointeeType(); 13838 else { 13839 ExprResult PR = S.CheckPlaceholderExpr(Op); 13840 if (PR.isInvalid()) return QualType(); 13841 if (PR.get() != Op) 13842 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13843 } 13844 13845 if (Result.isNull()) { 13846 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13847 << OpTy << Op->getSourceRange(); 13848 return QualType(); 13849 } 13850 13851 // Note that per both C89 and C99, indirection is always legal, even if Result 13852 // is an incomplete type or void. It would be possible to warn about 13853 // dereferencing a void pointer, but it's completely well-defined, and such a 13854 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13855 // for pointers to 'void' but is fine for any other pointer type: 13856 // 13857 // C++ [expr.unary.op]p1: 13858 // [...] the expression to which [the unary * operator] is applied shall 13859 // be a pointer to an object type, or a pointer to a function type 13860 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13861 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13862 << OpTy << Op->getSourceRange(); 13863 13864 // Dereferences are usually l-values... 13865 VK = VK_LValue; 13866 13867 // ...except that certain expressions are never l-values in C. 13868 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13869 VK = VK_PRValue; 13870 13871 return Result; 13872 } 13873 13874 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13875 BinaryOperatorKind Opc; 13876 switch (Kind) { 13877 default: llvm_unreachable("Unknown binop!"); 13878 case tok::periodstar: Opc = BO_PtrMemD; break; 13879 case tok::arrowstar: Opc = BO_PtrMemI; break; 13880 case tok::star: Opc = BO_Mul; break; 13881 case tok::slash: Opc = BO_Div; break; 13882 case tok::percent: Opc = BO_Rem; break; 13883 case tok::plus: Opc = BO_Add; break; 13884 case tok::minus: Opc = BO_Sub; break; 13885 case tok::lessless: Opc = BO_Shl; break; 13886 case tok::greatergreater: Opc = BO_Shr; break; 13887 case tok::lessequal: Opc = BO_LE; break; 13888 case tok::less: Opc = BO_LT; break; 13889 case tok::greaterequal: Opc = BO_GE; break; 13890 case tok::greater: Opc = BO_GT; break; 13891 case tok::exclaimequal: Opc = BO_NE; break; 13892 case tok::equalequal: Opc = BO_EQ; break; 13893 case tok::spaceship: Opc = BO_Cmp; break; 13894 case tok::amp: Opc = BO_And; break; 13895 case tok::caret: Opc = BO_Xor; break; 13896 case tok::pipe: Opc = BO_Or; break; 13897 case tok::ampamp: Opc = BO_LAnd; break; 13898 case tok::pipepipe: Opc = BO_LOr; break; 13899 case tok::equal: Opc = BO_Assign; break; 13900 case tok::starequal: Opc = BO_MulAssign; break; 13901 case tok::slashequal: Opc = BO_DivAssign; break; 13902 case tok::percentequal: Opc = BO_RemAssign; break; 13903 case tok::plusequal: Opc = BO_AddAssign; break; 13904 case tok::minusequal: Opc = BO_SubAssign; break; 13905 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13906 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13907 case tok::ampequal: Opc = BO_AndAssign; break; 13908 case tok::caretequal: Opc = BO_XorAssign; break; 13909 case tok::pipeequal: Opc = BO_OrAssign; break; 13910 case tok::comma: Opc = BO_Comma; break; 13911 } 13912 return Opc; 13913 } 13914 13915 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13916 tok::TokenKind Kind) { 13917 UnaryOperatorKind Opc; 13918 switch (Kind) { 13919 default: llvm_unreachable("Unknown unary op!"); 13920 case tok::plusplus: Opc = UO_PreInc; break; 13921 case tok::minusminus: Opc = UO_PreDec; break; 13922 case tok::amp: Opc = UO_AddrOf; break; 13923 case tok::star: Opc = UO_Deref; break; 13924 case tok::plus: Opc = UO_Plus; break; 13925 case tok::minus: Opc = UO_Minus; break; 13926 case tok::tilde: Opc = UO_Not; break; 13927 case tok::exclaim: Opc = UO_LNot; break; 13928 case tok::kw___real: Opc = UO_Real; break; 13929 case tok::kw___imag: Opc = UO_Imag; break; 13930 case tok::kw___extension__: Opc = UO_Extension; break; 13931 } 13932 return Opc; 13933 } 13934 13935 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13936 /// This warning suppressed in the event of macro expansions. 13937 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13938 SourceLocation OpLoc, bool IsBuiltin) { 13939 if (S.inTemplateInstantiation()) 13940 return; 13941 if (S.isUnevaluatedContext()) 13942 return; 13943 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13944 return; 13945 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13946 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13947 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13948 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13949 if (!LHSDeclRef || !RHSDeclRef || 13950 LHSDeclRef->getLocation().isMacroID() || 13951 RHSDeclRef->getLocation().isMacroID()) 13952 return; 13953 const ValueDecl *LHSDecl = 13954 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13955 const ValueDecl *RHSDecl = 13956 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13957 if (LHSDecl != RHSDecl) 13958 return; 13959 if (LHSDecl->getType().isVolatileQualified()) 13960 return; 13961 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13962 if (RefTy->getPointeeType().isVolatileQualified()) 13963 return; 13964 13965 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13966 : diag::warn_self_assignment_overloaded) 13967 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13968 << RHSExpr->getSourceRange(); 13969 } 13970 13971 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13972 /// is usually indicative of introspection within the Objective-C pointer. 13973 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13974 SourceLocation OpLoc) { 13975 if (!S.getLangOpts().ObjC) 13976 return; 13977 13978 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13979 const Expr *LHS = L.get(); 13980 const Expr *RHS = R.get(); 13981 13982 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13983 ObjCPointerExpr = LHS; 13984 OtherExpr = RHS; 13985 } 13986 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13987 ObjCPointerExpr = RHS; 13988 OtherExpr = LHS; 13989 } 13990 13991 // This warning is deliberately made very specific to reduce false 13992 // positives with logic that uses '&' for hashing. This logic mainly 13993 // looks for code trying to introspect into tagged pointers, which 13994 // code should generally never do. 13995 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13996 unsigned Diag = diag::warn_objc_pointer_masking; 13997 // Determine if we are introspecting the result of performSelectorXXX. 13998 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13999 // Special case messages to -performSelector and friends, which 14000 // can return non-pointer values boxed in a pointer value. 14001 // Some clients may wish to silence warnings in this subcase. 14002 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 14003 Selector S = ME->getSelector(); 14004 StringRef SelArg0 = S.getNameForSlot(0); 14005 if (SelArg0.startswith("performSelector")) 14006 Diag = diag::warn_objc_pointer_masking_performSelector; 14007 } 14008 14009 S.Diag(OpLoc, Diag) 14010 << ObjCPointerExpr->getSourceRange(); 14011 } 14012 } 14013 14014 static NamedDecl *getDeclFromExpr(Expr *E) { 14015 if (!E) 14016 return nullptr; 14017 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 14018 return DRE->getDecl(); 14019 if (auto *ME = dyn_cast<MemberExpr>(E)) 14020 return ME->getMemberDecl(); 14021 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 14022 return IRE->getDecl(); 14023 return nullptr; 14024 } 14025 14026 // This helper function promotes a binary operator's operands (which are of a 14027 // half vector type) to a vector of floats and then truncates the result to 14028 // a vector of either half or short. 14029 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 14030 BinaryOperatorKind Opc, QualType ResultTy, 14031 ExprValueKind VK, ExprObjectKind OK, 14032 bool IsCompAssign, SourceLocation OpLoc, 14033 FPOptionsOverride FPFeatures) { 14034 auto &Context = S.getASTContext(); 14035 assert((isVector(ResultTy, Context.HalfTy) || 14036 isVector(ResultTy, Context.ShortTy)) && 14037 "Result must be a vector of half or short"); 14038 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 14039 isVector(RHS.get()->getType(), Context.HalfTy) && 14040 "both operands expected to be a half vector"); 14041 14042 RHS = convertVector(RHS.get(), Context.FloatTy, S); 14043 QualType BinOpResTy = RHS.get()->getType(); 14044 14045 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 14046 // change BinOpResTy to a vector of ints. 14047 if (isVector(ResultTy, Context.ShortTy)) 14048 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 14049 14050 if (IsCompAssign) 14051 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14052 ResultTy, VK, OK, OpLoc, FPFeatures, 14053 BinOpResTy, BinOpResTy); 14054 14055 LHS = convertVector(LHS.get(), Context.FloatTy, S); 14056 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14057 BinOpResTy, VK, OK, OpLoc, FPFeatures); 14058 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 14059 } 14060 14061 static std::pair<ExprResult, ExprResult> 14062 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 14063 Expr *RHSExpr) { 14064 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14065 if (!S.Context.isDependenceAllowed()) { 14066 // C cannot handle TypoExpr nodes on either side of a binop because it 14067 // doesn't handle dependent types properly, so make sure any TypoExprs have 14068 // been dealt with before checking the operands. 14069 LHS = S.CorrectDelayedTyposInExpr(LHS); 14070 RHS = S.CorrectDelayedTyposInExpr( 14071 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 14072 [Opc, LHS](Expr *E) { 14073 if (Opc != BO_Assign) 14074 return ExprResult(E); 14075 // Avoid correcting the RHS to the same Expr as the LHS. 14076 Decl *D = getDeclFromExpr(E); 14077 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 14078 }); 14079 } 14080 return std::make_pair(LHS, RHS); 14081 } 14082 14083 /// Returns true if conversion between vectors of halfs and vectors of floats 14084 /// is needed. 14085 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 14086 Expr *E0, Expr *E1 = nullptr) { 14087 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 14088 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 14089 return false; 14090 14091 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 14092 QualType Ty = E->IgnoreImplicit()->getType(); 14093 14094 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 14095 // to vectors of floats. Although the element type of the vectors is __fp16, 14096 // the vectors shouldn't be treated as storage-only types. See the 14097 // discussion here: https://reviews.llvm.org/rG825235c140e7 14098 if (const VectorType *VT = Ty->getAs<VectorType>()) { 14099 if (VT->getVectorKind() == VectorType::NeonVector) 14100 return false; 14101 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 14102 } 14103 return false; 14104 }; 14105 14106 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 14107 } 14108 14109 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 14110 /// operator @p Opc at location @c TokLoc. This routine only supports 14111 /// built-in operations; ActOnBinOp handles overloaded operators. 14112 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 14113 BinaryOperatorKind Opc, 14114 Expr *LHSExpr, Expr *RHSExpr) { 14115 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 14116 // The syntax only allows initializer lists on the RHS of assignment, 14117 // so we don't need to worry about accepting invalid code for 14118 // non-assignment operators. 14119 // C++11 5.17p9: 14120 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 14121 // of x = {} is x = T(). 14122 InitializationKind Kind = InitializationKind::CreateDirectList( 14123 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14124 InitializedEntity Entity = 14125 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 14126 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 14127 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 14128 if (Init.isInvalid()) 14129 return Init; 14130 RHSExpr = Init.get(); 14131 } 14132 14133 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14134 QualType ResultTy; // Result type of the binary operator. 14135 // The following two variables are used for compound assignment operators 14136 QualType CompLHSTy; // Type of LHS after promotions for computation 14137 QualType CompResultTy; // Type of computation result 14138 ExprValueKind VK = VK_PRValue; 14139 ExprObjectKind OK = OK_Ordinary; 14140 bool ConvertHalfVec = false; 14141 14142 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14143 if (!LHS.isUsable() || !RHS.isUsable()) 14144 return ExprError(); 14145 14146 if (getLangOpts().OpenCL) { 14147 QualType LHSTy = LHSExpr->getType(); 14148 QualType RHSTy = RHSExpr->getType(); 14149 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14150 // the ATOMIC_VAR_INIT macro. 14151 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14152 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14153 if (BO_Assign == Opc) 14154 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14155 else 14156 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14157 return ExprError(); 14158 } 14159 14160 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14161 // only with a builtin functions and therefore should be disallowed here. 14162 if (LHSTy->isImageType() || RHSTy->isImageType() || 14163 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14164 LHSTy->isPipeType() || RHSTy->isPipeType() || 14165 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14166 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14167 return ExprError(); 14168 } 14169 } 14170 14171 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14172 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14173 14174 switch (Opc) { 14175 case BO_Assign: 14176 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14177 if (getLangOpts().CPlusPlus && 14178 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14179 VK = LHS.get()->getValueKind(); 14180 OK = LHS.get()->getObjectKind(); 14181 } 14182 if (!ResultTy.isNull()) { 14183 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14184 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14185 14186 // Avoid copying a block to the heap if the block is assigned to a local 14187 // auto variable that is declared in the same scope as the block. This 14188 // optimization is unsafe if the local variable is declared in an outer 14189 // scope. For example: 14190 // 14191 // BlockTy b; 14192 // { 14193 // b = ^{...}; 14194 // } 14195 // // It is unsafe to invoke the block here if it wasn't copied to the 14196 // // heap. 14197 // b(); 14198 14199 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14200 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14201 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14202 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14203 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14204 14205 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14206 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14207 NTCUC_Assignment, NTCUK_Copy); 14208 } 14209 RecordModifiableNonNullParam(*this, LHS.get()); 14210 break; 14211 case BO_PtrMemD: 14212 case BO_PtrMemI: 14213 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14214 Opc == BO_PtrMemI); 14215 break; 14216 case BO_Mul: 14217 case BO_Div: 14218 ConvertHalfVec = true; 14219 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14220 Opc == BO_Div); 14221 break; 14222 case BO_Rem: 14223 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14224 break; 14225 case BO_Add: 14226 ConvertHalfVec = true; 14227 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14228 break; 14229 case BO_Sub: 14230 ConvertHalfVec = true; 14231 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14232 break; 14233 case BO_Shl: 14234 case BO_Shr: 14235 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14236 break; 14237 case BO_LE: 14238 case BO_LT: 14239 case BO_GE: 14240 case BO_GT: 14241 ConvertHalfVec = true; 14242 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14243 break; 14244 case BO_EQ: 14245 case BO_NE: 14246 ConvertHalfVec = true; 14247 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14248 break; 14249 case BO_Cmp: 14250 ConvertHalfVec = true; 14251 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14252 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14253 break; 14254 case BO_And: 14255 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14256 LLVM_FALLTHROUGH; 14257 case BO_Xor: 14258 case BO_Or: 14259 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14260 break; 14261 case BO_LAnd: 14262 case BO_LOr: 14263 ConvertHalfVec = true; 14264 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14265 break; 14266 case BO_MulAssign: 14267 case BO_DivAssign: 14268 ConvertHalfVec = true; 14269 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14270 Opc == BO_DivAssign); 14271 CompLHSTy = CompResultTy; 14272 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14273 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14274 break; 14275 case BO_RemAssign: 14276 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14277 CompLHSTy = CompResultTy; 14278 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14279 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14280 break; 14281 case BO_AddAssign: 14282 ConvertHalfVec = true; 14283 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14284 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14285 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14286 break; 14287 case BO_SubAssign: 14288 ConvertHalfVec = true; 14289 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14290 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14291 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14292 break; 14293 case BO_ShlAssign: 14294 case BO_ShrAssign: 14295 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14296 CompLHSTy = CompResultTy; 14297 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14298 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14299 break; 14300 case BO_AndAssign: 14301 case BO_OrAssign: // fallthrough 14302 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14303 LLVM_FALLTHROUGH; 14304 case BO_XorAssign: 14305 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14306 CompLHSTy = CompResultTy; 14307 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14308 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14309 break; 14310 case BO_Comma: 14311 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14312 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14313 VK = RHS.get()->getValueKind(); 14314 OK = RHS.get()->getObjectKind(); 14315 } 14316 break; 14317 } 14318 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14319 return ExprError(); 14320 14321 // Some of the binary operations require promoting operands of half vector to 14322 // float vectors and truncating the result back to half vector. For now, we do 14323 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14324 // arm64). 14325 assert( 14326 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14327 isVector(LHS.get()->getType(), Context.HalfTy)) && 14328 "both sides are half vectors or neither sides are"); 14329 ConvertHalfVec = 14330 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14331 14332 // Check for array bounds violations for both sides of the BinaryOperator 14333 CheckArrayAccess(LHS.get()); 14334 CheckArrayAccess(RHS.get()); 14335 14336 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14337 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14338 &Context.Idents.get("object_setClass"), 14339 SourceLocation(), LookupOrdinaryName); 14340 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14341 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14342 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14343 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14344 "object_setClass(") 14345 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14346 ",") 14347 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14348 } 14349 else 14350 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14351 } 14352 else if (const ObjCIvarRefExpr *OIRE = 14353 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14354 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14355 14356 // Opc is not a compound assignment if CompResultTy is null. 14357 if (CompResultTy.isNull()) { 14358 if (ConvertHalfVec) 14359 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14360 OpLoc, CurFPFeatureOverrides()); 14361 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14362 VK, OK, OpLoc, CurFPFeatureOverrides()); 14363 } 14364 14365 // Handle compound assignments. 14366 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14367 OK_ObjCProperty) { 14368 VK = VK_LValue; 14369 OK = LHS.get()->getObjectKind(); 14370 } 14371 14372 // The LHS is not converted to the result type for fixed-point compound 14373 // assignment as the common type is computed on demand. Reset the CompLHSTy 14374 // to the LHS type we would have gotten after unary conversions. 14375 if (CompResultTy->isFixedPointType()) 14376 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14377 14378 if (ConvertHalfVec) 14379 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14380 OpLoc, CurFPFeatureOverrides()); 14381 14382 return CompoundAssignOperator::Create( 14383 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14384 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14385 } 14386 14387 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14388 /// operators are mixed in a way that suggests that the programmer forgot that 14389 /// comparison operators have higher precedence. The most typical example of 14390 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14391 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14392 SourceLocation OpLoc, Expr *LHSExpr, 14393 Expr *RHSExpr) { 14394 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14395 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14396 14397 // Check that one of the sides is a comparison operator and the other isn't. 14398 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14399 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14400 if (isLeftComp == isRightComp) 14401 return; 14402 14403 // Bitwise operations are sometimes used as eager logical ops. 14404 // Don't diagnose this. 14405 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14406 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14407 if (isLeftBitwise || isRightBitwise) 14408 return; 14409 14410 SourceRange DiagRange = isLeftComp 14411 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14412 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14413 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14414 SourceRange ParensRange = 14415 isLeftComp 14416 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14417 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14418 14419 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14420 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14421 SuggestParentheses(Self, OpLoc, 14422 Self.PDiag(diag::note_precedence_silence) << OpStr, 14423 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14424 SuggestParentheses(Self, OpLoc, 14425 Self.PDiag(diag::note_precedence_bitwise_first) 14426 << BinaryOperator::getOpcodeStr(Opc), 14427 ParensRange); 14428 } 14429 14430 /// It accepts a '&&' expr that is inside a '||' one. 14431 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14432 /// in parentheses. 14433 static void 14434 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14435 BinaryOperator *Bop) { 14436 assert(Bop->getOpcode() == BO_LAnd); 14437 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14438 << Bop->getSourceRange() << OpLoc; 14439 SuggestParentheses(Self, Bop->getOperatorLoc(), 14440 Self.PDiag(diag::note_precedence_silence) 14441 << Bop->getOpcodeStr(), 14442 Bop->getSourceRange()); 14443 } 14444 14445 /// Returns true if the given expression can be evaluated as a constant 14446 /// 'true'. 14447 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14448 bool Res; 14449 return !E->isValueDependent() && 14450 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14451 } 14452 14453 /// Returns true if the given expression can be evaluated as a constant 14454 /// 'false'. 14455 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14456 bool Res; 14457 return !E->isValueDependent() && 14458 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14459 } 14460 14461 /// Look for '&&' in the left hand of a '||' expr. 14462 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14463 Expr *LHSExpr, Expr *RHSExpr) { 14464 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14465 if (Bop->getOpcode() == BO_LAnd) { 14466 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14467 if (EvaluatesAsFalse(S, RHSExpr)) 14468 return; 14469 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14470 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14471 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14472 } else if (Bop->getOpcode() == BO_LOr) { 14473 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14474 // If it's "a || b && 1 || c" we didn't warn earlier for 14475 // "a || b && 1", but warn now. 14476 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14477 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14478 } 14479 } 14480 } 14481 } 14482 14483 /// Look for '&&' in the right hand of a '||' expr. 14484 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14485 Expr *LHSExpr, Expr *RHSExpr) { 14486 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14487 if (Bop->getOpcode() == BO_LAnd) { 14488 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14489 if (EvaluatesAsFalse(S, LHSExpr)) 14490 return; 14491 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14492 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14493 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14494 } 14495 } 14496 } 14497 14498 /// Look for bitwise op in the left or right hand of a bitwise op with 14499 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14500 /// the '&' expression in parentheses. 14501 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14502 SourceLocation OpLoc, Expr *SubExpr) { 14503 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14504 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14505 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14506 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14507 << Bop->getSourceRange() << OpLoc; 14508 SuggestParentheses(S, Bop->getOperatorLoc(), 14509 S.PDiag(diag::note_precedence_silence) 14510 << Bop->getOpcodeStr(), 14511 Bop->getSourceRange()); 14512 } 14513 } 14514 } 14515 14516 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14517 Expr *SubExpr, StringRef Shift) { 14518 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14519 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14520 StringRef Op = Bop->getOpcodeStr(); 14521 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14522 << Bop->getSourceRange() << OpLoc << Shift << Op; 14523 SuggestParentheses(S, Bop->getOperatorLoc(), 14524 S.PDiag(diag::note_precedence_silence) << Op, 14525 Bop->getSourceRange()); 14526 } 14527 } 14528 } 14529 14530 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14531 Expr *LHSExpr, Expr *RHSExpr) { 14532 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14533 if (!OCE) 14534 return; 14535 14536 FunctionDecl *FD = OCE->getDirectCallee(); 14537 if (!FD || !FD->isOverloadedOperator()) 14538 return; 14539 14540 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14541 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14542 return; 14543 14544 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14545 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14546 << (Kind == OO_LessLess); 14547 SuggestParentheses(S, OCE->getOperatorLoc(), 14548 S.PDiag(diag::note_precedence_silence) 14549 << (Kind == OO_LessLess ? "<<" : ">>"), 14550 OCE->getSourceRange()); 14551 SuggestParentheses( 14552 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14553 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14554 } 14555 14556 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14557 /// precedence. 14558 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14559 SourceLocation OpLoc, Expr *LHSExpr, 14560 Expr *RHSExpr){ 14561 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14562 if (BinaryOperator::isBitwiseOp(Opc)) 14563 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14564 14565 // Diagnose "arg1 & arg2 | arg3" 14566 if ((Opc == BO_Or || Opc == BO_Xor) && 14567 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14568 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14569 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14570 } 14571 14572 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14573 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14574 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14575 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14576 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14577 } 14578 14579 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14580 || Opc == BO_Shr) { 14581 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14582 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14583 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14584 } 14585 14586 // Warn on overloaded shift operators and comparisons, such as: 14587 // cout << 5 == 4; 14588 if (BinaryOperator::isComparisonOp(Opc)) 14589 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14590 } 14591 14592 // Binary Operators. 'Tok' is the token for the operator. 14593 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14594 tok::TokenKind Kind, 14595 Expr *LHSExpr, Expr *RHSExpr) { 14596 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14597 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14598 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14599 14600 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14601 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14602 14603 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14604 } 14605 14606 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14607 UnresolvedSetImpl &Functions) { 14608 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14609 if (OverOp != OO_None && OverOp != OO_Equal) 14610 LookupOverloadedOperatorName(OverOp, S, Functions); 14611 14612 // In C++20 onwards, we may have a second operator to look up. 14613 if (getLangOpts().CPlusPlus20) { 14614 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14615 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14616 } 14617 } 14618 14619 /// Build an overloaded binary operator expression in the given scope. 14620 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14621 BinaryOperatorKind Opc, 14622 Expr *LHS, Expr *RHS) { 14623 switch (Opc) { 14624 case BO_Assign: 14625 case BO_DivAssign: 14626 case BO_RemAssign: 14627 case BO_SubAssign: 14628 case BO_AndAssign: 14629 case BO_OrAssign: 14630 case BO_XorAssign: 14631 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14632 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14633 break; 14634 default: 14635 break; 14636 } 14637 14638 // Find all of the overloaded operators visible from this point. 14639 UnresolvedSet<16> Functions; 14640 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14641 14642 // Build the (potentially-overloaded, potentially-dependent) 14643 // binary operation. 14644 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14645 } 14646 14647 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14648 BinaryOperatorKind Opc, 14649 Expr *LHSExpr, Expr *RHSExpr) { 14650 ExprResult LHS, RHS; 14651 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14652 if (!LHS.isUsable() || !RHS.isUsable()) 14653 return ExprError(); 14654 LHSExpr = LHS.get(); 14655 RHSExpr = RHS.get(); 14656 14657 // We want to end up calling one of checkPseudoObjectAssignment 14658 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14659 // both expressions are overloadable or either is type-dependent), 14660 // or CreateBuiltinBinOp (in any other case). We also want to get 14661 // any placeholder types out of the way. 14662 14663 // Handle pseudo-objects in the LHS. 14664 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14665 // Assignments with a pseudo-object l-value need special analysis. 14666 if (pty->getKind() == BuiltinType::PseudoObject && 14667 BinaryOperator::isAssignmentOp(Opc)) 14668 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14669 14670 // Don't resolve overloads if the other type is overloadable. 14671 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14672 // We can't actually test that if we still have a placeholder, 14673 // though. Fortunately, none of the exceptions we see in that 14674 // code below are valid when the LHS is an overload set. Note 14675 // that an overload set can be dependently-typed, but it never 14676 // instantiates to having an overloadable type. 14677 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14678 if (resolvedRHS.isInvalid()) return ExprError(); 14679 RHSExpr = resolvedRHS.get(); 14680 14681 if (RHSExpr->isTypeDependent() || 14682 RHSExpr->getType()->isOverloadableType()) 14683 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14684 } 14685 14686 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14687 // template, diagnose the missing 'template' keyword instead of diagnosing 14688 // an invalid use of a bound member function. 14689 // 14690 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14691 // to C++1z [over.over]/1.4, but we already checked for that case above. 14692 if (Opc == BO_LT && inTemplateInstantiation() && 14693 (pty->getKind() == BuiltinType::BoundMember || 14694 pty->getKind() == BuiltinType::Overload)) { 14695 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14696 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14697 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14698 return isa<FunctionTemplateDecl>(ND); 14699 })) { 14700 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14701 : OE->getNameLoc(), 14702 diag::err_template_kw_missing) 14703 << OE->getName().getAsString() << ""; 14704 return ExprError(); 14705 } 14706 } 14707 14708 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14709 if (LHS.isInvalid()) return ExprError(); 14710 LHSExpr = LHS.get(); 14711 } 14712 14713 // Handle pseudo-objects in the RHS. 14714 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14715 // An overload in the RHS can potentially be resolved by the type 14716 // being assigned to. 14717 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14718 if (getLangOpts().CPlusPlus && 14719 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14720 LHSExpr->getType()->isOverloadableType())) 14721 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14722 14723 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14724 } 14725 14726 // Don't resolve overloads if the other type is overloadable. 14727 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14728 LHSExpr->getType()->isOverloadableType()) 14729 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14730 14731 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14732 if (!resolvedRHS.isUsable()) return ExprError(); 14733 RHSExpr = resolvedRHS.get(); 14734 } 14735 14736 if (getLangOpts().CPlusPlus) { 14737 // If either expression is type-dependent, always build an 14738 // overloaded op. 14739 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14740 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14741 14742 // Otherwise, build an overloaded op if either expression has an 14743 // overloadable type. 14744 if (LHSExpr->getType()->isOverloadableType() || 14745 RHSExpr->getType()->isOverloadableType()) 14746 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14747 } 14748 14749 if (getLangOpts().RecoveryAST && 14750 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14751 assert(!getLangOpts().CPlusPlus); 14752 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14753 "Should only occur in error-recovery path."); 14754 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14755 // C [6.15.16] p3: 14756 // An assignment expression has the value of the left operand after the 14757 // assignment, but is not an lvalue. 14758 return CompoundAssignOperator::Create( 14759 Context, LHSExpr, RHSExpr, Opc, 14760 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 14761 OpLoc, CurFPFeatureOverrides()); 14762 QualType ResultType; 14763 switch (Opc) { 14764 case BO_Assign: 14765 ResultType = LHSExpr->getType().getUnqualifiedType(); 14766 break; 14767 case BO_LT: 14768 case BO_GT: 14769 case BO_LE: 14770 case BO_GE: 14771 case BO_EQ: 14772 case BO_NE: 14773 case BO_LAnd: 14774 case BO_LOr: 14775 // These operators have a fixed result type regardless of operands. 14776 ResultType = Context.IntTy; 14777 break; 14778 case BO_Comma: 14779 ResultType = RHSExpr->getType(); 14780 break; 14781 default: 14782 ResultType = Context.DependentTy; 14783 break; 14784 } 14785 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14786 VK_PRValue, OK_Ordinary, OpLoc, 14787 CurFPFeatureOverrides()); 14788 } 14789 14790 // Build a built-in binary operation. 14791 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14792 } 14793 14794 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14795 if (T.isNull() || T->isDependentType()) 14796 return false; 14797 14798 if (!T->isPromotableIntegerType()) 14799 return true; 14800 14801 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14802 } 14803 14804 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14805 UnaryOperatorKind Opc, 14806 Expr *InputExpr) { 14807 ExprResult Input = InputExpr; 14808 ExprValueKind VK = VK_PRValue; 14809 ExprObjectKind OK = OK_Ordinary; 14810 QualType resultType; 14811 bool CanOverflow = false; 14812 14813 bool ConvertHalfVec = false; 14814 if (getLangOpts().OpenCL) { 14815 QualType Ty = InputExpr->getType(); 14816 // The only legal unary operation for atomics is '&'. 14817 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14818 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14819 // only with a builtin functions and therefore should be disallowed here. 14820 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14821 || Ty->isBlockPointerType())) { 14822 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14823 << InputExpr->getType() 14824 << Input.get()->getSourceRange()); 14825 } 14826 } 14827 14828 switch (Opc) { 14829 case UO_PreInc: 14830 case UO_PreDec: 14831 case UO_PostInc: 14832 case UO_PostDec: 14833 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14834 OpLoc, 14835 Opc == UO_PreInc || 14836 Opc == UO_PostInc, 14837 Opc == UO_PreInc || 14838 Opc == UO_PreDec); 14839 CanOverflow = isOverflowingIntegerType(Context, resultType); 14840 break; 14841 case UO_AddrOf: 14842 resultType = CheckAddressOfOperand(Input, OpLoc); 14843 CheckAddressOfNoDeref(InputExpr); 14844 RecordModifiableNonNullParam(*this, InputExpr); 14845 break; 14846 case UO_Deref: { 14847 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14848 if (Input.isInvalid()) return ExprError(); 14849 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14850 break; 14851 } 14852 case UO_Plus: 14853 case UO_Minus: 14854 CanOverflow = Opc == UO_Minus && 14855 isOverflowingIntegerType(Context, Input.get()->getType()); 14856 Input = UsualUnaryConversions(Input.get()); 14857 if (Input.isInvalid()) return ExprError(); 14858 // Unary plus and minus require promoting an operand of half vector to a 14859 // float vector and truncating the result back to a half vector. For now, we 14860 // do this only when HalfArgsAndReturns is set (that is, when the target is 14861 // arm or arm64). 14862 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14863 14864 // If the operand is a half vector, promote it to a float vector. 14865 if (ConvertHalfVec) 14866 Input = convertVector(Input.get(), Context.FloatTy, *this); 14867 resultType = Input.get()->getType(); 14868 if (resultType->isDependentType()) 14869 break; 14870 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14871 break; 14872 else if (resultType->isVectorType() && 14873 // The z vector extensions don't allow + or - with bool vectors. 14874 (!Context.getLangOpts().ZVector || 14875 resultType->castAs<VectorType>()->getVectorKind() != 14876 VectorType::AltiVecBool)) 14877 break; 14878 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14879 Opc == UO_Plus && 14880 resultType->isPointerType()) 14881 break; 14882 14883 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14884 << resultType << Input.get()->getSourceRange()); 14885 14886 case UO_Not: // bitwise complement 14887 Input = UsualUnaryConversions(Input.get()); 14888 if (Input.isInvalid()) 14889 return ExprError(); 14890 resultType = Input.get()->getType(); 14891 if (resultType->isDependentType()) 14892 break; 14893 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14894 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14895 // C99 does not support '~' for complex conjugation. 14896 Diag(OpLoc, diag::ext_integer_complement_complex) 14897 << resultType << Input.get()->getSourceRange(); 14898 else if (resultType->hasIntegerRepresentation()) 14899 break; 14900 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14901 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14902 // on vector float types. 14903 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14904 if (!T->isIntegerType()) 14905 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14906 << resultType << Input.get()->getSourceRange()); 14907 } else { 14908 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14909 << resultType << Input.get()->getSourceRange()); 14910 } 14911 break; 14912 14913 case UO_LNot: // logical negation 14914 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14915 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14916 if (Input.isInvalid()) return ExprError(); 14917 resultType = Input.get()->getType(); 14918 14919 // Though we still have to promote half FP to float... 14920 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14921 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14922 resultType = Context.FloatTy; 14923 } 14924 14925 if (resultType->isDependentType()) 14926 break; 14927 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14928 // C99 6.5.3.3p1: ok, fallthrough; 14929 if (Context.getLangOpts().CPlusPlus) { 14930 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14931 // operand contextually converted to bool. 14932 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14933 ScalarTypeToBooleanCastKind(resultType)); 14934 } else if (Context.getLangOpts().OpenCL && 14935 Context.getLangOpts().OpenCLVersion < 120) { 14936 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14937 // operate on scalar float types. 14938 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14939 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14940 << resultType << Input.get()->getSourceRange()); 14941 } 14942 } else if (resultType->isExtVectorType()) { 14943 if (Context.getLangOpts().OpenCL && 14944 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { 14945 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14946 // operate on vector float types. 14947 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14948 if (!T->isIntegerType()) 14949 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14950 << resultType << Input.get()->getSourceRange()); 14951 } 14952 // Vector logical not returns the signed variant of the operand type. 14953 resultType = GetSignedVectorType(resultType); 14954 break; 14955 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14956 const VectorType *VTy = resultType->castAs<VectorType>(); 14957 if (VTy->getVectorKind() != VectorType::GenericVector) 14958 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14959 << resultType << Input.get()->getSourceRange()); 14960 14961 // Vector logical not returns the signed variant of the operand type. 14962 resultType = GetSignedVectorType(resultType); 14963 break; 14964 } else { 14965 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14966 << resultType << Input.get()->getSourceRange()); 14967 } 14968 14969 // LNot always has type int. C99 6.5.3.3p5. 14970 // In C++, it's bool. C++ 5.3.1p8 14971 resultType = Context.getLogicalOperationType(); 14972 break; 14973 case UO_Real: 14974 case UO_Imag: 14975 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14976 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14977 // complex l-values to ordinary l-values and all other values to r-values. 14978 if (Input.isInvalid()) return ExprError(); 14979 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14980 if (Input.get()->isGLValue() && 14981 Input.get()->getObjectKind() == OK_Ordinary) 14982 VK = Input.get()->getValueKind(); 14983 } else if (!getLangOpts().CPlusPlus) { 14984 // In C, a volatile scalar is read by __imag. In C++, it is not. 14985 Input = DefaultLvalueConversion(Input.get()); 14986 } 14987 break; 14988 case UO_Extension: 14989 resultType = Input.get()->getType(); 14990 VK = Input.get()->getValueKind(); 14991 OK = Input.get()->getObjectKind(); 14992 break; 14993 case UO_Coawait: 14994 // It's unnecessary to represent the pass-through operator co_await in the 14995 // AST; just return the input expression instead. 14996 assert(!Input.get()->getType()->isDependentType() && 14997 "the co_await expression must be non-dependant before " 14998 "building operator co_await"); 14999 return Input; 15000 } 15001 if (resultType.isNull() || Input.isInvalid()) 15002 return ExprError(); 15003 15004 // Check for array bounds violations in the operand of the UnaryOperator, 15005 // except for the '*' and '&' operators that have to be handled specially 15006 // by CheckArrayAccess (as there are special cases like &array[arraysize] 15007 // that are explicitly defined as valid by the standard). 15008 if (Opc != UO_AddrOf && Opc != UO_Deref) 15009 CheckArrayAccess(Input.get()); 15010 15011 auto *UO = 15012 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 15013 OpLoc, CanOverflow, CurFPFeatureOverrides()); 15014 15015 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 15016 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 15017 !isUnevaluatedContext()) 15018 ExprEvalContexts.back().PossibleDerefs.insert(UO); 15019 15020 // Convert the result back to a half vector. 15021 if (ConvertHalfVec) 15022 return convertVector(UO, Context.HalfTy, *this); 15023 return UO; 15024 } 15025 15026 /// Determine whether the given expression is a qualified member 15027 /// access expression, of a form that could be turned into a pointer to member 15028 /// with the address-of operator. 15029 bool Sema::isQualifiedMemberAccess(Expr *E) { 15030 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15031 if (!DRE->getQualifier()) 15032 return false; 15033 15034 ValueDecl *VD = DRE->getDecl(); 15035 if (!VD->isCXXClassMember()) 15036 return false; 15037 15038 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 15039 return true; 15040 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 15041 return Method->isInstance(); 15042 15043 return false; 15044 } 15045 15046 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15047 if (!ULE->getQualifier()) 15048 return false; 15049 15050 for (NamedDecl *D : ULE->decls()) { 15051 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 15052 if (Method->isInstance()) 15053 return true; 15054 } else { 15055 // Overload set does not contain methods. 15056 break; 15057 } 15058 } 15059 15060 return false; 15061 } 15062 15063 return false; 15064 } 15065 15066 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 15067 UnaryOperatorKind Opc, Expr *Input) { 15068 // First things first: handle placeholders so that the 15069 // overloaded-operator check considers the right type. 15070 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 15071 // Increment and decrement of pseudo-object references. 15072 if (pty->getKind() == BuiltinType::PseudoObject && 15073 UnaryOperator::isIncrementDecrementOp(Opc)) 15074 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 15075 15076 // extension is always a builtin operator. 15077 if (Opc == UO_Extension) 15078 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15079 15080 // & gets special logic for several kinds of placeholder. 15081 // The builtin code knows what to do. 15082 if (Opc == UO_AddrOf && 15083 (pty->getKind() == BuiltinType::Overload || 15084 pty->getKind() == BuiltinType::UnknownAny || 15085 pty->getKind() == BuiltinType::BoundMember)) 15086 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15087 15088 // Anything else needs to be handled now. 15089 ExprResult Result = CheckPlaceholderExpr(Input); 15090 if (Result.isInvalid()) return ExprError(); 15091 Input = Result.get(); 15092 } 15093 15094 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 15095 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 15096 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 15097 // Find all of the overloaded operators visible from this point. 15098 UnresolvedSet<16> Functions; 15099 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 15100 if (S && OverOp != OO_None) 15101 LookupOverloadedOperatorName(OverOp, S, Functions); 15102 15103 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 15104 } 15105 15106 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15107 } 15108 15109 // Unary Operators. 'Tok' is the token for the operator. 15110 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 15111 tok::TokenKind Op, Expr *Input) { 15112 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 15113 } 15114 15115 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 15116 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 15117 LabelDecl *TheDecl) { 15118 TheDecl->markUsed(Context); 15119 // Create the AST node. The address of a label always has type 'void*'. 15120 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 15121 Context.getPointerType(Context.VoidTy)); 15122 } 15123 15124 void Sema::ActOnStartStmtExpr() { 15125 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15126 } 15127 15128 void Sema::ActOnStmtExprError() { 15129 // Note that function is also called by TreeTransform when leaving a 15130 // StmtExpr scope without rebuilding anything. 15131 15132 DiscardCleanupsInEvaluationContext(); 15133 PopExpressionEvaluationContext(); 15134 } 15135 15136 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15137 SourceLocation RPLoc) { 15138 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15139 } 15140 15141 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15142 SourceLocation RPLoc, unsigned TemplateDepth) { 15143 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15144 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15145 15146 if (hasAnyUnrecoverableErrorsInThisFunction()) 15147 DiscardCleanupsInEvaluationContext(); 15148 assert(!Cleanup.exprNeedsCleanups() && 15149 "cleanups within StmtExpr not correctly bound!"); 15150 PopExpressionEvaluationContext(); 15151 15152 // FIXME: there are a variety of strange constraints to enforce here, for 15153 // example, it is not possible to goto into a stmt expression apparently. 15154 // More semantic analysis is needed. 15155 15156 // If there are sub-stmts in the compound stmt, take the type of the last one 15157 // as the type of the stmtexpr. 15158 QualType Ty = Context.VoidTy; 15159 bool StmtExprMayBindToTemp = false; 15160 if (!Compound->body_empty()) { 15161 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15162 if (const auto *LastStmt = 15163 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15164 if (const Expr *Value = LastStmt->getExprStmt()) { 15165 StmtExprMayBindToTemp = true; 15166 Ty = Value->getType(); 15167 } 15168 } 15169 } 15170 15171 // FIXME: Check that expression type is complete/non-abstract; statement 15172 // expressions are not lvalues. 15173 Expr *ResStmtExpr = 15174 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15175 if (StmtExprMayBindToTemp) 15176 return MaybeBindToTemporary(ResStmtExpr); 15177 return ResStmtExpr; 15178 } 15179 15180 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15181 if (ER.isInvalid()) 15182 return ExprError(); 15183 15184 // Do function/array conversion on the last expression, but not 15185 // lvalue-to-rvalue. However, initialize an unqualified type. 15186 ER = DefaultFunctionArrayConversion(ER.get()); 15187 if (ER.isInvalid()) 15188 return ExprError(); 15189 Expr *E = ER.get(); 15190 15191 if (E->isTypeDependent()) 15192 return E; 15193 15194 // In ARC, if the final expression ends in a consume, splice 15195 // the consume out and bind it later. In the alternate case 15196 // (when dealing with a retainable type), the result 15197 // initialization will create a produce. In both cases the 15198 // result will be +1, and we'll need to balance that out with 15199 // a bind. 15200 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15201 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15202 return Cast->getSubExpr(); 15203 15204 // FIXME: Provide a better location for the initialization. 15205 return PerformCopyInitialization( 15206 InitializedEntity::InitializeStmtExprResult( 15207 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15208 SourceLocation(), E); 15209 } 15210 15211 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15212 TypeSourceInfo *TInfo, 15213 ArrayRef<OffsetOfComponent> Components, 15214 SourceLocation RParenLoc) { 15215 QualType ArgTy = TInfo->getType(); 15216 bool Dependent = ArgTy->isDependentType(); 15217 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15218 15219 // We must have at least one component that refers to the type, and the first 15220 // one is known to be a field designator. Verify that the ArgTy represents 15221 // a struct/union/class. 15222 if (!Dependent && !ArgTy->isRecordType()) 15223 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15224 << ArgTy << TypeRange); 15225 15226 // Type must be complete per C99 7.17p3 because a declaring a variable 15227 // with an incomplete type would be ill-formed. 15228 if (!Dependent 15229 && RequireCompleteType(BuiltinLoc, ArgTy, 15230 diag::err_offsetof_incomplete_type, TypeRange)) 15231 return ExprError(); 15232 15233 bool DidWarnAboutNonPOD = false; 15234 QualType CurrentType = ArgTy; 15235 SmallVector<OffsetOfNode, 4> Comps; 15236 SmallVector<Expr*, 4> Exprs; 15237 for (const OffsetOfComponent &OC : Components) { 15238 if (OC.isBrackets) { 15239 // Offset of an array sub-field. TODO: Should we allow vector elements? 15240 if (!CurrentType->isDependentType()) { 15241 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15242 if(!AT) 15243 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15244 << CurrentType); 15245 CurrentType = AT->getElementType(); 15246 } else 15247 CurrentType = Context.DependentTy; 15248 15249 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15250 if (IdxRval.isInvalid()) 15251 return ExprError(); 15252 Expr *Idx = IdxRval.get(); 15253 15254 // The expression must be an integral expression. 15255 // FIXME: An integral constant expression? 15256 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15257 !Idx->getType()->isIntegerType()) 15258 return ExprError( 15259 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15260 << Idx->getSourceRange()); 15261 15262 // Record this array index. 15263 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15264 Exprs.push_back(Idx); 15265 continue; 15266 } 15267 15268 // Offset of a field. 15269 if (CurrentType->isDependentType()) { 15270 // We have the offset of a field, but we can't look into the dependent 15271 // type. Just record the identifier of the field. 15272 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15273 CurrentType = Context.DependentTy; 15274 continue; 15275 } 15276 15277 // We need to have a complete type to look into. 15278 if (RequireCompleteType(OC.LocStart, CurrentType, 15279 diag::err_offsetof_incomplete_type)) 15280 return ExprError(); 15281 15282 // Look for the designated field. 15283 const RecordType *RC = CurrentType->getAs<RecordType>(); 15284 if (!RC) 15285 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15286 << CurrentType); 15287 RecordDecl *RD = RC->getDecl(); 15288 15289 // C++ [lib.support.types]p5: 15290 // The macro offsetof accepts a restricted set of type arguments in this 15291 // International Standard. type shall be a POD structure or a POD union 15292 // (clause 9). 15293 // C++11 [support.types]p4: 15294 // If type is not a standard-layout class (Clause 9), the results are 15295 // undefined. 15296 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15297 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15298 unsigned DiagID = 15299 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15300 : diag::ext_offsetof_non_pod_type; 15301 15302 if (!IsSafe && !DidWarnAboutNonPOD && 15303 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15304 PDiag(DiagID) 15305 << SourceRange(Components[0].LocStart, OC.LocEnd) 15306 << CurrentType)) 15307 DidWarnAboutNonPOD = true; 15308 } 15309 15310 // Look for the field. 15311 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15312 LookupQualifiedName(R, RD); 15313 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15314 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15315 if (!MemberDecl) { 15316 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15317 MemberDecl = IndirectMemberDecl->getAnonField(); 15318 } 15319 15320 if (!MemberDecl) 15321 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15322 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15323 OC.LocEnd)); 15324 15325 // C99 7.17p3: 15326 // (If the specified member is a bit-field, the behavior is undefined.) 15327 // 15328 // We diagnose this as an error. 15329 if (MemberDecl->isBitField()) { 15330 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15331 << MemberDecl->getDeclName() 15332 << SourceRange(BuiltinLoc, RParenLoc); 15333 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15334 return ExprError(); 15335 } 15336 15337 RecordDecl *Parent = MemberDecl->getParent(); 15338 if (IndirectMemberDecl) 15339 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15340 15341 // If the member was found in a base class, introduce OffsetOfNodes for 15342 // the base class indirections. 15343 CXXBasePaths Paths; 15344 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15345 Paths)) { 15346 if (Paths.getDetectedVirtual()) { 15347 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15348 << MemberDecl->getDeclName() 15349 << SourceRange(BuiltinLoc, RParenLoc); 15350 return ExprError(); 15351 } 15352 15353 CXXBasePath &Path = Paths.front(); 15354 for (const CXXBasePathElement &B : Path) 15355 Comps.push_back(OffsetOfNode(B.Base)); 15356 } 15357 15358 if (IndirectMemberDecl) { 15359 for (auto *FI : IndirectMemberDecl->chain()) { 15360 assert(isa<FieldDecl>(FI)); 15361 Comps.push_back(OffsetOfNode(OC.LocStart, 15362 cast<FieldDecl>(FI), OC.LocEnd)); 15363 } 15364 } else 15365 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15366 15367 CurrentType = MemberDecl->getType().getNonReferenceType(); 15368 } 15369 15370 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15371 Comps, Exprs, RParenLoc); 15372 } 15373 15374 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15375 SourceLocation BuiltinLoc, 15376 SourceLocation TypeLoc, 15377 ParsedType ParsedArgTy, 15378 ArrayRef<OffsetOfComponent> Components, 15379 SourceLocation RParenLoc) { 15380 15381 TypeSourceInfo *ArgTInfo; 15382 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15383 if (ArgTy.isNull()) 15384 return ExprError(); 15385 15386 if (!ArgTInfo) 15387 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15388 15389 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15390 } 15391 15392 15393 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15394 Expr *CondExpr, 15395 Expr *LHSExpr, Expr *RHSExpr, 15396 SourceLocation RPLoc) { 15397 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15398 15399 ExprValueKind VK = VK_PRValue; 15400 ExprObjectKind OK = OK_Ordinary; 15401 QualType resType; 15402 bool CondIsTrue = false; 15403 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15404 resType = Context.DependentTy; 15405 } else { 15406 // The conditional expression is required to be a constant expression. 15407 llvm::APSInt condEval(32); 15408 ExprResult CondICE = VerifyIntegerConstantExpression( 15409 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15410 if (CondICE.isInvalid()) 15411 return ExprError(); 15412 CondExpr = CondICE.get(); 15413 CondIsTrue = condEval.getZExtValue(); 15414 15415 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15416 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15417 15418 resType = ActiveExpr->getType(); 15419 VK = ActiveExpr->getValueKind(); 15420 OK = ActiveExpr->getObjectKind(); 15421 } 15422 15423 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15424 resType, VK, OK, RPLoc, CondIsTrue); 15425 } 15426 15427 //===----------------------------------------------------------------------===// 15428 // Clang Extensions. 15429 //===----------------------------------------------------------------------===// 15430 15431 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15432 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15433 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15434 15435 if (LangOpts.CPlusPlus) { 15436 MangleNumberingContext *MCtx; 15437 Decl *ManglingContextDecl; 15438 std::tie(MCtx, ManglingContextDecl) = 15439 getCurrentMangleNumberContext(Block->getDeclContext()); 15440 if (MCtx) { 15441 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15442 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15443 } 15444 } 15445 15446 PushBlockScope(CurScope, Block); 15447 CurContext->addDecl(Block); 15448 if (CurScope) 15449 PushDeclContext(CurScope, Block); 15450 else 15451 CurContext = Block; 15452 15453 getCurBlock()->HasImplicitReturnType = true; 15454 15455 // Enter a new evaluation context to insulate the block from any 15456 // cleanups from the enclosing full-expression. 15457 PushExpressionEvaluationContext( 15458 ExpressionEvaluationContext::PotentiallyEvaluated); 15459 } 15460 15461 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15462 Scope *CurScope) { 15463 assert(ParamInfo.getIdentifier() == nullptr && 15464 "block-id should have no identifier!"); 15465 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15466 BlockScopeInfo *CurBlock = getCurBlock(); 15467 15468 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15469 QualType T = Sig->getType(); 15470 15471 // FIXME: We should allow unexpanded parameter packs here, but that would, 15472 // in turn, make the block expression contain unexpanded parameter packs. 15473 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15474 // Drop the parameters. 15475 FunctionProtoType::ExtProtoInfo EPI; 15476 EPI.HasTrailingReturn = false; 15477 EPI.TypeQuals.addConst(); 15478 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15479 Sig = Context.getTrivialTypeSourceInfo(T); 15480 } 15481 15482 // GetTypeForDeclarator always produces a function type for a block 15483 // literal signature. Furthermore, it is always a FunctionProtoType 15484 // unless the function was written with a typedef. 15485 assert(T->isFunctionType() && 15486 "GetTypeForDeclarator made a non-function block signature"); 15487 15488 // Look for an explicit signature in that function type. 15489 FunctionProtoTypeLoc ExplicitSignature; 15490 15491 if ((ExplicitSignature = Sig->getTypeLoc() 15492 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15493 15494 // Check whether that explicit signature was synthesized by 15495 // GetTypeForDeclarator. If so, don't save that as part of the 15496 // written signature. 15497 if (ExplicitSignature.getLocalRangeBegin() == 15498 ExplicitSignature.getLocalRangeEnd()) { 15499 // This would be much cheaper if we stored TypeLocs instead of 15500 // TypeSourceInfos. 15501 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15502 unsigned Size = Result.getFullDataSize(); 15503 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15504 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15505 15506 ExplicitSignature = FunctionProtoTypeLoc(); 15507 } 15508 } 15509 15510 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15511 CurBlock->FunctionType = T; 15512 15513 const auto *Fn = T->castAs<FunctionType>(); 15514 QualType RetTy = Fn->getReturnType(); 15515 bool isVariadic = 15516 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15517 15518 CurBlock->TheDecl->setIsVariadic(isVariadic); 15519 15520 // Context.DependentTy is used as a placeholder for a missing block 15521 // return type. TODO: what should we do with declarators like: 15522 // ^ * { ... } 15523 // If the answer is "apply template argument deduction".... 15524 if (RetTy != Context.DependentTy) { 15525 CurBlock->ReturnType = RetTy; 15526 CurBlock->TheDecl->setBlockMissingReturnType(false); 15527 CurBlock->HasImplicitReturnType = false; 15528 } 15529 15530 // Push block parameters from the declarator if we had them. 15531 SmallVector<ParmVarDecl*, 8> Params; 15532 if (ExplicitSignature) { 15533 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15534 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15535 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15536 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15537 // Diagnose this as an extension in C17 and earlier. 15538 if (!getLangOpts().C2x) 15539 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15540 } 15541 Params.push_back(Param); 15542 } 15543 15544 // Fake up parameter variables if we have a typedef, like 15545 // ^ fntype { ... } 15546 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15547 for (const auto &I : Fn->param_types()) { 15548 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15549 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15550 Params.push_back(Param); 15551 } 15552 } 15553 15554 // Set the parameters on the block decl. 15555 if (!Params.empty()) { 15556 CurBlock->TheDecl->setParams(Params); 15557 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15558 /*CheckParameterNames=*/false); 15559 } 15560 15561 // Finally we can process decl attributes. 15562 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15563 15564 // Put the parameter variables in scope. 15565 for (auto AI : CurBlock->TheDecl->parameters()) { 15566 AI->setOwningFunction(CurBlock->TheDecl); 15567 15568 // If this has an identifier, add it to the scope stack. 15569 if (AI->getIdentifier()) { 15570 CheckShadow(CurBlock->TheScope, AI); 15571 15572 PushOnScopeChains(AI, CurBlock->TheScope); 15573 } 15574 } 15575 } 15576 15577 /// ActOnBlockError - If there is an error parsing a block, this callback 15578 /// is invoked to pop the information about the block from the action impl. 15579 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15580 // Leave the expression-evaluation context. 15581 DiscardCleanupsInEvaluationContext(); 15582 PopExpressionEvaluationContext(); 15583 15584 // Pop off CurBlock, handle nested blocks. 15585 PopDeclContext(); 15586 PopFunctionScopeInfo(); 15587 } 15588 15589 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15590 /// literal was successfully completed. ^(int x){...} 15591 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15592 Stmt *Body, Scope *CurScope) { 15593 // If blocks are disabled, emit an error. 15594 if (!LangOpts.Blocks) 15595 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15596 15597 // Leave the expression-evaluation context. 15598 if (hasAnyUnrecoverableErrorsInThisFunction()) 15599 DiscardCleanupsInEvaluationContext(); 15600 assert(!Cleanup.exprNeedsCleanups() && 15601 "cleanups within block not correctly bound!"); 15602 PopExpressionEvaluationContext(); 15603 15604 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15605 BlockDecl *BD = BSI->TheDecl; 15606 15607 if (BSI->HasImplicitReturnType) 15608 deduceClosureReturnType(*BSI); 15609 15610 QualType RetTy = Context.VoidTy; 15611 if (!BSI->ReturnType.isNull()) 15612 RetTy = BSI->ReturnType; 15613 15614 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15615 QualType BlockTy; 15616 15617 // If the user wrote a function type in some form, try to use that. 15618 if (!BSI->FunctionType.isNull()) { 15619 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15620 15621 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15622 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15623 15624 // Turn protoless block types into nullary block types. 15625 if (isa<FunctionNoProtoType>(FTy)) { 15626 FunctionProtoType::ExtProtoInfo EPI; 15627 EPI.ExtInfo = Ext; 15628 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15629 15630 // Otherwise, if we don't need to change anything about the function type, 15631 // preserve its sugar structure. 15632 } else if (FTy->getReturnType() == RetTy && 15633 (!NoReturn || FTy->getNoReturnAttr())) { 15634 BlockTy = BSI->FunctionType; 15635 15636 // Otherwise, make the minimal modifications to the function type. 15637 } else { 15638 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15639 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15640 EPI.TypeQuals = Qualifiers(); 15641 EPI.ExtInfo = Ext; 15642 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15643 } 15644 15645 // If we don't have a function type, just build one from nothing. 15646 } else { 15647 FunctionProtoType::ExtProtoInfo EPI; 15648 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15649 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15650 } 15651 15652 DiagnoseUnusedParameters(BD->parameters()); 15653 BlockTy = Context.getBlockPointerType(BlockTy); 15654 15655 // If needed, diagnose invalid gotos and switches in the block. 15656 if (getCurFunction()->NeedsScopeChecking() && 15657 !PP.isCodeCompletionEnabled()) 15658 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15659 15660 BD->setBody(cast<CompoundStmt>(Body)); 15661 15662 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15663 DiagnoseUnguardedAvailabilityViolations(BD); 15664 15665 // Try to apply the named return value optimization. We have to check again 15666 // if we can do this, though, because blocks keep return statements around 15667 // to deduce an implicit return type. 15668 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15669 !BD->isDependentContext()) 15670 computeNRVO(Body, BSI); 15671 15672 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15673 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15674 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15675 NTCUK_Destruct|NTCUK_Copy); 15676 15677 PopDeclContext(); 15678 15679 // Set the captured variables on the block. 15680 SmallVector<BlockDecl::Capture, 4> Captures; 15681 for (Capture &Cap : BSI->Captures) { 15682 if (Cap.isInvalid() || Cap.isThisCapture()) 15683 continue; 15684 15685 VarDecl *Var = Cap.getVariable(); 15686 Expr *CopyExpr = nullptr; 15687 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15688 if (const RecordType *Record = 15689 Cap.getCaptureType()->getAs<RecordType>()) { 15690 // The capture logic needs the destructor, so make sure we mark it. 15691 // Usually this is unnecessary because most local variables have 15692 // their destructors marked at declaration time, but parameters are 15693 // an exception because it's technically only the call site that 15694 // actually requires the destructor. 15695 if (isa<ParmVarDecl>(Var)) 15696 FinalizeVarWithDestructor(Var, Record); 15697 15698 // Enter a separate potentially-evaluated context while building block 15699 // initializers to isolate their cleanups from those of the block 15700 // itself. 15701 // FIXME: Is this appropriate even when the block itself occurs in an 15702 // unevaluated operand? 15703 EnterExpressionEvaluationContext EvalContext( 15704 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15705 15706 SourceLocation Loc = Cap.getLocation(); 15707 15708 ExprResult Result = BuildDeclarationNameExpr( 15709 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15710 15711 // According to the blocks spec, the capture of a variable from 15712 // the stack requires a const copy constructor. This is not true 15713 // of the copy/move done to move a __block variable to the heap. 15714 if (!Result.isInvalid() && 15715 !Result.get()->getType().isConstQualified()) { 15716 Result = ImpCastExprToType(Result.get(), 15717 Result.get()->getType().withConst(), 15718 CK_NoOp, VK_LValue); 15719 } 15720 15721 if (!Result.isInvalid()) { 15722 Result = PerformCopyInitialization( 15723 InitializedEntity::InitializeBlock(Var->getLocation(), 15724 Cap.getCaptureType()), 15725 Loc, Result.get()); 15726 } 15727 15728 // Build a full-expression copy expression if initialization 15729 // succeeded and used a non-trivial constructor. Recover from 15730 // errors by pretending that the copy isn't necessary. 15731 if (!Result.isInvalid() && 15732 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15733 ->isTrivial()) { 15734 Result = MaybeCreateExprWithCleanups(Result); 15735 CopyExpr = Result.get(); 15736 } 15737 } 15738 } 15739 15740 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15741 CopyExpr); 15742 Captures.push_back(NewCap); 15743 } 15744 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15745 15746 // Pop the block scope now but keep it alive to the end of this function. 15747 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15748 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15749 15750 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15751 15752 // If the block isn't obviously global, i.e. it captures anything at 15753 // all, then we need to do a few things in the surrounding context: 15754 if (Result->getBlockDecl()->hasCaptures()) { 15755 // First, this expression has a new cleanup object. 15756 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15757 Cleanup.setExprNeedsCleanups(true); 15758 15759 // It also gets a branch-protected scope if any of the captured 15760 // variables needs destruction. 15761 for (const auto &CI : Result->getBlockDecl()->captures()) { 15762 const VarDecl *var = CI.getVariable(); 15763 if (var->getType().isDestructedType() != QualType::DK_none) { 15764 setFunctionHasBranchProtectedScope(); 15765 break; 15766 } 15767 } 15768 } 15769 15770 if (getCurFunction()) 15771 getCurFunction()->addBlock(BD); 15772 15773 return Result; 15774 } 15775 15776 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15777 SourceLocation RPLoc) { 15778 TypeSourceInfo *TInfo; 15779 GetTypeFromParser(Ty, &TInfo); 15780 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15781 } 15782 15783 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15784 Expr *E, TypeSourceInfo *TInfo, 15785 SourceLocation RPLoc) { 15786 Expr *OrigExpr = E; 15787 bool IsMS = false; 15788 15789 // CUDA device code does not support varargs. 15790 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15791 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15792 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15793 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15794 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15795 } 15796 } 15797 15798 // NVPTX does not support va_arg expression. 15799 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15800 Context.getTargetInfo().getTriple().isNVPTX()) 15801 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15802 15803 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15804 // as Microsoft ABI on an actual Microsoft platform, where 15805 // __builtin_ms_va_list and __builtin_va_list are the same.) 15806 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15807 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15808 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15809 if (Context.hasSameType(MSVaListType, E->getType())) { 15810 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15811 return ExprError(); 15812 IsMS = true; 15813 } 15814 } 15815 15816 // Get the va_list type 15817 QualType VaListType = Context.getBuiltinVaListType(); 15818 if (!IsMS) { 15819 if (VaListType->isArrayType()) { 15820 // Deal with implicit array decay; for example, on x86-64, 15821 // va_list is an array, but it's supposed to decay to 15822 // a pointer for va_arg. 15823 VaListType = Context.getArrayDecayedType(VaListType); 15824 // Make sure the input expression also decays appropriately. 15825 ExprResult Result = UsualUnaryConversions(E); 15826 if (Result.isInvalid()) 15827 return ExprError(); 15828 E = Result.get(); 15829 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15830 // If va_list is a record type and we are compiling in C++ mode, 15831 // check the argument using reference binding. 15832 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15833 Context, Context.getLValueReferenceType(VaListType), false); 15834 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15835 if (Init.isInvalid()) 15836 return ExprError(); 15837 E = Init.getAs<Expr>(); 15838 } else { 15839 // Otherwise, the va_list argument must be an l-value because 15840 // it is modified by va_arg. 15841 if (!E->isTypeDependent() && 15842 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15843 return ExprError(); 15844 } 15845 } 15846 15847 if (!IsMS && !E->isTypeDependent() && 15848 !Context.hasSameType(VaListType, E->getType())) 15849 return ExprError( 15850 Diag(E->getBeginLoc(), 15851 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15852 << OrigExpr->getType() << E->getSourceRange()); 15853 15854 if (!TInfo->getType()->isDependentType()) { 15855 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15856 diag::err_second_parameter_to_va_arg_incomplete, 15857 TInfo->getTypeLoc())) 15858 return ExprError(); 15859 15860 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15861 TInfo->getType(), 15862 diag::err_second_parameter_to_va_arg_abstract, 15863 TInfo->getTypeLoc())) 15864 return ExprError(); 15865 15866 if (!TInfo->getType().isPODType(Context)) { 15867 Diag(TInfo->getTypeLoc().getBeginLoc(), 15868 TInfo->getType()->isObjCLifetimeType() 15869 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15870 : diag::warn_second_parameter_to_va_arg_not_pod) 15871 << TInfo->getType() 15872 << TInfo->getTypeLoc().getSourceRange(); 15873 } 15874 15875 // Check for va_arg where arguments of the given type will be promoted 15876 // (i.e. this va_arg is guaranteed to have undefined behavior). 15877 QualType PromoteType; 15878 if (TInfo->getType()->isPromotableIntegerType()) { 15879 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15880 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 15881 // and C2x 7.16.1.1p2 says, in part: 15882 // If type is not compatible with the type of the actual next argument 15883 // (as promoted according to the default argument promotions), the 15884 // behavior is undefined, except for the following cases: 15885 // - both types are pointers to qualified or unqualified versions of 15886 // compatible types; 15887 // - one type is a signed integer type, the other type is the 15888 // corresponding unsigned integer type, and the value is 15889 // representable in both types; 15890 // - one type is pointer to qualified or unqualified void and the 15891 // other is a pointer to a qualified or unqualified character type. 15892 // Given that type compatibility is the primary requirement (ignoring 15893 // qualifications), you would think we could call typesAreCompatible() 15894 // directly to test this. However, in C++, that checks for *same type*, 15895 // which causes false positives when passing an enumeration type to 15896 // va_arg. Instead, get the underlying type of the enumeration and pass 15897 // that. 15898 QualType UnderlyingType = TInfo->getType(); 15899 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 15900 UnderlyingType = ET->getDecl()->getIntegerType(); 15901 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15902 /*CompareUnqualified*/ true)) 15903 PromoteType = QualType(); 15904 15905 // If the types are still not compatible, we need to test whether the 15906 // promoted type and the underlying type are the same except for 15907 // signedness. Ask the AST for the correctly corresponding type and see 15908 // if that's compatible. 15909 if (!PromoteType.isNull() && 15910 PromoteType->isUnsignedIntegerType() != 15911 UnderlyingType->isUnsignedIntegerType()) { 15912 UnderlyingType = 15913 UnderlyingType->isUnsignedIntegerType() 15914 ? Context.getCorrespondingSignedType(UnderlyingType) 15915 : Context.getCorrespondingUnsignedType(UnderlyingType); 15916 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15917 /*CompareUnqualified*/ true)) 15918 PromoteType = QualType(); 15919 } 15920 } 15921 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15922 PromoteType = Context.DoubleTy; 15923 if (!PromoteType.isNull()) 15924 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15925 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15926 << TInfo->getType() 15927 << PromoteType 15928 << TInfo->getTypeLoc().getSourceRange()); 15929 } 15930 15931 QualType T = TInfo->getType().getNonLValueExprType(Context); 15932 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15933 } 15934 15935 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15936 // The type of __null will be int or long, depending on the size of 15937 // pointers on the target. 15938 QualType Ty; 15939 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15940 if (pw == Context.getTargetInfo().getIntWidth()) 15941 Ty = Context.IntTy; 15942 else if (pw == Context.getTargetInfo().getLongWidth()) 15943 Ty = Context.LongTy; 15944 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15945 Ty = Context.LongLongTy; 15946 else { 15947 llvm_unreachable("I don't know size of pointer!"); 15948 } 15949 15950 return new (Context) GNUNullExpr(Ty, TokenLoc); 15951 } 15952 15953 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15954 SourceLocation BuiltinLoc, 15955 SourceLocation RPLoc) { 15956 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15957 } 15958 15959 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15960 SourceLocation BuiltinLoc, 15961 SourceLocation RPLoc, 15962 DeclContext *ParentContext) { 15963 return new (Context) 15964 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15965 } 15966 15967 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15968 bool Diagnose) { 15969 if (!getLangOpts().ObjC) 15970 return false; 15971 15972 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15973 if (!PT) 15974 return false; 15975 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15976 15977 // Ignore any parens, implicit casts (should only be 15978 // array-to-pointer decays), and not-so-opaque values. The last is 15979 // important for making this trigger for property assignments. 15980 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15981 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15982 if (OV->getSourceExpr()) 15983 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15984 15985 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15986 if (!PT->isObjCIdType() && 15987 !(ID && ID->getIdentifier()->isStr("NSString"))) 15988 return false; 15989 if (!SL->isAscii()) 15990 return false; 15991 15992 if (Diagnose) { 15993 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15994 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15995 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15996 } 15997 return true; 15998 } 15999 16000 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 16001 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 16002 isa<CXXBoolLiteralExpr>(SrcExpr)) && 16003 !SrcExpr->isNullPointerConstant( 16004 getASTContext(), Expr::NPC_NeverValueDependent)) { 16005 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 16006 return false; 16007 if (Diagnose) { 16008 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 16009 << /*number*/1 16010 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 16011 Expr *NumLit = 16012 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 16013 if (NumLit) 16014 Exp = NumLit; 16015 } 16016 return true; 16017 } 16018 16019 return false; 16020 } 16021 16022 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 16023 const Expr *SrcExpr) { 16024 if (!DstType->isFunctionPointerType() || 16025 !SrcExpr->getType()->isFunctionType()) 16026 return false; 16027 16028 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 16029 if (!DRE) 16030 return false; 16031 16032 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 16033 if (!FD) 16034 return false; 16035 16036 return !S.checkAddressOfFunctionIsAvailable(FD, 16037 /*Complain=*/true, 16038 SrcExpr->getBeginLoc()); 16039 } 16040 16041 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 16042 SourceLocation Loc, 16043 QualType DstType, QualType SrcType, 16044 Expr *SrcExpr, AssignmentAction Action, 16045 bool *Complained) { 16046 if (Complained) 16047 *Complained = false; 16048 16049 // Decode the result (notice that AST's are still created for extensions). 16050 bool CheckInferredResultType = false; 16051 bool isInvalid = false; 16052 unsigned DiagKind = 0; 16053 ConversionFixItGenerator ConvHints; 16054 bool MayHaveConvFixit = false; 16055 bool MayHaveFunctionDiff = false; 16056 const ObjCInterfaceDecl *IFace = nullptr; 16057 const ObjCProtocolDecl *PDecl = nullptr; 16058 16059 switch (ConvTy) { 16060 case Compatible: 16061 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 16062 return false; 16063 16064 case PointerToInt: 16065 if (getLangOpts().CPlusPlus) { 16066 DiagKind = diag::err_typecheck_convert_pointer_int; 16067 isInvalid = true; 16068 } else { 16069 DiagKind = diag::ext_typecheck_convert_pointer_int; 16070 } 16071 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16072 MayHaveConvFixit = true; 16073 break; 16074 case IntToPointer: 16075 if (getLangOpts().CPlusPlus) { 16076 DiagKind = diag::err_typecheck_convert_int_pointer; 16077 isInvalid = true; 16078 } else { 16079 DiagKind = diag::ext_typecheck_convert_int_pointer; 16080 } 16081 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16082 MayHaveConvFixit = true; 16083 break; 16084 case IncompatibleFunctionPointer: 16085 if (getLangOpts().CPlusPlus) { 16086 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 16087 isInvalid = true; 16088 } else { 16089 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 16090 } 16091 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16092 MayHaveConvFixit = true; 16093 break; 16094 case IncompatiblePointer: 16095 if (Action == AA_Passing_CFAudited) { 16096 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 16097 } else if (getLangOpts().CPlusPlus) { 16098 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 16099 isInvalid = true; 16100 } else { 16101 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 16102 } 16103 CheckInferredResultType = DstType->isObjCObjectPointerType() && 16104 SrcType->isObjCObjectPointerType(); 16105 if (!CheckInferredResultType) { 16106 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16107 } else if (CheckInferredResultType) { 16108 SrcType = SrcType.getUnqualifiedType(); 16109 DstType = DstType.getUnqualifiedType(); 16110 } 16111 MayHaveConvFixit = true; 16112 break; 16113 case IncompatiblePointerSign: 16114 if (getLangOpts().CPlusPlus) { 16115 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 16116 isInvalid = true; 16117 } else { 16118 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 16119 } 16120 break; 16121 case FunctionVoidPointer: 16122 if (getLangOpts().CPlusPlus) { 16123 DiagKind = diag::err_typecheck_convert_pointer_void_func; 16124 isInvalid = true; 16125 } else { 16126 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 16127 } 16128 break; 16129 case IncompatiblePointerDiscardsQualifiers: { 16130 // Perform array-to-pointer decay if necessary. 16131 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 16132 16133 isInvalid = true; 16134 16135 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 16136 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 16137 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 16138 DiagKind = diag::err_typecheck_incompatible_address_space; 16139 break; 16140 16141 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 16142 DiagKind = diag::err_typecheck_incompatible_ownership; 16143 break; 16144 } 16145 16146 llvm_unreachable("unknown error case for discarding qualifiers!"); 16147 // fallthrough 16148 } 16149 case CompatiblePointerDiscardsQualifiers: 16150 // If the qualifiers lost were because we were applying the 16151 // (deprecated) C++ conversion from a string literal to a char* 16152 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 16153 // Ideally, this check would be performed in 16154 // checkPointerTypesForAssignment. However, that would require a 16155 // bit of refactoring (so that the second argument is an 16156 // expression, rather than a type), which should be done as part 16157 // of a larger effort to fix checkPointerTypesForAssignment for 16158 // C++ semantics. 16159 if (getLangOpts().CPlusPlus && 16160 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 16161 return false; 16162 if (getLangOpts().CPlusPlus) { 16163 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 16164 isInvalid = true; 16165 } else { 16166 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 16167 } 16168 16169 break; 16170 case IncompatibleNestedPointerQualifiers: 16171 if (getLangOpts().CPlusPlus) { 16172 isInvalid = true; 16173 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 16174 } else { 16175 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16176 } 16177 break; 16178 case IncompatibleNestedPointerAddressSpaceMismatch: 16179 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16180 isInvalid = true; 16181 break; 16182 case IntToBlockPointer: 16183 DiagKind = diag::err_int_to_block_pointer; 16184 isInvalid = true; 16185 break; 16186 case IncompatibleBlockPointer: 16187 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16188 isInvalid = true; 16189 break; 16190 case IncompatibleObjCQualifiedId: { 16191 if (SrcType->isObjCQualifiedIdType()) { 16192 const ObjCObjectPointerType *srcOPT = 16193 SrcType->castAs<ObjCObjectPointerType>(); 16194 for (auto *srcProto : srcOPT->quals()) { 16195 PDecl = srcProto; 16196 break; 16197 } 16198 if (const ObjCInterfaceType *IFaceT = 16199 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16200 IFace = IFaceT->getDecl(); 16201 } 16202 else if (DstType->isObjCQualifiedIdType()) { 16203 const ObjCObjectPointerType *dstOPT = 16204 DstType->castAs<ObjCObjectPointerType>(); 16205 for (auto *dstProto : dstOPT->quals()) { 16206 PDecl = dstProto; 16207 break; 16208 } 16209 if (const ObjCInterfaceType *IFaceT = 16210 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16211 IFace = IFaceT->getDecl(); 16212 } 16213 if (getLangOpts().CPlusPlus) { 16214 DiagKind = diag::err_incompatible_qualified_id; 16215 isInvalid = true; 16216 } else { 16217 DiagKind = diag::warn_incompatible_qualified_id; 16218 } 16219 break; 16220 } 16221 case IncompatibleVectors: 16222 if (getLangOpts().CPlusPlus) { 16223 DiagKind = diag::err_incompatible_vectors; 16224 isInvalid = true; 16225 } else { 16226 DiagKind = diag::warn_incompatible_vectors; 16227 } 16228 break; 16229 case IncompatibleObjCWeakRef: 16230 DiagKind = diag::err_arc_weak_unavailable_assign; 16231 isInvalid = true; 16232 break; 16233 case Incompatible: 16234 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16235 if (Complained) 16236 *Complained = true; 16237 return true; 16238 } 16239 16240 DiagKind = diag::err_typecheck_convert_incompatible; 16241 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16242 MayHaveConvFixit = true; 16243 isInvalid = true; 16244 MayHaveFunctionDiff = true; 16245 break; 16246 } 16247 16248 QualType FirstType, SecondType; 16249 switch (Action) { 16250 case AA_Assigning: 16251 case AA_Initializing: 16252 // The destination type comes first. 16253 FirstType = DstType; 16254 SecondType = SrcType; 16255 break; 16256 16257 case AA_Returning: 16258 case AA_Passing: 16259 case AA_Passing_CFAudited: 16260 case AA_Converting: 16261 case AA_Sending: 16262 case AA_Casting: 16263 // The source type comes first. 16264 FirstType = SrcType; 16265 SecondType = DstType; 16266 break; 16267 } 16268 16269 PartialDiagnostic FDiag = PDiag(DiagKind); 16270 if (Action == AA_Passing_CFAudited) 16271 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16272 else 16273 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16274 16275 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16276 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16277 auto isPlainChar = [](const clang::Type *Type) { 16278 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16279 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16280 }; 16281 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16282 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16283 } 16284 16285 // If we can fix the conversion, suggest the FixIts. 16286 if (!ConvHints.isNull()) { 16287 for (FixItHint &H : ConvHints.Hints) 16288 FDiag << H; 16289 } 16290 16291 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16292 16293 if (MayHaveFunctionDiff) 16294 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16295 16296 Diag(Loc, FDiag); 16297 if ((DiagKind == diag::warn_incompatible_qualified_id || 16298 DiagKind == diag::err_incompatible_qualified_id) && 16299 PDecl && IFace && !IFace->hasDefinition()) 16300 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16301 << IFace << PDecl; 16302 16303 if (SecondType == Context.OverloadTy) 16304 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16305 FirstType, /*TakingAddress=*/true); 16306 16307 if (CheckInferredResultType) 16308 EmitRelatedResultTypeNote(SrcExpr); 16309 16310 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16311 EmitRelatedResultTypeNoteForReturn(DstType); 16312 16313 if (Complained) 16314 *Complained = true; 16315 return isInvalid; 16316 } 16317 16318 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16319 llvm::APSInt *Result, 16320 AllowFoldKind CanFold) { 16321 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16322 public: 16323 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16324 QualType T) override { 16325 return S.Diag(Loc, diag::err_ice_not_integral) 16326 << T << S.LangOpts.CPlusPlus; 16327 } 16328 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16329 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16330 } 16331 } Diagnoser; 16332 16333 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16334 } 16335 16336 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16337 llvm::APSInt *Result, 16338 unsigned DiagID, 16339 AllowFoldKind CanFold) { 16340 class IDDiagnoser : public VerifyICEDiagnoser { 16341 unsigned DiagID; 16342 16343 public: 16344 IDDiagnoser(unsigned DiagID) 16345 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16346 16347 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16348 return S.Diag(Loc, DiagID); 16349 } 16350 } Diagnoser(DiagID); 16351 16352 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16353 } 16354 16355 Sema::SemaDiagnosticBuilder 16356 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16357 QualType T) { 16358 return diagnoseNotICE(S, Loc); 16359 } 16360 16361 Sema::SemaDiagnosticBuilder 16362 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16363 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16364 } 16365 16366 ExprResult 16367 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16368 VerifyICEDiagnoser &Diagnoser, 16369 AllowFoldKind CanFold) { 16370 SourceLocation DiagLoc = E->getBeginLoc(); 16371 16372 if (getLangOpts().CPlusPlus11) { 16373 // C++11 [expr.const]p5: 16374 // If an expression of literal class type is used in a context where an 16375 // integral constant expression is required, then that class type shall 16376 // have a single non-explicit conversion function to an integral or 16377 // unscoped enumeration type 16378 ExprResult Converted; 16379 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16380 VerifyICEDiagnoser &BaseDiagnoser; 16381 public: 16382 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16383 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16384 BaseDiagnoser.Suppress, true), 16385 BaseDiagnoser(BaseDiagnoser) {} 16386 16387 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16388 QualType T) override { 16389 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16390 } 16391 16392 SemaDiagnosticBuilder diagnoseIncomplete( 16393 Sema &S, SourceLocation Loc, QualType T) override { 16394 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16395 } 16396 16397 SemaDiagnosticBuilder diagnoseExplicitConv( 16398 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16399 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16400 } 16401 16402 SemaDiagnosticBuilder noteExplicitConv( 16403 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16404 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16405 << ConvTy->isEnumeralType() << ConvTy; 16406 } 16407 16408 SemaDiagnosticBuilder diagnoseAmbiguous( 16409 Sema &S, SourceLocation Loc, QualType T) override { 16410 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16411 } 16412 16413 SemaDiagnosticBuilder noteAmbiguous( 16414 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16415 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16416 << ConvTy->isEnumeralType() << ConvTy; 16417 } 16418 16419 SemaDiagnosticBuilder diagnoseConversion( 16420 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16421 llvm_unreachable("conversion functions are permitted"); 16422 } 16423 } ConvertDiagnoser(Diagnoser); 16424 16425 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16426 ConvertDiagnoser); 16427 if (Converted.isInvalid()) 16428 return Converted; 16429 E = Converted.get(); 16430 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16431 return ExprError(); 16432 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16433 // An ICE must be of integral or unscoped enumeration type. 16434 if (!Diagnoser.Suppress) 16435 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16436 << E->getSourceRange(); 16437 return ExprError(); 16438 } 16439 16440 ExprResult RValueExpr = DefaultLvalueConversion(E); 16441 if (RValueExpr.isInvalid()) 16442 return ExprError(); 16443 16444 E = RValueExpr.get(); 16445 16446 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16447 // in the non-ICE case. 16448 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16449 if (Result) 16450 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16451 if (!isa<ConstantExpr>(E)) 16452 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16453 : ConstantExpr::Create(Context, E); 16454 return E; 16455 } 16456 16457 Expr::EvalResult EvalResult; 16458 SmallVector<PartialDiagnosticAt, 8> Notes; 16459 EvalResult.Diag = &Notes; 16460 16461 // Try to evaluate the expression, and produce diagnostics explaining why it's 16462 // not a constant expression as a side-effect. 16463 bool Folded = 16464 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16465 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16466 16467 if (!isa<ConstantExpr>(E)) 16468 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16469 16470 // In C++11, we can rely on diagnostics being produced for any expression 16471 // which is not a constant expression. If no diagnostics were produced, then 16472 // this is a constant expression. 16473 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16474 if (Result) 16475 *Result = EvalResult.Val.getInt(); 16476 return E; 16477 } 16478 16479 // If our only note is the usual "invalid subexpression" note, just point 16480 // the caret at its location rather than producing an essentially 16481 // redundant note. 16482 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16483 diag::note_invalid_subexpr_in_const_expr) { 16484 DiagLoc = Notes[0].first; 16485 Notes.clear(); 16486 } 16487 16488 if (!Folded || !CanFold) { 16489 if (!Diagnoser.Suppress) { 16490 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16491 for (const PartialDiagnosticAt &Note : Notes) 16492 Diag(Note.first, Note.second); 16493 } 16494 16495 return ExprError(); 16496 } 16497 16498 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16499 for (const PartialDiagnosticAt &Note : Notes) 16500 Diag(Note.first, Note.second); 16501 16502 if (Result) 16503 *Result = EvalResult.Val.getInt(); 16504 return E; 16505 } 16506 16507 namespace { 16508 // Handle the case where we conclude a expression which we speculatively 16509 // considered to be unevaluated is actually evaluated. 16510 class TransformToPE : public TreeTransform<TransformToPE> { 16511 typedef TreeTransform<TransformToPE> BaseTransform; 16512 16513 public: 16514 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16515 16516 // Make sure we redo semantic analysis 16517 bool AlwaysRebuild() { return true; } 16518 bool ReplacingOriginal() { return true; } 16519 16520 // We need to special-case DeclRefExprs referring to FieldDecls which 16521 // are not part of a member pointer formation; normal TreeTransforming 16522 // doesn't catch this case because of the way we represent them in the AST. 16523 // FIXME: This is a bit ugly; is it really the best way to handle this 16524 // case? 16525 // 16526 // Error on DeclRefExprs referring to FieldDecls. 16527 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16528 if (isa<FieldDecl>(E->getDecl()) && 16529 !SemaRef.isUnevaluatedContext()) 16530 return SemaRef.Diag(E->getLocation(), 16531 diag::err_invalid_non_static_member_use) 16532 << E->getDecl() << E->getSourceRange(); 16533 16534 return BaseTransform::TransformDeclRefExpr(E); 16535 } 16536 16537 // Exception: filter out member pointer formation 16538 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16539 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16540 return E; 16541 16542 return BaseTransform::TransformUnaryOperator(E); 16543 } 16544 16545 // The body of a lambda-expression is in a separate expression evaluation 16546 // context so never needs to be transformed. 16547 // FIXME: Ideally we wouldn't transform the closure type either, and would 16548 // just recreate the capture expressions and lambda expression. 16549 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16550 return SkipLambdaBody(E, Body); 16551 } 16552 }; 16553 } 16554 16555 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16556 assert(isUnevaluatedContext() && 16557 "Should only transform unevaluated expressions"); 16558 ExprEvalContexts.back().Context = 16559 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16560 if (isUnevaluatedContext()) 16561 return E; 16562 return TransformToPE(*this).TransformExpr(E); 16563 } 16564 16565 void 16566 Sema::PushExpressionEvaluationContext( 16567 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16568 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16569 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16570 LambdaContextDecl, ExprContext); 16571 Cleanup.reset(); 16572 if (!MaybeODRUseExprs.empty()) 16573 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16574 } 16575 16576 void 16577 Sema::PushExpressionEvaluationContext( 16578 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16579 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16580 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16581 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16582 } 16583 16584 namespace { 16585 16586 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16587 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16588 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16589 if (E->getOpcode() == UO_Deref) 16590 return CheckPossibleDeref(S, E->getSubExpr()); 16591 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16592 return CheckPossibleDeref(S, E->getBase()); 16593 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16594 return CheckPossibleDeref(S, E->getBase()); 16595 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16596 QualType Inner; 16597 QualType Ty = E->getType(); 16598 if (const auto *Ptr = Ty->getAs<PointerType>()) 16599 Inner = Ptr->getPointeeType(); 16600 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16601 Inner = Arr->getElementType(); 16602 else 16603 return nullptr; 16604 16605 if (Inner->hasAttr(attr::NoDeref)) 16606 return E; 16607 } 16608 return nullptr; 16609 } 16610 16611 } // namespace 16612 16613 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16614 for (const Expr *E : Rec.PossibleDerefs) { 16615 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16616 if (DeclRef) { 16617 const ValueDecl *Decl = DeclRef->getDecl(); 16618 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16619 << Decl->getName() << E->getSourceRange(); 16620 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16621 } else { 16622 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16623 << E->getSourceRange(); 16624 } 16625 } 16626 Rec.PossibleDerefs.clear(); 16627 } 16628 16629 /// Check whether E, which is either a discarded-value expression or an 16630 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16631 /// and if so, remove it from the list of volatile-qualified assignments that 16632 /// we are going to warn are deprecated. 16633 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16634 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16635 return; 16636 16637 // Note: ignoring parens here is not justified by the standard rules, but 16638 // ignoring parentheses seems like a more reasonable approach, and this only 16639 // drives a deprecation warning so doesn't affect conformance. 16640 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16641 if (BO->getOpcode() == BO_Assign) { 16642 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16643 llvm::erase_value(LHSs, BO->getLHS()); 16644 } 16645 } 16646 } 16647 16648 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16649 if (isUnevaluatedContext() || !E.isUsable() || !Decl || 16650 !Decl->isConsteval() || isConstantEvaluated() || 16651 RebuildingImmediateInvocation || isImmediateFunctionContext()) 16652 return E; 16653 16654 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16655 /// It's OK if this fails; we'll also remove this in 16656 /// HandleImmediateInvocations, but catching it here allows us to avoid 16657 /// walking the AST looking for it in simple cases. 16658 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16659 if (auto *DeclRef = 16660 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16661 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16662 16663 E = MaybeCreateExprWithCleanups(E); 16664 16665 ConstantExpr *Res = ConstantExpr::Create( 16666 getASTContext(), E.get(), 16667 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16668 getASTContext()), 16669 /*IsImmediateInvocation*/ true); 16670 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16671 return Res; 16672 } 16673 16674 static void EvaluateAndDiagnoseImmediateInvocation( 16675 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16676 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16677 Expr::EvalResult Eval; 16678 Eval.Diag = &Notes; 16679 ConstantExpr *CE = Candidate.getPointer(); 16680 bool Result = CE->EvaluateAsConstantExpr( 16681 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16682 if (!Result || !Notes.empty()) { 16683 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16684 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16685 InnerExpr = FunctionalCast->getSubExpr(); 16686 FunctionDecl *FD = nullptr; 16687 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16688 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16689 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16690 FD = Call->getConstructor(); 16691 else 16692 llvm_unreachable("unhandled decl kind"); 16693 assert(FD->isConsteval()); 16694 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16695 for (auto &Note : Notes) 16696 SemaRef.Diag(Note.first, Note.second); 16697 return; 16698 } 16699 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16700 } 16701 16702 static void RemoveNestedImmediateInvocation( 16703 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16704 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16705 struct ComplexRemove : TreeTransform<ComplexRemove> { 16706 using Base = TreeTransform<ComplexRemove>; 16707 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16708 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16709 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16710 CurrentII; 16711 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16712 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16713 SmallVector<Sema::ImmediateInvocationCandidate, 16714 4>::reverse_iterator Current) 16715 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16716 void RemoveImmediateInvocation(ConstantExpr* E) { 16717 auto It = std::find_if(CurrentII, IISet.rend(), 16718 [E](Sema::ImmediateInvocationCandidate Elem) { 16719 return Elem.getPointer() == E; 16720 }); 16721 assert(It != IISet.rend() && 16722 "ConstantExpr marked IsImmediateInvocation should " 16723 "be present"); 16724 It->setInt(1); // Mark as deleted 16725 } 16726 ExprResult TransformConstantExpr(ConstantExpr *E) { 16727 if (!E->isImmediateInvocation()) 16728 return Base::TransformConstantExpr(E); 16729 RemoveImmediateInvocation(E); 16730 return Base::TransformExpr(E->getSubExpr()); 16731 } 16732 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16733 /// we need to remove its DeclRefExpr from the DRSet. 16734 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16735 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16736 return Base::TransformCXXOperatorCallExpr(E); 16737 } 16738 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16739 /// here. 16740 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16741 if (!Init) 16742 return Init; 16743 /// ConstantExpr are the first layer of implicit node to be removed so if 16744 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16745 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16746 if (CE->isImmediateInvocation()) 16747 RemoveImmediateInvocation(CE); 16748 return Base::TransformInitializer(Init, NotCopyInit); 16749 } 16750 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16751 DRSet.erase(E); 16752 return E; 16753 } 16754 bool AlwaysRebuild() { return false; } 16755 bool ReplacingOriginal() { return true; } 16756 bool AllowSkippingCXXConstructExpr() { 16757 bool Res = AllowSkippingFirstCXXConstructExpr; 16758 AllowSkippingFirstCXXConstructExpr = true; 16759 return Res; 16760 } 16761 bool AllowSkippingFirstCXXConstructExpr = true; 16762 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16763 Rec.ImmediateInvocationCandidates, It); 16764 16765 /// CXXConstructExpr with a single argument are getting skipped by 16766 /// TreeTransform in some situtation because they could be implicit. This 16767 /// can only occur for the top-level CXXConstructExpr because it is used 16768 /// nowhere in the expression being transformed therefore will not be rebuilt. 16769 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16770 /// skipping the first CXXConstructExpr. 16771 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16772 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16773 16774 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16775 assert(Res.isUsable()); 16776 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16777 It->getPointer()->setSubExpr(Res.get()); 16778 } 16779 16780 static void 16781 HandleImmediateInvocations(Sema &SemaRef, 16782 Sema::ExpressionEvaluationContextRecord &Rec) { 16783 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16784 Rec.ReferenceToConsteval.size() == 0) || 16785 SemaRef.RebuildingImmediateInvocation) 16786 return; 16787 16788 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16789 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16790 /// need to remove ReferenceToConsteval in the immediate invocation. 16791 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16792 16793 /// Prevent sema calls during the tree transform from adding pointers that 16794 /// are already in the sets. 16795 llvm::SaveAndRestore<bool> DisableIITracking( 16796 SemaRef.RebuildingImmediateInvocation, true); 16797 16798 /// Prevent diagnostic during tree transfrom as they are duplicates 16799 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16800 16801 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16802 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16803 if (!It->getInt()) 16804 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16805 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16806 Rec.ReferenceToConsteval.size()) { 16807 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16808 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16809 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16810 bool VisitDeclRefExpr(DeclRefExpr *E) { 16811 DRSet.erase(E); 16812 return DRSet.size(); 16813 } 16814 } Visitor(Rec.ReferenceToConsteval); 16815 Visitor.TraverseStmt( 16816 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16817 } 16818 for (auto CE : Rec.ImmediateInvocationCandidates) 16819 if (!CE.getInt()) 16820 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16821 for (auto DR : Rec.ReferenceToConsteval) { 16822 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16823 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16824 << FD; 16825 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16826 } 16827 } 16828 16829 void Sema::PopExpressionEvaluationContext() { 16830 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16831 unsigned NumTypos = Rec.NumTypos; 16832 16833 if (!Rec.Lambdas.empty()) { 16834 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16835 if (!getLangOpts().CPlusPlus20 && 16836 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 16837 Rec.isUnevaluated() || 16838 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 16839 unsigned D; 16840 if (Rec.isUnevaluated()) { 16841 // C++11 [expr.prim.lambda]p2: 16842 // A lambda-expression shall not appear in an unevaluated operand 16843 // (Clause 5). 16844 D = diag::err_lambda_unevaluated_operand; 16845 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16846 // C++1y [expr.const]p2: 16847 // A conditional-expression e is a core constant expression unless the 16848 // evaluation of e, following the rules of the abstract machine, would 16849 // evaluate [...] a lambda-expression. 16850 D = diag::err_lambda_in_constant_expression; 16851 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16852 // C++17 [expr.prim.lamda]p2: 16853 // A lambda-expression shall not appear [...] in a template-argument. 16854 D = diag::err_lambda_in_invalid_context; 16855 } else 16856 llvm_unreachable("Couldn't infer lambda error message."); 16857 16858 for (const auto *L : Rec.Lambdas) 16859 Diag(L->getBeginLoc(), D); 16860 } 16861 } 16862 16863 WarnOnPendingNoDerefs(Rec); 16864 HandleImmediateInvocations(*this, Rec); 16865 16866 // Warn on any volatile-qualified simple-assignments that are not discarded- 16867 // value expressions nor unevaluated operands (those cases get removed from 16868 // this list by CheckUnusedVolatileAssignment). 16869 for (auto *BO : Rec.VolatileAssignmentLHSs) 16870 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16871 << BO->getType(); 16872 16873 // When are coming out of an unevaluated context, clear out any 16874 // temporaries that we may have created as part of the evaluation of 16875 // the expression in that context: they aren't relevant because they 16876 // will never be constructed. 16877 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16878 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16879 ExprCleanupObjects.end()); 16880 Cleanup = Rec.ParentCleanup; 16881 CleanupVarDeclMarking(); 16882 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16883 // Otherwise, merge the contexts together. 16884 } else { 16885 Cleanup.mergeFrom(Rec.ParentCleanup); 16886 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16887 Rec.SavedMaybeODRUseExprs.end()); 16888 } 16889 16890 // Pop the current expression evaluation context off the stack. 16891 ExprEvalContexts.pop_back(); 16892 16893 // The global expression evaluation context record is never popped. 16894 ExprEvalContexts.back().NumTypos += NumTypos; 16895 } 16896 16897 void Sema::DiscardCleanupsInEvaluationContext() { 16898 ExprCleanupObjects.erase( 16899 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16900 ExprCleanupObjects.end()); 16901 Cleanup.reset(); 16902 MaybeODRUseExprs.clear(); 16903 } 16904 16905 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16906 ExprResult Result = CheckPlaceholderExpr(E); 16907 if (Result.isInvalid()) 16908 return ExprError(); 16909 E = Result.get(); 16910 if (!E->getType()->isVariablyModifiedType()) 16911 return E; 16912 return TransformToPotentiallyEvaluated(E); 16913 } 16914 16915 /// Are we in a context that is potentially constant evaluated per C++20 16916 /// [expr.const]p12? 16917 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16918 /// C++2a [expr.const]p12: 16919 // An expression or conversion is potentially constant evaluated if it is 16920 switch (SemaRef.ExprEvalContexts.back().Context) { 16921 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16922 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 16923 16924 // -- a manifestly constant-evaluated expression, 16925 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16926 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16927 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16928 // -- a potentially-evaluated expression, 16929 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16930 // -- an immediate subexpression of a braced-init-list, 16931 16932 // -- [FIXME] an expression of the form & cast-expression that occurs 16933 // within a templated entity 16934 // -- a subexpression of one of the above that is not a subexpression of 16935 // a nested unevaluated operand. 16936 return true; 16937 16938 case Sema::ExpressionEvaluationContext::Unevaluated: 16939 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16940 // Expressions in this context are never evaluated. 16941 return false; 16942 } 16943 llvm_unreachable("Invalid context"); 16944 } 16945 16946 /// Return true if this function has a calling convention that requires mangling 16947 /// in the size of the parameter pack. 16948 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16949 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16950 // we don't need parameter type sizes. 16951 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16952 if (!TT.isOSWindows() || !TT.isX86()) 16953 return false; 16954 16955 // If this is C++ and this isn't an extern "C" function, parameters do not 16956 // need to be complete. In this case, C++ mangling will apply, which doesn't 16957 // use the size of the parameters. 16958 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16959 return false; 16960 16961 // Stdcall, fastcall, and vectorcall need this special treatment. 16962 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16963 switch (CC) { 16964 case CC_X86StdCall: 16965 case CC_X86FastCall: 16966 case CC_X86VectorCall: 16967 return true; 16968 default: 16969 break; 16970 } 16971 return false; 16972 } 16973 16974 /// Require that all of the parameter types of function be complete. Normally, 16975 /// parameter types are only required to be complete when a function is called 16976 /// or defined, but to mangle functions with certain calling conventions, the 16977 /// mangler needs to know the size of the parameter list. In this situation, 16978 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16979 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16980 /// result in a linker error. Clang doesn't implement this behavior, and instead 16981 /// attempts to error at compile time. 16982 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16983 SourceLocation Loc) { 16984 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16985 FunctionDecl *FD; 16986 ParmVarDecl *Param; 16987 16988 public: 16989 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16990 : FD(FD), Param(Param) {} 16991 16992 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16993 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16994 StringRef CCName; 16995 switch (CC) { 16996 case CC_X86StdCall: 16997 CCName = "stdcall"; 16998 break; 16999 case CC_X86FastCall: 17000 CCName = "fastcall"; 17001 break; 17002 case CC_X86VectorCall: 17003 CCName = "vectorcall"; 17004 break; 17005 default: 17006 llvm_unreachable("CC does not need mangling"); 17007 } 17008 17009 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 17010 << Param->getDeclName() << FD->getDeclName() << CCName; 17011 } 17012 }; 17013 17014 for (ParmVarDecl *Param : FD->parameters()) { 17015 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 17016 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 17017 } 17018 } 17019 17020 namespace { 17021 enum class OdrUseContext { 17022 /// Declarations in this context are not odr-used. 17023 None, 17024 /// Declarations in this context are formally odr-used, but this is a 17025 /// dependent context. 17026 Dependent, 17027 /// Declarations in this context are odr-used but not actually used (yet). 17028 FormallyOdrUsed, 17029 /// Declarations in this context are used. 17030 Used 17031 }; 17032 } 17033 17034 /// Are we within a context in which references to resolved functions or to 17035 /// variables result in odr-use? 17036 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 17037 OdrUseContext Result; 17038 17039 switch (SemaRef.ExprEvalContexts.back().Context) { 17040 case Sema::ExpressionEvaluationContext::Unevaluated: 17041 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17042 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17043 return OdrUseContext::None; 17044 17045 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17046 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 17047 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17048 Result = OdrUseContext::Used; 17049 break; 17050 17051 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17052 Result = OdrUseContext::FormallyOdrUsed; 17053 break; 17054 17055 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17056 // A default argument formally results in odr-use, but doesn't actually 17057 // result in a use in any real sense until it itself is used. 17058 Result = OdrUseContext::FormallyOdrUsed; 17059 break; 17060 } 17061 17062 if (SemaRef.CurContext->isDependentContext()) 17063 return OdrUseContext::Dependent; 17064 17065 return Result; 17066 } 17067 17068 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 17069 if (!Func->isConstexpr()) 17070 return false; 17071 17072 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 17073 return true; 17074 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 17075 return CCD && CCD->getInheritedConstructor(); 17076 } 17077 17078 /// Mark a function referenced, and check whether it is odr-used 17079 /// (C++ [basic.def.odr]p2, C99 6.9p3) 17080 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 17081 bool MightBeOdrUse) { 17082 assert(Func && "No function?"); 17083 17084 Func->setReferenced(); 17085 17086 // Recursive functions aren't really used until they're used from some other 17087 // context. 17088 bool IsRecursiveCall = CurContext == Func; 17089 17090 // C++11 [basic.def.odr]p3: 17091 // A function whose name appears as a potentially-evaluated expression is 17092 // odr-used if it is the unique lookup result or the selected member of a 17093 // set of overloaded functions [...]. 17094 // 17095 // We (incorrectly) mark overload resolution as an unevaluated context, so we 17096 // can just check that here. 17097 OdrUseContext OdrUse = 17098 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 17099 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 17100 OdrUse = OdrUseContext::FormallyOdrUsed; 17101 17102 // Trivial default constructors and destructors are never actually used. 17103 // FIXME: What about other special members? 17104 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 17105 OdrUse == OdrUseContext::Used) { 17106 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 17107 if (Constructor->isDefaultConstructor()) 17108 OdrUse = OdrUseContext::FormallyOdrUsed; 17109 if (isa<CXXDestructorDecl>(Func)) 17110 OdrUse = OdrUseContext::FormallyOdrUsed; 17111 } 17112 17113 // C++20 [expr.const]p12: 17114 // A function [...] is needed for constant evaluation if it is [...] a 17115 // constexpr function that is named by an expression that is potentially 17116 // constant evaluated 17117 bool NeededForConstantEvaluation = 17118 isPotentiallyConstantEvaluatedContext(*this) && 17119 isImplicitlyDefinableConstexprFunction(Func); 17120 17121 // Determine whether we require a function definition to exist, per 17122 // C++11 [temp.inst]p3: 17123 // Unless a function template specialization has been explicitly 17124 // instantiated or explicitly specialized, the function template 17125 // specialization is implicitly instantiated when the specialization is 17126 // referenced in a context that requires a function definition to exist. 17127 // C++20 [temp.inst]p7: 17128 // The existence of a definition of a [...] function is considered to 17129 // affect the semantics of the program if the [...] function is needed for 17130 // constant evaluation by an expression 17131 // C++20 [basic.def.odr]p10: 17132 // Every program shall contain exactly one definition of every non-inline 17133 // function or variable that is odr-used in that program outside of a 17134 // discarded statement 17135 // C++20 [special]p1: 17136 // The implementation will implicitly define [defaulted special members] 17137 // if they are odr-used or needed for constant evaluation. 17138 // 17139 // Note that we skip the implicit instantiation of templates that are only 17140 // used in unused default arguments or by recursive calls to themselves. 17141 // This is formally non-conforming, but seems reasonable in practice. 17142 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 17143 NeededForConstantEvaluation); 17144 17145 // C++14 [temp.expl.spec]p6: 17146 // If a template [...] is explicitly specialized then that specialization 17147 // shall be declared before the first use of that specialization that would 17148 // cause an implicit instantiation to take place, in every translation unit 17149 // in which such a use occurs 17150 if (NeedDefinition && 17151 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 17152 Func->getMemberSpecializationInfo())) 17153 checkSpecializationVisibility(Loc, Func); 17154 17155 if (getLangOpts().CUDA) 17156 CheckCUDACall(Loc, Func); 17157 17158 if (getLangOpts().SYCLIsDevice) 17159 checkSYCLDeviceFunction(Loc, Func); 17160 17161 // If we need a definition, try to create one. 17162 if (NeedDefinition && !Func->getBody()) { 17163 runWithSufficientStackSpace(Loc, [&] { 17164 if (CXXConstructorDecl *Constructor = 17165 dyn_cast<CXXConstructorDecl>(Func)) { 17166 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 17167 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 17168 if (Constructor->isDefaultConstructor()) { 17169 if (Constructor->isTrivial() && 17170 !Constructor->hasAttr<DLLExportAttr>()) 17171 return; 17172 DefineImplicitDefaultConstructor(Loc, Constructor); 17173 } else if (Constructor->isCopyConstructor()) { 17174 DefineImplicitCopyConstructor(Loc, Constructor); 17175 } else if (Constructor->isMoveConstructor()) { 17176 DefineImplicitMoveConstructor(Loc, Constructor); 17177 } 17178 } else if (Constructor->getInheritedConstructor()) { 17179 DefineInheritingConstructor(Loc, Constructor); 17180 } 17181 } else if (CXXDestructorDecl *Destructor = 17182 dyn_cast<CXXDestructorDecl>(Func)) { 17183 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17184 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17185 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17186 return; 17187 DefineImplicitDestructor(Loc, Destructor); 17188 } 17189 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17190 MarkVTableUsed(Loc, Destructor->getParent()); 17191 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17192 if (MethodDecl->isOverloadedOperator() && 17193 MethodDecl->getOverloadedOperator() == OO_Equal) { 17194 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17195 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17196 if (MethodDecl->isCopyAssignmentOperator()) 17197 DefineImplicitCopyAssignment(Loc, MethodDecl); 17198 else if (MethodDecl->isMoveAssignmentOperator()) 17199 DefineImplicitMoveAssignment(Loc, MethodDecl); 17200 } 17201 } else if (isa<CXXConversionDecl>(MethodDecl) && 17202 MethodDecl->getParent()->isLambda()) { 17203 CXXConversionDecl *Conversion = 17204 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17205 if (Conversion->isLambdaToBlockPointerConversion()) 17206 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17207 else 17208 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17209 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17210 MarkVTableUsed(Loc, MethodDecl->getParent()); 17211 } 17212 17213 if (Func->isDefaulted() && !Func->isDeleted()) { 17214 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17215 if (DCK != DefaultedComparisonKind::None) 17216 DefineDefaultedComparison(Loc, Func, DCK); 17217 } 17218 17219 // Implicit instantiation of function templates and member functions of 17220 // class templates. 17221 if (Func->isImplicitlyInstantiable()) { 17222 TemplateSpecializationKind TSK = 17223 Func->getTemplateSpecializationKindForInstantiation(); 17224 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17225 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17226 if (FirstInstantiation) { 17227 PointOfInstantiation = Loc; 17228 if (auto *MSI = Func->getMemberSpecializationInfo()) 17229 MSI->setPointOfInstantiation(Loc); 17230 // FIXME: Notify listener. 17231 else 17232 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17233 } else if (TSK != TSK_ImplicitInstantiation) { 17234 // Use the point of use as the point of instantiation, instead of the 17235 // point of explicit instantiation (which we track as the actual point 17236 // of instantiation). This gives better backtraces in diagnostics. 17237 PointOfInstantiation = Loc; 17238 } 17239 17240 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17241 Func->isConstexpr()) { 17242 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17243 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17244 CodeSynthesisContexts.size()) 17245 PendingLocalImplicitInstantiations.push_back( 17246 std::make_pair(Func, PointOfInstantiation)); 17247 else if (Func->isConstexpr()) 17248 // Do not defer instantiations of constexpr functions, to avoid the 17249 // expression evaluator needing to call back into Sema if it sees a 17250 // call to such a function. 17251 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17252 else { 17253 Func->setInstantiationIsPending(true); 17254 PendingInstantiations.push_back( 17255 std::make_pair(Func, PointOfInstantiation)); 17256 // Notify the consumer that a function was implicitly instantiated. 17257 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17258 } 17259 } 17260 } else { 17261 // Walk redefinitions, as some of them may be instantiable. 17262 for (auto i : Func->redecls()) { 17263 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17264 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17265 } 17266 } 17267 }); 17268 } 17269 17270 // C++14 [except.spec]p17: 17271 // An exception-specification is considered to be needed when: 17272 // - the function is odr-used or, if it appears in an unevaluated operand, 17273 // would be odr-used if the expression were potentially-evaluated; 17274 // 17275 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17276 // function is a pure virtual function we're calling, and in that case the 17277 // function was selected by overload resolution and we need to resolve its 17278 // exception specification for a different reason. 17279 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17280 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17281 ResolveExceptionSpec(Loc, FPT); 17282 17283 // If this is the first "real" use, act on that. 17284 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17285 // Keep track of used but undefined functions. 17286 if (!Func->isDefined()) { 17287 if (mightHaveNonExternalLinkage(Func)) 17288 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17289 else if (Func->getMostRecentDecl()->isInlined() && 17290 !LangOpts.GNUInline && 17291 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17292 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17293 else if (isExternalWithNoLinkageType(Func)) 17294 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17295 } 17296 17297 // Some x86 Windows calling conventions mangle the size of the parameter 17298 // pack into the name. Computing the size of the parameters requires the 17299 // parameter types to be complete. Check that now. 17300 if (funcHasParameterSizeMangling(*this, Func)) 17301 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17302 17303 // In the MS C++ ABI, the compiler emits destructor variants where they are 17304 // used. If the destructor is used here but defined elsewhere, mark the 17305 // virtual base destructors referenced. If those virtual base destructors 17306 // are inline, this will ensure they are defined when emitting the complete 17307 // destructor variant. This checking may be redundant if the destructor is 17308 // provided later in this TU. 17309 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17310 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17311 CXXRecordDecl *Parent = Dtor->getParent(); 17312 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17313 CheckCompleteDestructorVariant(Loc, Dtor); 17314 } 17315 } 17316 17317 Func->markUsed(Context); 17318 } 17319 } 17320 17321 /// Directly mark a variable odr-used. Given a choice, prefer to use 17322 /// MarkVariableReferenced since it does additional checks and then 17323 /// calls MarkVarDeclODRUsed. 17324 /// If the variable must be captured: 17325 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17326 /// - else capture it in the DeclContext that maps to the 17327 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17328 static void 17329 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17330 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17331 // Keep track of used but undefined variables. 17332 // FIXME: We shouldn't suppress this warning for static data members. 17333 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17334 (!Var->isExternallyVisible() || Var->isInline() || 17335 SemaRef.isExternalWithNoLinkageType(Var)) && 17336 !(Var->isStaticDataMember() && Var->hasInit())) { 17337 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17338 if (old.isInvalid()) 17339 old = Loc; 17340 } 17341 QualType CaptureType, DeclRefType; 17342 if (SemaRef.LangOpts.OpenMP) 17343 SemaRef.tryCaptureOpenMPLambdas(Var); 17344 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17345 /*EllipsisLoc*/ SourceLocation(), 17346 /*BuildAndDiagnose*/ true, 17347 CaptureType, DeclRefType, 17348 FunctionScopeIndexToStopAt); 17349 17350 if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) { 17351 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 17352 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 17353 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 17354 if (VarTarget == Sema::CVT_Host && 17355 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 17356 UserTarget == Sema::CFT_Global)) { 17357 // Diagnose ODR-use of host global variables in device functions. 17358 // Reference of device global variables in host functions is allowed 17359 // through shadow variables therefore it is not diagnosed. 17360 if (SemaRef.LangOpts.CUDAIsDevice) { 17361 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 17362 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 17363 SemaRef.targetDiag(Var->getLocation(), 17364 Var->getType().isConstQualified() 17365 ? diag::note_cuda_const_var_unpromoted 17366 : diag::note_cuda_host_var); 17367 } 17368 } else if (VarTarget == Sema::CVT_Device && 17369 (UserTarget == Sema::CFT_Host || 17370 UserTarget == Sema::CFT_HostDevice) && 17371 !Var->hasExternalStorage()) { 17372 // Record a CUDA/HIP device side variable if it is ODR-used 17373 // by host code. This is done conservatively, when the variable is 17374 // referenced in any of the following contexts: 17375 // - a non-function context 17376 // - a host function 17377 // - a host device function 17378 // This makes the ODR-use of the device side variable by host code to 17379 // be visible in the device compilation for the compiler to be able to 17380 // emit template variables instantiated by host code only and to 17381 // externalize the static device side variable ODR-used by host code. 17382 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 17383 } 17384 } 17385 17386 Var->markUsed(SemaRef.Context); 17387 } 17388 17389 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17390 SourceLocation Loc, 17391 unsigned CapturingScopeIndex) { 17392 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17393 } 17394 17395 static void 17396 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17397 ValueDecl *var, DeclContext *DC) { 17398 DeclContext *VarDC = var->getDeclContext(); 17399 17400 // If the parameter still belongs to the translation unit, then 17401 // we're actually just using one parameter in the declaration of 17402 // the next. 17403 if (isa<ParmVarDecl>(var) && 17404 isa<TranslationUnitDecl>(VarDC)) 17405 return; 17406 17407 // For C code, don't diagnose about capture if we're not actually in code 17408 // right now; it's impossible to write a non-constant expression outside of 17409 // function context, so we'll get other (more useful) diagnostics later. 17410 // 17411 // For C++, things get a bit more nasty... it would be nice to suppress this 17412 // diagnostic for certain cases like using a local variable in an array bound 17413 // for a member of a local class, but the correct predicate is not obvious. 17414 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17415 return; 17416 17417 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17418 unsigned ContextKind = 3; // unknown 17419 if (isa<CXXMethodDecl>(VarDC) && 17420 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17421 ContextKind = 2; 17422 } else if (isa<FunctionDecl>(VarDC)) { 17423 ContextKind = 0; 17424 } else if (isa<BlockDecl>(VarDC)) { 17425 ContextKind = 1; 17426 } 17427 17428 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17429 << var << ValueKind << ContextKind << VarDC; 17430 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17431 << var; 17432 17433 // FIXME: Add additional diagnostic info about class etc. which prevents 17434 // capture. 17435 } 17436 17437 17438 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17439 bool &SubCapturesAreNested, 17440 QualType &CaptureType, 17441 QualType &DeclRefType) { 17442 // Check whether we've already captured it. 17443 if (CSI->CaptureMap.count(Var)) { 17444 // If we found a capture, any subcaptures are nested. 17445 SubCapturesAreNested = true; 17446 17447 // Retrieve the capture type for this variable. 17448 CaptureType = CSI->getCapture(Var).getCaptureType(); 17449 17450 // Compute the type of an expression that refers to this variable. 17451 DeclRefType = CaptureType.getNonReferenceType(); 17452 17453 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17454 // are mutable in the sense that user can change their value - they are 17455 // private instances of the captured declarations. 17456 const Capture &Cap = CSI->getCapture(Var); 17457 if (Cap.isCopyCapture() && 17458 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17459 !(isa<CapturedRegionScopeInfo>(CSI) && 17460 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17461 DeclRefType.addConst(); 17462 return true; 17463 } 17464 return false; 17465 } 17466 17467 // Only block literals, captured statements, and lambda expressions can 17468 // capture; other scopes don't work. 17469 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17470 SourceLocation Loc, 17471 const bool Diagnose, Sema &S) { 17472 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17473 return getLambdaAwareParentOfDeclContext(DC); 17474 else if (Var->hasLocalStorage()) { 17475 if (Diagnose) 17476 diagnoseUncapturableValueReference(S, Loc, Var, DC); 17477 } 17478 return nullptr; 17479 } 17480 17481 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17482 // certain types of variables (unnamed, variably modified types etc.) 17483 // so check for eligibility. 17484 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17485 SourceLocation Loc, 17486 const bool Diagnose, Sema &S) { 17487 17488 bool IsBlock = isa<BlockScopeInfo>(CSI); 17489 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17490 17491 // Lambdas are not allowed to capture unnamed variables 17492 // (e.g. anonymous unions). 17493 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17494 // assuming that's the intent. 17495 if (IsLambda && !Var->getDeclName()) { 17496 if (Diagnose) { 17497 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17498 S.Diag(Var->getLocation(), diag::note_declared_at); 17499 } 17500 return false; 17501 } 17502 17503 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17504 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17505 if (Diagnose) { 17506 S.Diag(Loc, diag::err_ref_vm_type); 17507 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17508 } 17509 return false; 17510 } 17511 // Prohibit structs with flexible array members too. 17512 // We cannot capture what is in the tail end of the struct. 17513 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17514 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17515 if (Diagnose) { 17516 if (IsBlock) 17517 S.Diag(Loc, diag::err_ref_flexarray_type); 17518 else 17519 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17520 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17521 } 17522 return false; 17523 } 17524 } 17525 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17526 // Lambdas and captured statements are not allowed to capture __block 17527 // variables; they don't support the expected semantics. 17528 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17529 if (Diagnose) { 17530 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17531 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17532 } 17533 return false; 17534 } 17535 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17536 if (S.getLangOpts().OpenCL && IsBlock && 17537 Var->getType()->isBlockPointerType()) { 17538 if (Diagnose) 17539 S.Diag(Loc, diag::err_opencl_block_ref_block); 17540 return false; 17541 } 17542 17543 return true; 17544 } 17545 17546 // Returns true if the capture by block was successful. 17547 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17548 SourceLocation Loc, 17549 const bool BuildAndDiagnose, 17550 QualType &CaptureType, 17551 QualType &DeclRefType, 17552 const bool Nested, 17553 Sema &S, bool Invalid) { 17554 bool ByRef = false; 17555 17556 // Blocks are not allowed to capture arrays, excepting OpenCL. 17557 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17558 // (decayed to pointers). 17559 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17560 if (BuildAndDiagnose) { 17561 S.Diag(Loc, diag::err_ref_array_type); 17562 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17563 Invalid = true; 17564 } else { 17565 return false; 17566 } 17567 } 17568 17569 // Forbid the block-capture of autoreleasing variables. 17570 if (!Invalid && 17571 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17572 if (BuildAndDiagnose) { 17573 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17574 << /*block*/ 0; 17575 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17576 Invalid = true; 17577 } else { 17578 return false; 17579 } 17580 } 17581 17582 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17583 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17584 QualType PointeeTy = PT->getPointeeType(); 17585 17586 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17587 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17588 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17589 if (BuildAndDiagnose) { 17590 SourceLocation VarLoc = Var->getLocation(); 17591 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17592 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17593 } 17594 } 17595 } 17596 17597 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17598 if (HasBlocksAttr || CaptureType->isReferenceType() || 17599 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17600 // Block capture by reference does not change the capture or 17601 // declaration reference types. 17602 ByRef = true; 17603 } else { 17604 // Block capture by copy introduces 'const'. 17605 CaptureType = CaptureType.getNonReferenceType().withConst(); 17606 DeclRefType = CaptureType; 17607 } 17608 17609 // Actually capture the variable. 17610 if (BuildAndDiagnose) 17611 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17612 CaptureType, Invalid); 17613 17614 return !Invalid; 17615 } 17616 17617 17618 /// Capture the given variable in the captured region. 17619 static bool captureInCapturedRegion( 17620 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 17621 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 17622 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 17623 bool IsTopScope, Sema &S, bool Invalid) { 17624 // By default, capture variables by reference. 17625 bool ByRef = true; 17626 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17627 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17628 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17629 // Using an LValue reference type is consistent with Lambdas (see below). 17630 if (S.isOpenMPCapturedDecl(Var)) { 17631 bool HasConst = DeclRefType.isConstQualified(); 17632 DeclRefType = DeclRefType.getUnqualifiedType(); 17633 // Don't lose diagnostics about assignments to const. 17634 if (HasConst) 17635 DeclRefType.addConst(); 17636 } 17637 // Do not capture firstprivates in tasks. 17638 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17639 OMPC_unknown) 17640 return true; 17641 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17642 RSI->OpenMPCaptureLevel); 17643 } 17644 17645 if (ByRef) 17646 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17647 else 17648 CaptureType = DeclRefType; 17649 17650 // Actually capture the variable. 17651 if (BuildAndDiagnose) 17652 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17653 Loc, SourceLocation(), CaptureType, Invalid); 17654 17655 return !Invalid; 17656 } 17657 17658 /// Capture the given variable in the lambda. 17659 static bool captureInLambda(LambdaScopeInfo *LSI, 17660 VarDecl *Var, 17661 SourceLocation Loc, 17662 const bool BuildAndDiagnose, 17663 QualType &CaptureType, 17664 QualType &DeclRefType, 17665 const bool RefersToCapturedVariable, 17666 const Sema::TryCaptureKind Kind, 17667 SourceLocation EllipsisLoc, 17668 const bool IsTopScope, 17669 Sema &S, bool Invalid) { 17670 // Determine whether we are capturing by reference or by value. 17671 bool ByRef = false; 17672 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17673 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17674 } else { 17675 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17676 } 17677 17678 // Compute the type of the field that will capture this variable. 17679 if (ByRef) { 17680 // C++11 [expr.prim.lambda]p15: 17681 // An entity is captured by reference if it is implicitly or 17682 // explicitly captured but not captured by copy. It is 17683 // unspecified whether additional unnamed non-static data 17684 // members are declared in the closure type for entities 17685 // captured by reference. 17686 // 17687 // FIXME: It is not clear whether we want to build an lvalue reference 17688 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17689 // to do the former, while EDG does the latter. Core issue 1249 will 17690 // clarify, but for now we follow GCC because it's a more permissive and 17691 // easily defensible position. 17692 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17693 } else { 17694 // C++11 [expr.prim.lambda]p14: 17695 // For each entity captured by copy, an unnamed non-static 17696 // data member is declared in the closure type. The 17697 // declaration order of these members is unspecified. The type 17698 // of such a data member is the type of the corresponding 17699 // captured entity if the entity is not a reference to an 17700 // object, or the referenced type otherwise. [Note: If the 17701 // captured entity is a reference to a function, the 17702 // corresponding data member is also a reference to a 17703 // function. - end note ] 17704 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17705 if (!RefType->getPointeeType()->isFunctionType()) 17706 CaptureType = RefType->getPointeeType(); 17707 } 17708 17709 // Forbid the lambda copy-capture of autoreleasing variables. 17710 if (!Invalid && 17711 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17712 if (BuildAndDiagnose) { 17713 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17714 S.Diag(Var->getLocation(), diag::note_previous_decl) 17715 << Var->getDeclName(); 17716 Invalid = true; 17717 } else { 17718 return false; 17719 } 17720 } 17721 17722 // Make sure that by-copy captures are of a complete and non-abstract type. 17723 if (!Invalid && BuildAndDiagnose) { 17724 if (!CaptureType->isDependentType() && 17725 S.RequireCompleteSizedType( 17726 Loc, CaptureType, 17727 diag::err_capture_of_incomplete_or_sizeless_type, 17728 Var->getDeclName())) 17729 Invalid = true; 17730 else if (S.RequireNonAbstractType(Loc, CaptureType, 17731 diag::err_capture_of_abstract_type)) 17732 Invalid = true; 17733 } 17734 } 17735 17736 // Compute the type of a reference to this captured variable. 17737 if (ByRef) 17738 DeclRefType = CaptureType.getNonReferenceType(); 17739 else { 17740 // C++ [expr.prim.lambda]p5: 17741 // The closure type for a lambda-expression has a public inline 17742 // function call operator [...]. This function call operator is 17743 // declared const (9.3.1) if and only if the lambda-expression's 17744 // parameter-declaration-clause is not followed by mutable. 17745 DeclRefType = CaptureType.getNonReferenceType(); 17746 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17747 DeclRefType.addConst(); 17748 } 17749 17750 // Add the capture. 17751 if (BuildAndDiagnose) 17752 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17753 Loc, EllipsisLoc, CaptureType, Invalid); 17754 17755 return !Invalid; 17756 } 17757 17758 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 17759 // Offer a Copy fix even if the type is dependent. 17760 if (Var->getType()->isDependentType()) 17761 return true; 17762 QualType T = Var->getType().getNonReferenceType(); 17763 if (T.isTriviallyCopyableType(Context)) 17764 return true; 17765 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 17766 17767 if (!(RD = RD->getDefinition())) 17768 return false; 17769 if (RD->hasSimpleCopyConstructor()) 17770 return true; 17771 if (RD->hasUserDeclaredCopyConstructor()) 17772 for (CXXConstructorDecl *Ctor : RD->ctors()) 17773 if (Ctor->isCopyConstructor()) 17774 return !Ctor->isDeleted(); 17775 } 17776 return false; 17777 } 17778 17779 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 17780 /// default capture. Fixes may be omitted if they aren't allowed by the 17781 /// standard, for example we can't emit a default copy capture fix-it if we 17782 /// already explicitly copy capture capture another variable. 17783 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 17784 VarDecl *Var) { 17785 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 17786 // Don't offer Capture by copy of default capture by copy fixes if Var is 17787 // known not to be copy constructible. 17788 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 17789 17790 SmallString<32> FixBuffer; 17791 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 17792 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 17793 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 17794 if (ShouldOfferCopyFix) { 17795 // Offer fixes to insert an explicit capture for the variable. 17796 // [] -> [VarName] 17797 // [OtherCapture] -> [OtherCapture, VarName] 17798 FixBuffer.assign({Separator, Var->getName()}); 17799 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17800 << Var << /*value*/ 0 17801 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17802 } 17803 // As above but capture by reference. 17804 FixBuffer.assign({Separator, "&", Var->getName()}); 17805 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17806 << Var << /*reference*/ 1 17807 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17808 } 17809 17810 // Only try to offer default capture if there are no captures excluding this 17811 // and init captures. 17812 // [this]: OK. 17813 // [X = Y]: OK. 17814 // [&A, &B]: Don't offer. 17815 // [A, B]: Don't offer. 17816 if (llvm::any_of(LSI->Captures, [](Capture &C) { 17817 return !C.isThisCapture() && !C.isInitCapture(); 17818 })) 17819 return; 17820 17821 // The default capture specifiers, '=' or '&', must appear first in the 17822 // capture body. 17823 SourceLocation DefaultInsertLoc = 17824 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 17825 17826 if (ShouldOfferCopyFix) { 17827 bool CanDefaultCopyCapture = true; 17828 // [=, *this] OK since c++17 17829 // [=, this] OK since c++20 17830 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 17831 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 17832 ? LSI->getCXXThisCapture().isCopyCapture() 17833 : false; 17834 // We can't use default capture by copy if any captures already specified 17835 // capture by copy. 17836 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 17837 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 17838 })) { 17839 FixBuffer.assign({"=", Separator}); 17840 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17841 << /*value*/ 0 17842 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17843 } 17844 } 17845 17846 // We can't use default capture by reference if any captures already specified 17847 // capture by reference. 17848 if (llvm::none_of(LSI->Captures, [](Capture &C) { 17849 return !C.isInitCapture() && C.isReferenceCapture() && 17850 !C.isThisCapture(); 17851 })) { 17852 FixBuffer.assign({"&", Separator}); 17853 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17854 << /*reference*/ 1 17855 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17856 } 17857 } 17858 17859 bool Sema::tryCaptureVariable( 17860 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17861 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17862 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17863 // An init-capture is notionally from the context surrounding its 17864 // declaration, but its parent DC is the lambda class. 17865 DeclContext *VarDC = Var->getDeclContext(); 17866 if (Var->isInitCapture()) 17867 VarDC = VarDC->getParent(); 17868 17869 DeclContext *DC = CurContext; 17870 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17871 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17872 // We need to sync up the Declaration Context with the 17873 // FunctionScopeIndexToStopAt 17874 if (FunctionScopeIndexToStopAt) { 17875 unsigned FSIndex = FunctionScopes.size() - 1; 17876 while (FSIndex != MaxFunctionScopesIndex) { 17877 DC = getLambdaAwareParentOfDeclContext(DC); 17878 --FSIndex; 17879 } 17880 } 17881 17882 17883 // If the variable is declared in the current context, there is no need to 17884 // capture it. 17885 if (VarDC == DC) return true; 17886 17887 // Capture global variables if it is required to use private copy of this 17888 // variable. 17889 bool IsGlobal = !Var->hasLocalStorage(); 17890 if (IsGlobal && 17891 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17892 MaxFunctionScopesIndex))) 17893 return true; 17894 Var = Var->getCanonicalDecl(); 17895 17896 // Walk up the stack to determine whether we can capture the variable, 17897 // performing the "simple" checks that don't depend on type. We stop when 17898 // we've either hit the declared scope of the variable or find an existing 17899 // capture of that variable. We start from the innermost capturing-entity 17900 // (the DC) and ensure that all intervening capturing-entities 17901 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17902 // declcontext can either capture the variable or have already captured 17903 // the variable. 17904 CaptureType = Var->getType(); 17905 DeclRefType = CaptureType.getNonReferenceType(); 17906 bool Nested = false; 17907 bool Explicit = (Kind != TryCapture_Implicit); 17908 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17909 do { 17910 // Only block literals, captured statements, and lambda expressions can 17911 // capture; other scopes don't work. 17912 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17913 ExprLoc, 17914 BuildAndDiagnose, 17915 *this); 17916 // We need to check for the parent *first* because, if we *have* 17917 // private-captured a global variable, we need to recursively capture it in 17918 // intermediate blocks, lambdas, etc. 17919 if (!ParentDC) { 17920 if (IsGlobal) { 17921 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17922 break; 17923 } 17924 return true; 17925 } 17926 17927 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17928 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17929 17930 17931 // Check whether we've already captured it. 17932 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17933 DeclRefType)) { 17934 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17935 break; 17936 } 17937 // If we are instantiating a generic lambda call operator body, 17938 // we do not want to capture new variables. What was captured 17939 // during either a lambdas transformation or initial parsing 17940 // should be used. 17941 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17942 if (BuildAndDiagnose) { 17943 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17944 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17945 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17946 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17947 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17948 buildLambdaCaptureFixit(*this, LSI, Var); 17949 } else 17950 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17951 } 17952 return true; 17953 } 17954 17955 // Try to capture variable-length arrays types. 17956 if (Var->getType()->isVariablyModifiedType()) { 17957 // We're going to walk down into the type and look for VLA 17958 // expressions. 17959 QualType QTy = Var->getType(); 17960 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17961 QTy = PVD->getOriginalType(); 17962 captureVariablyModifiedType(Context, QTy, CSI); 17963 } 17964 17965 if (getLangOpts().OpenMP) { 17966 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17967 // OpenMP private variables should not be captured in outer scope, so 17968 // just break here. Similarly, global variables that are captured in a 17969 // target region should not be captured outside the scope of the region. 17970 if (RSI->CapRegionKind == CR_OpenMP) { 17971 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17972 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17973 // If the variable is private (i.e. not captured) and has variably 17974 // modified type, we still need to capture the type for correct 17975 // codegen in all regions, associated with the construct. Currently, 17976 // it is captured in the innermost captured region only. 17977 if (IsOpenMPPrivateDecl != OMPC_unknown && 17978 Var->getType()->isVariablyModifiedType()) { 17979 QualType QTy = Var->getType(); 17980 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17981 QTy = PVD->getOriginalType(); 17982 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17983 I < E; ++I) { 17984 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17985 FunctionScopes[FunctionScopesIndex - I]); 17986 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17987 "Wrong number of captured regions associated with the " 17988 "OpenMP construct."); 17989 captureVariablyModifiedType(Context, QTy, OuterRSI); 17990 } 17991 } 17992 bool IsTargetCap = 17993 IsOpenMPPrivateDecl != OMPC_private && 17994 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17995 RSI->OpenMPCaptureLevel); 17996 // Do not capture global if it is not privatized in outer regions. 17997 bool IsGlobalCap = 17998 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17999 RSI->OpenMPCaptureLevel); 18000 18001 // When we detect target captures we are looking from inside the 18002 // target region, therefore we need to propagate the capture from the 18003 // enclosing region. Therefore, the capture is not initially nested. 18004 if (IsTargetCap) 18005 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 18006 18007 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 18008 (IsGlobal && !IsGlobalCap)) { 18009 Nested = !IsTargetCap; 18010 bool HasConst = DeclRefType.isConstQualified(); 18011 DeclRefType = DeclRefType.getUnqualifiedType(); 18012 // Don't lose diagnostics about assignments to const. 18013 if (HasConst) 18014 DeclRefType.addConst(); 18015 CaptureType = Context.getLValueReferenceType(DeclRefType); 18016 break; 18017 } 18018 } 18019 } 18020 } 18021 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 18022 // No capture-default, and this is not an explicit capture 18023 // so cannot capture this variable. 18024 if (BuildAndDiagnose) { 18025 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18026 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18027 auto *LSI = cast<LambdaScopeInfo>(CSI); 18028 if (LSI->Lambda) { 18029 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18030 buildLambdaCaptureFixit(*this, LSI, Var); 18031 } 18032 // FIXME: If we error out because an outer lambda can not implicitly 18033 // capture a variable that an inner lambda explicitly captures, we 18034 // should have the inner lambda do the explicit capture - because 18035 // it makes for cleaner diagnostics later. This would purely be done 18036 // so that the diagnostic does not misleadingly claim that a variable 18037 // can not be captured by a lambda implicitly even though it is captured 18038 // explicitly. Suggestion: 18039 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 18040 // at the function head 18041 // - cache the StartingDeclContext - this must be a lambda 18042 // - captureInLambda in the innermost lambda the variable. 18043 } 18044 return true; 18045 } 18046 18047 FunctionScopesIndex--; 18048 DC = ParentDC; 18049 Explicit = false; 18050 } while (!VarDC->Equals(DC)); 18051 18052 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 18053 // computing the type of the capture at each step, checking type-specific 18054 // requirements, and adding captures if requested. 18055 // If the variable had already been captured previously, we start capturing 18056 // at the lambda nested within that one. 18057 bool Invalid = false; 18058 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 18059 ++I) { 18060 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 18061 18062 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18063 // certain types of variables (unnamed, variably modified types etc.) 18064 // so check for eligibility. 18065 if (!Invalid) 18066 Invalid = 18067 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 18068 18069 // After encountering an error, if we're actually supposed to capture, keep 18070 // capturing in nested contexts to suppress any follow-on diagnostics. 18071 if (Invalid && !BuildAndDiagnose) 18072 return true; 18073 18074 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 18075 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18076 DeclRefType, Nested, *this, Invalid); 18077 Nested = true; 18078 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18079 Invalid = !captureInCapturedRegion( 18080 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 18081 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 18082 Nested = true; 18083 } else { 18084 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18085 Invalid = 18086 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18087 DeclRefType, Nested, Kind, EllipsisLoc, 18088 /*IsTopScope*/ I == N - 1, *this, Invalid); 18089 Nested = true; 18090 } 18091 18092 if (Invalid && !BuildAndDiagnose) 18093 return true; 18094 } 18095 return Invalid; 18096 } 18097 18098 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 18099 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 18100 QualType CaptureType; 18101 QualType DeclRefType; 18102 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 18103 /*BuildAndDiagnose=*/true, CaptureType, 18104 DeclRefType, nullptr); 18105 } 18106 18107 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 18108 QualType CaptureType; 18109 QualType DeclRefType; 18110 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18111 /*BuildAndDiagnose=*/false, CaptureType, 18112 DeclRefType, nullptr); 18113 } 18114 18115 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 18116 QualType CaptureType; 18117 QualType DeclRefType; 18118 18119 // Determine whether we can capture this variable. 18120 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18121 /*BuildAndDiagnose=*/false, CaptureType, 18122 DeclRefType, nullptr)) 18123 return QualType(); 18124 18125 return DeclRefType; 18126 } 18127 18128 namespace { 18129 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 18130 // The produced TemplateArgumentListInfo* points to data stored within this 18131 // object, so should only be used in contexts where the pointer will not be 18132 // used after the CopiedTemplateArgs object is destroyed. 18133 class CopiedTemplateArgs { 18134 bool HasArgs; 18135 TemplateArgumentListInfo TemplateArgStorage; 18136 public: 18137 template<typename RefExpr> 18138 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 18139 if (HasArgs) 18140 E->copyTemplateArgumentsInto(TemplateArgStorage); 18141 } 18142 operator TemplateArgumentListInfo*() 18143 #ifdef __has_cpp_attribute 18144 #if __has_cpp_attribute(clang::lifetimebound) 18145 [[clang::lifetimebound]] 18146 #endif 18147 #endif 18148 { 18149 return HasArgs ? &TemplateArgStorage : nullptr; 18150 } 18151 }; 18152 } 18153 18154 /// Walk the set of potential results of an expression and mark them all as 18155 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 18156 /// 18157 /// \return A new expression if we found any potential results, ExprEmpty() if 18158 /// not, and ExprError() if we diagnosed an error. 18159 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 18160 NonOdrUseReason NOUR) { 18161 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 18162 // an object that satisfies the requirements for appearing in a 18163 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 18164 // is immediately applied." This function handles the lvalue-to-rvalue 18165 // conversion part. 18166 // 18167 // If we encounter a node that claims to be an odr-use but shouldn't be, we 18168 // transform it into the relevant kind of non-odr-use node and rebuild the 18169 // tree of nodes leading to it. 18170 // 18171 // This is a mini-TreeTransform that only transforms a restricted subset of 18172 // nodes (and only certain operands of them). 18173 18174 // Rebuild a subexpression. 18175 auto Rebuild = [&](Expr *Sub) { 18176 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 18177 }; 18178 18179 // Check whether a potential result satisfies the requirements of NOUR. 18180 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 18181 // Any entity other than a VarDecl is always odr-used whenever it's named 18182 // in a potentially-evaluated expression. 18183 auto *VD = dyn_cast<VarDecl>(D); 18184 if (!VD) 18185 return true; 18186 18187 // C++2a [basic.def.odr]p4: 18188 // A variable x whose name appears as a potentially-evalauted expression 18189 // e is odr-used by e unless 18190 // -- x is a reference that is usable in constant expressions, or 18191 // -- x is a variable of non-reference type that is usable in constant 18192 // expressions and has no mutable subobjects, and e is an element of 18193 // the set of potential results of an expression of 18194 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18195 // conversion is applied, or 18196 // -- x is a variable of non-reference type, and e is an element of the 18197 // set of potential results of a discarded-value expression to which 18198 // the lvalue-to-rvalue conversion is not applied 18199 // 18200 // We check the first bullet and the "potentially-evaluated" condition in 18201 // BuildDeclRefExpr. We check the type requirements in the second bullet 18202 // in CheckLValueToRValueConversionOperand below. 18203 switch (NOUR) { 18204 case NOUR_None: 18205 case NOUR_Unevaluated: 18206 llvm_unreachable("unexpected non-odr-use-reason"); 18207 18208 case NOUR_Constant: 18209 // Constant references were handled when they were built. 18210 if (VD->getType()->isReferenceType()) 18211 return true; 18212 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18213 if (RD->hasMutableFields()) 18214 return true; 18215 if (!VD->isUsableInConstantExpressions(S.Context)) 18216 return true; 18217 break; 18218 18219 case NOUR_Discarded: 18220 if (VD->getType()->isReferenceType()) 18221 return true; 18222 break; 18223 } 18224 return false; 18225 }; 18226 18227 // Mark that this expression does not constitute an odr-use. 18228 auto MarkNotOdrUsed = [&] { 18229 S.MaybeODRUseExprs.remove(E); 18230 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18231 LSI->markVariableExprAsNonODRUsed(E); 18232 }; 18233 18234 // C++2a [basic.def.odr]p2: 18235 // The set of potential results of an expression e is defined as follows: 18236 switch (E->getStmtClass()) { 18237 // -- If e is an id-expression, ... 18238 case Expr::DeclRefExprClass: { 18239 auto *DRE = cast<DeclRefExpr>(E); 18240 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18241 break; 18242 18243 // Rebuild as a non-odr-use DeclRefExpr. 18244 MarkNotOdrUsed(); 18245 return DeclRefExpr::Create( 18246 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18247 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18248 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18249 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18250 } 18251 18252 case Expr::FunctionParmPackExprClass: { 18253 auto *FPPE = cast<FunctionParmPackExpr>(E); 18254 // If any of the declarations in the pack is odr-used, then the expression 18255 // as a whole constitutes an odr-use. 18256 for (VarDecl *D : *FPPE) 18257 if (IsPotentialResultOdrUsed(D)) 18258 return ExprEmpty(); 18259 18260 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18261 // nothing cares about whether we marked this as an odr-use, but it might 18262 // be useful for non-compiler tools. 18263 MarkNotOdrUsed(); 18264 break; 18265 } 18266 18267 // -- If e is a subscripting operation with an array operand... 18268 case Expr::ArraySubscriptExprClass: { 18269 auto *ASE = cast<ArraySubscriptExpr>(E); 18270 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18271 if (!OldBase->getType()->isArrayType()) 18272 break; 18273 ExprResult Base = Rebuild(OldBase); 18274 if (!Base.isUsable()) 18275 return Base; 18276 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18277 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18278 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18279 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18280 ASE->getRBracketLoc()); 18281 } 18282 18283 case Expr::MemberExprClass: { 18284 auto *ME = cast<MemberExpr>(E); 18285 // -- If e is a class member access expression [...] naming a non-static 18286 // data member... 18287 if (isa<FieldDecl>(ME->getMemberDecl())) { 18288 ExprResult Base = Rebuild(ME->getBase()); 18289 if (!Base.isUsable()) 18290 return Base; 18291 return MemberExpr::Create( 18292 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18293 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18294 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18295 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18296 ME->getObjectKind(), ME->isNonOdrUse()); 18297 } 18298 18299 if (ME->getMemberDecl()->isCXXInstanceMember()) 18300 break; 18301 18302 // -- If e is a class member access expression naming a static data member, 18303 // ... 18304 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18305 break; 18306 18307 // Rebuild as a non-odr-use MemberExpr. 18308 MarkNotOdrUsed(); 18309 return MemberExpr::Create( 18310 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 18311 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 18312 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 18313 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 18314 } 18315 18316 case Expr::BinaryOperatorClass: { 18317 auto *BO = cast<BinaryOperator>(E); 18318 Expr *LHS = BO->getLHS(); 18319 Expr *RHS = BO->getRHS(); 18320 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18321 if (BO->getOpcode() == BO_PtrMemD) { 18322 ExprResult Sub = Rebuild(LHS); 18323 if (!Sub.isUsable()) 18324 return Sub; 18325 LHS = Sub.get(); 18326 // -- If e is a comma expression, ... 18327 } else if (BO->getOpcode() == BO_Comma) { 18328 ExprResult Sub = Rebuild(RHS); 18329 if (!Sub.isUsable()) 18330 return Sub; 18331 RHS = Sub.get(); 18332 } else { 18333 break; 18334 } 18335 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18336 LHS, RHS); 18337 } 18338 18339 // -- If e has the form (e1)... 18340 case Expr::ParenExprClass: { 18341 auto *PE = cast<ParenExpr>(E); 18342 ExprResult Sub = Rebuild(PE->getSubExpr()); 18343 if (!Sub.isUsable()) 18344 return Sub; 18345 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18346 } 18347 18348 // -- If e is a glvalue conditional expression, ... 18349 // We don't apply this to a binary conditional operator. FIXME: Should we? 18350 case Expr::ConditionalOperatorClass: { 18351 auto *CO = cast<ConditionalOperator>(E); 18352 ExprResult LHS = Rebuild(CO->getLHS()); 18353 if (LHS.isInvalid()) 18354 return ExprError(); 18355 ExprResult RHS = Rebuild(CO->getRHS()); 18356 if (RHS.isInvalid()) 18357 return ExprError(); 18358 if (!LHS.isUsable() && !RHS.isUsable()) 18359 return ExprEmpty(); 18360 if (!LHS.isUsable()) 18361 LHS = CO->getLHS(); 18362 if (!RHS.isUsable()) 18363 RHS = CO->getRHS(); 18364 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18365 CO->getCond(), LHS.get(), RHS.get()); 18366 } 18367 18368 // [Clang extension] 18369 // -- If e has the form __extension__ e1... 18370 case Expr::UnaryOperatorClass: { 18371 auto *UO = cast<UnaryOperator>(E); 18372 if (UO->getOpcode() != UO_Extension) 18373 break; 18374 ExprResult Sub = Rebuild(UO->getSubExpr()); 18375 if (!Sub.isUsable()) 18376 return Sub; 18377 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18378 Sub.get()); 18379 } 18380 18381 // [Clang extension] 18382 // -- If e has the form _Generic(...), the set of potential results is the 18383 // union of the sets of potential results of the associated expressions. 18384 case Expr::GenericSelectionExprClass: { 18385 auto *GSE = cast<GenericSelectionExpr>(E); 18386 18387 SmallVector<Expr *, 4> AssocExprs; 18388 bool AnyChanged = false; 18389 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18390 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18391 if (AssocExpr.isInvalid()) 18392 return ExprError(); 18393 if (AssocExpr.isUsable()) { 18394 AssocExprs.push_back(AssocExpr.get()); 18395 AnyChanged = true; 18396 } else { 18397 AssocExprs.push_back(OrigAssocExpr); 18398 } 18399 } 18400 18401 return AnyChanged ? S.CreateGenericSelectionExpr( 18402 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18403 GSE->getRParenLoc(), GSE->getControllingExpr(), 18404 GSE->getAssocTypeSourceInfos(), AssocExprs) 18405 : ExprEmpty(); 18406 } 18407 18408 // [Clang extension] 18409 // -- If e has the form __builtin_choose_expr(...), the set of potential 18410 // results is the union of the sets of potential results of the 18411 // second and third subexpressions. 18412 case Expr::ChooseExprClass: { 18413 auto *CE = cast<ChooseExpr>(E); 18414 18415 ExprResult LHS = Rebuild(CE->getLHS()); 18416 if (LHS.isInvalid()) 18417 return ExprError(); 18418 18419 ExprResult RHS = Rebuild(CE->getLHS()); 18420 if (RHS.isInvalid()) 18421 return ExprError(); 18422 18423 if (!LHS.get() && !RHS.get()) 18424 return ExprEmpty(); 18425 if (!LHS.isUsable()) 18426 LHS = CE->getLHS(); 18427 if (!RHS.isUsable()) 18428 RHS = CE->getRHS(); 18429 18430 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18431 RHS.get(), CE->getRParenLoc()); 18432 } 18433 18434 // Step through non-syntactic nodes. 18435 case Expr::ConstantExprClass: { 18436 auto *CE = cast<ConstantExpr>(E); 18437 ExprResult Sub = Rebuild(CE->getSubExpr()); 18438 if (!Sub.isUsable()) 18439 return Sub; 18440 return ConstantExpr::Create(S.Context, Sub.get()); 18441 } 18442 18443 // We could mostly rely on the recursive rebuilding to rebuild implicit 18444 // casts, but not at the top level, so rebuild them here. 18445 case Expr::ImplicitCastExprClass: { 18446 auto *ICE = cast<ImplicitCastExpr>(E); 18447 // Only step through the narrow set of cast kinds we expect to encounter. 18448 // Anything else suggests we've left the region in which potential results 18449 // can be found. 18450 switch (ICE->getCastKind()) { 18451 case CK_NoOp: 18452 case CK_DerivedToBase: 18453 case CK_UncheckedDerivedToBase: { 18454 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18455 if (!Sub.isUsable()) 18456 return Sub; 18457 CXXCastPath Path(ICE->path()); 18458 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18459 ICE->getValueKind(), &Path); 18460 } 18461 18462 default: 18463 break; 18464 } 18465 break; 18466 } 18467 18468 default: 18469 break; 18470 } 18471 18472 // Can't traverse through this node. Nothing to do. 18473 return ExprEmpty(); 18474 } 18475 18476 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18477 // Check whether the operand is or contains an object of non-trivial C union 18478 // type. 18479 if (E->getType().isVolatileQualified() && 18480 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18481 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18482 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18483 Sema::NTCUC_LValueToRValueVolatile, 18484 NTCUK_Destruct|NTCUK_Copy); 18485 18486 // C++2a [basic.def.odr]p4: 18487 // [...] an expression of non-volatile-qualified non-class type to which 18488 // the lvalue-to-rvalue conversion is applied [...] 18489 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18490 return E; 18491 18492 ExprResult Result = 18493 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18494 if (Result.isInvalid()) 18495 return ExprError(); 18496 return Result.get() ? Result : E; 18497 } 18498 18499 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18500 Res = CorrectDelayedTyposInExpr(Res); 18501 18502 if (!Res.isUsable()) 18503 return Res; 18504 18505 // If a constant-expression is a reference to a variable where we delay 18506 // deciding whether it is an odr-use, just assume we will apply the 18507 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18508 // (a non-type template argument), we have special handling anyway. 18509 return CheckLValueToRValueConversionOperand(Res.get()); 18510 } 18511 18512 void Sema::CleanupVarDeclMarking() { 18513 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18514 // call. 18515 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18516 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18517 18518 for (Expr *E : LocalMaybeODRUseExprs) { 18519 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18520 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18521 DRE->getLocation(), *this); 18522 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18523 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18524 *this); 18525 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18526 for (VarDecl *VD : *FP) 18527 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18528 } else { 18529 llvm_unreachable("Unexpected expression"); 18530 } 18531 } 18532 18533 assert(MaybeODRUseExprs.empty() && 18534 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18535 } 18536 18537 static void DoMarkVarDeclReferenced( 18538 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 18539 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18540 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18541 isa<FunctionParmPackExpr>(E)) && 18542 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18543 Var->setReferenced(); 18544 18545 if (Var->isInvalidDecl()) 18546 return; 18547 18548 auto *MSI = Var->getMemberSpecializationInfo(); 18549 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18550 : Var->getTemplateSpecializationKind(); 18551 18552 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18553 bool UsableInConstantExpr = 18554 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18555 18556 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 18557 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 18558 } 18559 18560 // C++20 [expr.const]p12: 18561 // A variable [...] is needed for constant evaluation if it is [...] a 18562 // variable whose name appears as a potentially constant evaluated 18563 // expression that is either a contexpr variable or is of non-volatile 18564 // const-qualified integral type or of reference type 18565 bool NeededForConstantEvaluation = 18566 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18567 18568 bool NeedDefinition = 18569 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18570 18571 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18572 "Can't instantiate a partial template specialization."); 18573 18574 // If this might be a member specialization of a static data member, check 18575 // the specialization is visible. We already did the checks for variable 18576 // template specializations when we created them. 18577 if (NeedDefinition && TSK != TSK_Undeclared && 18578 !isa<VarTemplateSpecializationDecl>(Var)) 18579 SemaRef.checkSpecializationVisibility(Loc, Var); 18580 18581 // Perform implicit instantiation of static data members, static data member 18582 // templates of class templates, and variable template specializations. Delay 18583 // instantiations of variable templates, except for those that could be used 18584 // in a constant expression. 18585 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18586 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18587 // instantiation declaration if a variable is usable in a constant 18588 // expression (among other cases). 18589 bool TryInstantiating = 18590 TSK == TSK_ImplicitInstantiation || 18591 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18592 18593 if (TryInstantiating) { 18594 SourceLocation PointOfInstantiation = 18595 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18596 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18597 if (FirstInstantiation) { 18598 PointOfInstantiation = Loc; 18599 if (MSI) 18600 MSI->setPointOfInstantiation(PointOfInstantiation); 18601 // FIXME: Notify listener. 18602 else 18603 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18604 } 18605 18606 if (UsableInConstantExpr) { 18607 // Do not defer instantiations of variables that could be used in a 18608 // constant expression. 18609 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18610 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18611 }); 18612 18613 // Re-set the member to trigger a recomputation of the dependence bits 18614 // for the expression. 18615 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18616 DRE->setDecl(DRE->getDecl()); 18617 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18618 ME->setMemberDecl(ME->getMemberDecl()); 18619 } else if (FirstInstantiation || 18620 isa<VarTemplateSpecializationDecl>(Var)) { 18621 // FIXME: For a specialization of a variable template, we don't 18622 // distinguish between "declaration and type implicitly instantiated" 18623 // and "implicit instantiation of definition requested", so we have 18624 // no direct way to avoid enqueueing the pending instantiation 18625 // multiple times. 18626 SemaRef.PendingInstantiations 18627 .push_back(std::make_pair(Var, PointOfInstantiation)); 18628 } 18629 } 18630 } 18631 18632 // C++2a [basic.def.odr]p4: 18633 // A variable x whose name appears as a potentially-evaluated expression e 18634 // is odr-used by e unless 18635 // -- x is a reference that is usable in constant expressions 18636 // -- x is a variable of non-reference type that is usable in constant 18637 // expressions and has no mutable subobjects [FIXME], and e is an 18638 // element of the set of potential results of an expression of 18639 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18640 // conversion is applied 18641 // -- x is a variable of non-reference type, and e is an element of the set 18642 // of potential results of a discarded-value expression to which the 18643 // lvalue-to-rvalue conversion is not applied [FIXME] 18644 // 18645 // We check the first part of the second bullet here, and 18646 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18647 // FIXME: To get the third bullet right, we need to delay this even for 18648 // variables that are not usable in constant expressions. 18649 18650 // If we already know this isn't an odr-use, there's nothing more to do. 18651 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18652 if (DRE->isNonOdrUse()) 18653 return; 18654 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18655 if (ME->isNonOdrUse()) 18656 return; 18657 18658 switch (OdrUse) { 18659 case OdrUseContext::None: 18660 assert((!E || isa<FunctionParmPackExpr>(E)) && 18661 "missing non-odr-use marking for unevaluated decl ref"); 18662 break; 18663 18664 case OdrUseContext::FormallyOdrUsed: 18665 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18666 // behavior. 18667 break; 18668 18669 case OdrUseContext::Used: 18670 // If we might later find that this expression isn't actually an odr-use, 18671 // delay the marking. 18672 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18673 SemaRef.MaybeODRUseExprs.insert(E); 18674 else 18675 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18676 break; 18677 18678 case OdrUseContext::Dependent: 18679 // If this is a dependent context, we don't need to mark variables as 18680 // odr-used, but we may still need to track them for lambda capture. 18681 // FIXME: Do we also need to do this inside dependent typeid expressions 18682 // (which are modeled as unevaluated at this point)? 18683 const bool RefersToEnclosingScope = 18684 (SemaRef.CurContext != Var->getDeclContext() && 18685 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18686 if (RefersToEnclosingScope) { 18687 LambdaScopeInfo *const LSI = 18688 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18689 if (LSI && (!LSI->CallOperator || 18690 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18691 // If a variable could potentially be odr-used, defer marking it so 18692 // until we finish analyzing the full expression for any 18693 // lvalue-to-rvalue 18694 // or discarded value conversions that would obviate odr-use. 18695 // Add it to the list of potential captures that will be analyzed 18696 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18697 // unless the variable is a reference that was initialized by a constant 18698 // expression (this will never need to be captured or odr-used). 18699 // 18700 // FIXME: We can simplify this a lot after implementing P0588R1. 18701 assert(E && "Capture variable should be used in an expression."); 18702 if (!Var->getType()->isReferenceType() || 18703 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18704 LSI->addPotentialCapture(E->IgnoreParens()); 18705 } 18706 } 18707 break; 18708 } 18709 } 18710 18711 /// Mark a variable referenced, and check whether it is odr-used 18712 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18713 /// used directly for normal expressions referring to VarDecl. 18714 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18715 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 18716 } 18717 18718 static void 18719 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 18720 bool MightBeOdrUse, 18721 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18722 if (SemaRef.isInOpenMPDeclareTargetContext()) 18723 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18724 18725 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18726 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 18727 return; 18728 } 18729 18730 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18731 18732 // If this is a call to a method via a cast, also mark the method in the 18733 // derived class used in case codegen can devirtualize the call. 18734 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18735 if (!ME) 18736 return; 18737 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18738 if (!MD) 18739 return; 18740 // Only attempt to devirtualize if this is truly a virtual call. 18741 bool IsVirtualCall = MD->isVirtual() && 18742 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18743 if (!IsVirtualCall) 18744 return; 18745 18746 // If it's possible to devirtualize the call, mark the called function 18747 // referenced. 18748 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18749 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18750 if (DM) 18751 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18752 } 18753 18754 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18755 /// 18756 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18757 /// handled with care if the DeclRefExpr is not newly-created. 18758 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18759 // TODO: update this with DR# once a defect report is filed. 18760 // C++11 defect. The address of a pure member should not be an ODR use, even 18761 // if it's a qualified reference. 18762 bool OdrUse = true; 18763 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18764 if (Method->isVirtual() && 18765 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18766 OdrUse = false; 18767 18768 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18769 if (!isUnevaluatedContext() && !isConstantEvaluated() && 18770 FD->isConsteval() && !RebuildingImmediateInvocation) 18771 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18772 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 18773 RefsMinusAssignments); 18774 } 18775 18776 /// Perform reference-marking and odr-use handling for a MemberExpr. 18777 void Sema::MarkMemberReferenced(MemberExpr *E) { 18778 // C++11 [basic.def.odr]p2: 18779 // A non-overloaded function whose name appears as a potentially-evaluated 18780 // expression or a member of a set of candidate functions, if selected by 18781 // overload resolution when referred to from a potentially-evaluated 18782 // expression, is odr-used, unless it is a pure virtual function and its 18783 // name is not explicitly qualified. 18784 bool MightBeOdrUse = true; 18785 if (E->performsVirtualDispatch(getLangOpts())) { 18786 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18787 if (Method->isPure()) 18788 MightBeOdrUse = false; 18789 } 18790 SourceLocation Loc = 18791 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18792 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 18793 RefsMinusAssignments); 18794 } 18795 18796 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18797 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18798 for (VarDecl *VD : *E) 18799 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 18800 RefsMinusAssignments); 18801 } 18802 18803 /// Perform marking for a reference to an arbitrary declaration. It 18804 /// marks the declaration referenced, and performs odr-use checking for 18805 /// functions and variables. This method should not be used when building a 18806 /// normal expression which refers to a variable. 18807 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18808 bool MightBeOdrUse) { 18809 if (MightBeOdrUse) { 18810 if (auto *VD = dyn_cast<VarDecl>(D)) { 18811 MarkVariableReferenced(Loc, VD); 18812 return; 18813 } 18814 } 18815 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18816 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18817 return; 18818 } 18819 D->setReferenced(); 18820 } 18821 18822 namespace { 18823 // Mark all of the declarations used by a type as referenced. 18824 // FIXME: Not fully implemented yet! We need to have a better understanding 18825 // of when we're entering a context we should not recurse into. 18826 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18827 // TreeTransforms rebuilding the type in a new context. Rather than 18828 // duplicating the TreeTransform logic, we should consider reusing it here. 18829 // Currently that causes problems when rebuilding LambdaExprs. 18830 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18831 Sema &S; 18832 SourceLocation Loc; 18833 18834 public: 18835 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18836 18837 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18838 18839 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18840 }; 18841 } 18842 18843 bool MarkReferencedDecls::TraverseTemplateArgument( 18844 const TemplateArgument &Arg) { 18845 { 18846 // A non-type template argument is a constant-evaluated context. 18847 EnterExpressionEvaluationContext Evaluated( 18848 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18849 if (Arg.getKind() == TemplateArgument::Declaration) { 18850 if (Decl *D = Arg.getAsDecl()) 18851 S.MarkAnyDeclReferenced(Loc, D, true); 18852 } else if (Arg.getKind() == TemplateArgument::Expression) { 18853 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18854 } 18855 } 18856 18857 return Inherited::TraverseTemplateArgument(Arg); 18858 } 18859 18860 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18861 MarkReferencedDecls Marker(*this, Loc); 18862 Marker.TraverseType(T); 18863 } 18864 18865 namespace { 18866 /// Helper class that marks all of the declarations referenced by 18867 /// potentially-evaluated subexpressions as "referenced". 18868 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18869 public: 18870 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18871 bool SkipLocalVariables; 18872 18873 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18874 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18875 18876 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18877 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18878 } 18879 18880 void VisitDeclRefExpr(DeclRefExpr *E) { 18881 // If we were asked not to visit local variables, don't. 18882 if (SkipLocalVariables) { 18883 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18884 if (VD->hasLocalStorage()) 18885 return; 18886 } 18887 18888 // FIXME: This can trigger the instantiation of the initializer of a 18889 // variable, which can cause the expression to become value-dependent 18890 // or error-dependent. Do we need to propagate the new dependence bits? 18891 S.MarkDeclRefReferenced(E); 18892 } 18893 18894 void VisitMemberExpr(MemberExpr *E) { 18895 S.MarkMemberReferenced(E); 18896 Visit(E->getBase()); 18897 } 18898 }; 18899 } // namespace 18900 18901 /// Mark any declarations that appear within this expression or any 18902 /// potentially-evaluated subexpressions as "referenced". 18903 /// 18904 /// \param SkipLocalVariables If true, don't mark local variables as 18905 /// 'referenced'. 18906 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18907 bool SkipLocalVariables) { 18908 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18909 } 18910 18911 /// Emit a diagnostic when statements are reachable. 18912 /// FIXME: check for reachability even in expressions for which we don't build a 18913 /// CFG (eg, in the initializer of a global or in a constant expression). 18914 /// For example, 18915 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; } 18916 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, 18917 const PartialDiagnostic &PD) { 18918 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18919 if (!FunctionScopes.empty()) 18920 FunctionScopes.back()->PossiblyUnreachableDiags.push_back( 18921 sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18922 return true; 18923 } 18924 18925 // The initializer of a constexpr variable or of the first declaration of a 18926 // static data member is not syntactically a constant evaluated constant, 18927 // but nonetheless is always required to be a constant expression, so we 18928 // can skip diagnosing. 18929 // FIXME: Using the mangling context here is a hack. 18930 if (auto *VD = dyn_cast_or_null<VarDecl>( 18931 ExprEvalContexts.back().ManglingContextDecl)) { 18932 if (VD->isConstexpr() || 18933 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18934 return false; 18935 // FIXME: For any other kind of variable, we should build a CFG for its 18936 // initializer and check whether the context in question is reachable. 18937 } 18938 18939 Diag(Loc, PD); 18940 return true; 18941 } 18942 18943 /// Emit a diagnostic that describes an effect on the run-time behavior 18944 /// of the program being compiled. 18945 /// 18946 /// This routine emits the given diagnostic when the code currently being 18947 /// type-checked is "potentially evaluated", meaning that there is a 18948 /// possibility that the code will actually be executable. Code in sizeof() 18949 /// expressions, code used only during overload resolution, etc., are not 18950 /// potentially evaluated. This routine will suppress such diagnostics or, 18951 /// in the absolutely nutty case of potentially potentially evaluated 18952 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18953 /// later. 18954 /// 18955 /// This routine should be used for all diagnostics that describe the run-time 18956 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18957 /// Failure to do so will likely result in spurious diagnostics or failures 18958 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18959 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18960 const PartialDiagnostic &PD) { 18961 switch (ExprEvalContexts.back().Context) { 18962 case ExpressionEvaluationContext::Unevaluated: 18963 case ExpressionEvaluationContext::UnevaluatedList: 18964 case ExpressionEvaluationContext::UnevaluatedAbstract: 18965 case ExpressionEvaluationContext::DiscardedStatement: 18966 // The argument will never be evaluated, so don't complain. 18967 break; 18968 18969 case ExpressionEvaluationContext::ConstantEvaluated: 18970 case ExpressionEvaluationContext::ImmediateFunctionContext: 18971 // Relevant diagnostics should be produced by constant evaluation. 18972 break; 18973 18974 case ExpressionEvaluationContext::PotentiallyEvaluated: 18975 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18976 return DiagIfReachable(Loc, Stmts, PD); 18977 } 18978 18979 return false; 18980 } 18981 18982 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18983 const PartialDiagnostic &PD) { 18984 return DiagRuntimeBehavior( 18985 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18986 } 18987 18988 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18989 CallExpr *CE, FunctionDecl *FD) { 18990 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18991 return false; 18992 18993 // If we're inside a decltype's expression, don't check for a valid return 18994 // type or construct temporaries until we know whether this is the last call. 18995 if (ExprEvalContexts.back().ExprContext == 18996 ExpressionEvaluationContextRecord::EK_Decltype) { 18997 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18998 return false; 18999 } 19000 19001 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 19002 FunctionDecl *FD; 19003 CallExpr *CE; 19004 19005 public: 19006 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 19007 : FD(FD), CE(CE) { } 19008 19009 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 19010 if (!FD) { 19011 S.Diag(Loc, diag::err_call_incomplete_return) 19012 << T << CE->getSourceRange(); 19013 return; 19014 } 19015 19016 S.Diag(Loc, diag::err_call_function_incomplete_return) 19017 << CE->getSourceRange() << FD << T; 19018 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 19019 << FD->getDeclName(); 19020 } 19021 } Diagnoser(FD, CE); 19022 19023 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 19024 return true; 19025 19026 return false; 19027 } 19028 19029 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 19030 // will prevent this condition from triggering, which is what we want. 19031 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 19032 SourceLocation Loc; 19033 19034 unsigned diagnostic = diag::warn_condition_is_assignment; 19035 bool IsOrAssign = false; 19036 19037 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 19038 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 19039 return; 19040 19041 IsOrAssign = Op->getOpcode() == BO_OrAssign; 19042 19043 // Greylist some idioms by putting them into a warning subcategory. 19044 if (ObjCMessageExpr *ME 19045 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 19046 Selector Sel = ME->getSelector(); 19047 19048 // self = [<foo> init...] 19049 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 19050 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19051 19052 // <foo> = [<bar> nextObject] 19053 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 19054 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19055 } 19056 19057 Loc = Op->getOperatorLoc(); 19058 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 19059 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 19060 return; 19061 19062 IsOrAssign = Op->getOperator() == OO_PipeEqual; 19063 Loc = Op->getOperatorLoc(); 19064 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 19065 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 19066 else { 19067 // Not an assignment. 19068 return; 19069 } 19070 19071 Diag(Loc, diagnostic) << E->getSourceRange(); 19072 19073 SourceLocation Open = E->getBeginLoc(); 19074 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 19075 Diag(Loc, diag::note_condition_assign_silence) 19076 << FixItHint::CreateInsertion(Open, "(") 19077 << FixItHint::CreateInsertion(Close, ")"); 19078 19079 if (IsOrAssign) 19080 Diag(Loc, diag::note_condition_or_assign_to_comparison) 19081 << FixItHint::CreateReplacement(Loc, "!="); 19082 else 19083 Diag(Loc, diag::note_condition_assign_to_comparison) 19084 << FixItHint::CreateReplacement(Loc, "=="); 19085 } 19086 19087 /// Redundant parentheses over an equality comparison can indicate 19088 /// that the user intended an assignment used as condition. 19089 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 19090 // Don't warn if the parens came from a macro. 19091 SourceLocation parenLoc = ParenE->getBeginLoc(); 19092 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 19093 return; 19094 // Don't warn for dependent expressions. 19095 if (ParenE->isTypeDependent()) 19096 return; 19097 19098 Expr *E = ParenE->IgnoreParens(); 19099 19100 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 19101 if (opE->getOpcode() == BO_EQ && 19102 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 19103 == Expr::MLV_Valid) { 19104 SourceLocation Loc = opE->getOperatorLoc(); 19105 19106 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 19107 SourceRange ParenERange = ParenE->getSourceRange(); 19108 Diag(Loc, diag::note_equality_comparison_silence) 19109 << FixItHint::CreateRemoval(ParenERange.getBegin()) 19110 << FixItHint::CreateRemoval(ParenERange.getEnd()); 19111 Diag(Loc, diag::note_equality_comparison_to_assign) 19112 << FixItHint::CreateReplacement(Loc, "="); 19113 } 19114 } 19115 19116 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 19117 bool IsConstexpr) { 19118 DiagnoseAssignmentAsCondition(E); 19119 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 19120 DiagnoseEqualityWithExtraParens(parenE); 19121 19122 ExprResult result = CheckPlaceholderExpr(E); 19123 if (result.isInvalid()) return ExprError(); 19124 E = result.get(); 19125 19126 if (!E->isTypeDependent()) { 19127 if (getLangOpts().CPlusPlus) 19128 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 19129 19130 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 19131 if (ERes.isInvalid()) 19132 return ExprError(); 19133 E = ERes.get(); 19134 19135 QualType T = E->getType(); 19136 if (!T->isScalarType()) { // C99 6.8.4.1p1 19137 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 19138 << T << E->getSourceRange(); 19139 return ExprError(); 19140 } 19141 CheckBoolLikeConversion(E, Loc); 19142 } 19143 19144 return E; 19145 } 19146 19147 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 19148 Expr *SubExpr, ConditionKind CK) { 19149 // Empty conditions are valid in for-statements. 19150 if (!SubExpr) 19151 return ConditionResult(); 19152 19153 ExprResult Cond; 19154 switch (CK) { 19155 case ConditionKind::Boolean: 19156 Cond = CheckBooleanCondition(Loc, SubExpr); 19157 break; 19158 19159 case ConditionKind::ConstexprIf: 19160 Cond = CheckBooleanCondition(Loc, SubExpr, true); 19161 break; 19162 19163 case ConditionKind::Switch: 19164 Cond = CheckSwitchCondition(Loc, SubExpr); 19165 break; 19166 } 19167 if (Cond.isInvalid()) { 19168 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 19169 {SubExpr}); 19170 if (!Cond.get()) 19171 return ConditionError(); 19172 } 19173 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 19174 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 19175 if (!FullExpr.get()) 19176 return ConditionError(); 19177 19178 return ConditionResult(*this, nullptr, FullExpr, 19179 CK == ConditionKind::ConstexprIf); 19180 } 19181 19182 namespace { 19183 /// A visitor for rebuilding a call to an __unknown_any expression 19184 /// to have an appropriate type. 19185 struct RebuildUnknownAnyFunction 19186 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 19187 19188 Sema &S; 19189 19190 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 19191 19192 ExprResult VisitStmt(Stmt *S) { 19193 llvm_unreachable("unexpected statement!"); 19194 } 19195 19196 ExprResult VisitExpr(Expr *E) { 19197 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 19198 << E->getSourceRange(); 19199 return ExprError(); 19200 } 19201 19202 /// Rebuild an expression which simply semantically wraps another 19203 /// expression which it shares the type and value kind of. 19204 template <class T> ExprResult rebuildSugarExpr(T *E) { 19205 ExprResult SubResult = Visit(E->getSubExpr()); 19206 if (SubResult.isInvalid()) return ExprError(); 19207 19208 Expr *SubExpr = SubResult.get(); 19209 E->setSubExpr(SubExpr); 19210 E->setType(SubExpr->getType()); 19211 E->setValueKind(SubExpr->getValueKind()); 19212 assert(E->getObjectKind() == OK_Ordinary); 19213 return E; 19214 } 19215 19216 ExprResult VisitParenExpr(ParenExpr *E) { 19217 return rebuildSugarExpr(E); 19218 } 19219 19220 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19221 return rebuildSugarExpr(E); 19222 } 19223 19224 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19225 ExprResult SubResult = Visit(E->getSubExpr()); 19226 if (SubResult.isInvalid()) return ExprError(); 19227 19228 Expr *SubExpr = SubResult.get(); 19229 E->setSubExpr(SubExpr); 19230 E->setType(S.Context.getPointerType(SubExpr->getType())); 19231 assert(E->isPRValue()); 19232 assert(E->getObjectKind() == OK_Ordinary); 19233 return E; 19234 } 19235 19236 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19237 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19238 19239 E->setType(VD->getType()); 19240 19241 assert(E->isPRValue()); 19242 if (S.getLangOpts().CPlusPlus && 19243 !(isa<CXXMethodDecl>(VD) && 19244 cast<CXXMethodDecl>(VD)->isInstance())) 19245 E->setValueKind(VK_LValue); 19246 19247 return E; 19248 } 19249 19250 ExprResult VisitMemberExpr(MemberExpr *E) { 19251 return resolveDecl(E, E->getMemberDecl()); 19252 } 19253 19254 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19255 return resolveDecl(E, E->getDecl()); 19256 } 19257 }; 19258 } 19259 19260 /// Given a function expression of unknown-any type, try to rebuild it 19261 /// to have a function type. 19262 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19263 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19264 if (Result.isInvalid()) return ExprError(); 19265 return S.DefaultFunctionArrayConversion(Result.get()); 19266 } 19267 19268 namespace { 19269 /// A visitor for rebuilding an expression of type __unknown_anytype 19270 /// into one which resolves the type directly on the referring 19271 /// expression. Strict preservation of the original source 19272 /// structure is not a goal. 19273 struct RebuildUnknownAnyExpr 19274 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19275 19276 Sema &S; 19277 19278 /// The current destination type. 19279 QualType DestType; 19280 19281 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19282 : S(S), DestType(CastType) {} 19283 19284 ExprResult VisitStmt(Stmt *S) { 19285 llvm_unreachable("unexpected statement!"); 19286 } 19287 19288 ExprResult VisitExpr(Expr *E) { 19289 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19290 << E->getSourceRange(); 19291 return ExprError(); 19292 } 19293 19294 ExprResult VisitCallExpr(CallExpr *E); 19295 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 19296 19297 /// Rebuild an expression which simply semantically wraps another 19298 /// expression which it shares the type and value kind of. 19299 template <class T> ExprResult rebuildSugarExpr(T *E) { 19300 ExprResult SubResult = Visit(E->getSubExpr()); 19301 if (SubResult.isInvalid()) return ExprError(); 19302 Expr *SubExpr = SubResult.get(); 19303 E->setSubExpr(SubExpr); 19304 E->setType(SubExpr->getType()); 19305 E->setValueKind(SubExpr->getValueKind()); 19306 assert(E->getObjectKind() == OK_Ordinary); 19307 return E; 19308 } 19309 19310 ExprResult VisitParenExpr(ParenExpr *E) { 19311 return rebuildSugarExpr(E); 19312 } 19313 19314 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19315 return rebuildSugarExpr(E); 19316 } 19317 19318 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19319 const PointerType *Ptr = DestType->getAs<PointerType>(); 19320 if (!Ptr) { 19321 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19322 << E->getSourceRange(); 19323 return ExprError(); 19324 } 19325 19326 if (isa<CallExpr>(E->getSubExpr())) { 19327 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19328 << E->getSourceRange(); 19329 return ExprError(); 19330 } 19331 19332 assert(E->isPRValue()); 19333 assert(E->getObjectKind() == OK_Ordinary); 19334 E->setType(DestType); 19335 19336 // Build the sub-expression as if it were an object of the pointee type. 19337 DestType = Ptr->getPointeeType(); 19338 ExprResult SubResult = Visit(E->getSubExpr()); 19339 if (SubResult.isInvalid()) return ExprError(); 19340 E->setSubExpr(SubResult.get()); 19341 return E; 19342 } 19343 19344 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19345 19346 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19347 19348 ExprResult VisitMemberExpr(MemberExpr *E) { 19349 return resolveDecl(E, E->getMemberDecl()); 19350 } 19351 19352 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19353 return resolveDecl(E, E->getDecl()); 19354 } 19355 }; 19356 } 19357 19358 /// Rebuilds a call expression which yielded __unknown_anytype. 19359 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19360 Expr *CalleeExpr = E->getCallee(); 19361 19362 enum FnKind { 19363 FK_MemberFunction, 19364 FK_FunctionPointer, 19365 FK_BlockPointer 19366 }; 19367 19368 FnKind Kind; 19369 QualType CalleeType = CalleeExpr->getType(); 19370 if (CalleeType == S.Context.BoundMemberTy) { 19371 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19372 Kind = FK_MemberFunction; 19373 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19374 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19375 CalleeType = Ptr->getPointeeType(); 19376 Kind = FK_FunctionPointer; 19377 } else { 19378 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19379 Kind = FK_BlockPointer; 19380 } 19381 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19382 19383 // Verify that this is a legal result type of a function. 19384 if (DestType->isArrayType() || DestType->isFunctionType()) { 19385 unsigned diagID = diag::err_func_returning_array_function; 19386 if (Kind == FK_BlockPointer) 19387 diagID = diag::err_block_returning_array_function; 19388 19389 S.Diag(E->getExprLoc(), diagID) 19390 << DestType->isFunctionType() << DestType; 19391 return ExprError(); 19392 } 19393 19394 // Otherwise, go ahead and set DestType as the call's result. 19395 E->setType(DestType.getNonLValueExprType(S.Context)); 19396 E->setValueKind(Expr::getValueKindForType(DestType)); 19397 assert(E->getObjectKind() == OK_Ordinary); 19398 19399 // Rebuild the function type, replacing the result type with DestType. 19400 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19401 if (Proto) { 19402 // __unknown_anytype(...) is a special case used by the debugger when 19403 // it has no idea what a function's signature is. 19404 // 19405 // We want to build this call essentially under the K&R 19406 // unprototyped rules, but making a FunctionNoProtoType in C++ 19407 // would foul up all sorts of assumptions. However, we cannot 19408 // simply pass all arguments as variadic arguments, nor can we 19409 // portably just call the function under a non-variadic type; see 19410 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19411 // However, it turns out that in practice it is generally safe to 19412 // call a function declared as "A foo(B,C,D);" under the prototype 19413 // "A foo(B,C,D,...);". The only known exception is with the 19414 // Windows ABI, where any variadic function is implicitly cdecl 19415 // regardless of its normal CC. Therefore we change the parameter 19416 // types to match the types of the arguments. 19417 // 19418 // This is a hack, but it is far superior to moving the 19419 // corresponding target-specific code from IR-gen to Sema/AST. 19420 19421 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19422 SmallVector<QualType, 8> ArgTypes; 19423 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19424 ArgTypes.reserve(E->getNumArgs()); 19425 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19426 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); 19427 } 19428 ParamTypes = ArgTypes; 19429 } 19430 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19431 Proto->getExtProtoInfo()); 19432 } else { 19433 DestType = S.Context.getFunctionNoProtoType(DestType, 19434 FnType->getExtInfo()); 19435 } 19436 19437 // Rebuild the appropriate pointer-to-function type. 19438 switch (Kind) { 19439 case FK_MemberFunction: 19440 // Nothing to do. 19441 break; 19442 19443 case FK_FunctionPointer: 19444 DestType = S.Context.getPointerType(DestType); 19445 break; 19446 19447 case FK_BlockPointer: 19448 DestType = S.Context.getBlockPointerType(DestType); 19449 break; 19450 } 19451 19452 // Finally, we can recurse. 19453 ExprResult CalleeResult = Visit(CalleeExpr); 19454 if (!CalleeResult.isUsable()) return ExprError(); 19455 E->setCallee(CalleeResult.get()); 19456 19457 // Bind a temporary if necessary. 19458 return S.MaybeBindToTemporary(E); 19459 } 19460 19461 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19462 // Verify that this is a legal result type of a call. 19463 if (DestType->isArrayType() || DestType->isFunctionType()) { 19464 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19465 << DestType->isFunctionType() << DestType; 19466 return ExprError(); 19467 } 19468 19469 // Rewrite the method result type if available. 19470 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19471 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19472 Method->setReturnType(DestType); 19473 } 19474 19475 // Change the type of the message. 19476 E->setType(DestType.getNonReferenceType()); 19477 E->setValueKind(Expr::getValueKindForType(DestType)); 19478 19479 return S.MaybeBindToTemporary(E); 19480 } 19481 19482 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19483 // The only case we should ever see here is a function-to-pointer decay. 19484 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19485 assert(E->isPRValue()); 19486 assert(E->getObjectKind() == OK_Ordinary); 19487 19488 E->setType(DestType); 19489 19490 // Rebuild the sub-expression as the pointee (function) type. 19491 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19492 19493 ExprResult Result = Visit(E->getSubExpr()); 19494 if (!Result.isUsable()) return ExprError(); 19495 19496 E->setSubExpr(Result.get()); 19497 return E; 19498 } else if (E->getCastKind() == CK_LValueToRValue) { 19499 assert(E->isPRValue()); 19500 assert(E->getObjectKind() == OK_Ordinary); 19501 19502 assert(isa<BlockPointerType>(E->getType())); 19503 19504 E->setType(DestType); 19505 19506 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19507 DestType = S.Context.getLValueReferenceType(DestType); 19508 19509 ExprResult Result = Visit(E->getSubExpr()); 19510 if (!Result.isUsable()) return ExprError(); 19511 19512 E->setSubExpr(Result.get()); 19513 return E; 19514 } else { 19515 llvm_unreachable("Unhandled cast type!"); 19516 } 19517 } 19518 19519 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19520 ExprValueKind ValueKind = VK_LValue; 19521 QualType Type = DestType; 19522 19523 // We know how to make this work for certain kinds of decls: 19524 19525 // - functions 19526 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19527 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19528 DestType = Ptr->getPointeeType(); 19529 ExprResult Result = resolveDecl(E, VD); 19530 if (Result.isInvalid()) return ExprError(); 19531 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 19532 VK_PRValue); 19533 } 19534 19535 if (!Type->isFunctionType()) { 19536 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19537 << VD << E->getSourceRange(); 19538 return ExprError(); 19539 } 19540 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19541 // We must match the FunctionDecl's type to the hack introduced in 19542 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19543 // type. See the lengthy commentary in that routine. 19544 QualType FDT = FD->getType(); 19545 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19546 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19547 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19548 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19549 SourceLocation Loc = FD->getLocation(); 19550 FunctionDecl *NewFD = FunctionDecl::Create( 19551 S.Context, FD->getDeclContext(), Loc, Loc, 19552 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19553 SC_None, S.getCurFPFeatures().isFPConstrained(), 19554 false /*isInlineSpecified*/, FD->hasPrototype(), 19555 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19556 19557 if (FD->getQualifier()) 19558 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19559 19560 SmallVector<ParmVarDecl*, 16> Params; 19561 for (const auto &AI : FT->param_types()) { 19562 ParmVarDecl *Param = 19563 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19564 Param->setScopeInfo(0, Params.size()); 19565 Params.push_back(Param); 19566 } 19567 NewFD->setParams(Params); 19568 DRE->setDecl(NewFD); 19569 VD = DRE->getDecl(); 19570 } 19571 } 19572 19573 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19574 if (MD->isInstance()) { 19575 ValueKind = VK_PRValue; 19576 Type = S.Context.BoundMemberTy; 19577 } 19578 19579 // Function references aren't l-values in C. 19580 if (!S.getLangOpts().CPlusPlus) 19581 ValueKind = VK_PRValue; 19582 19583 // - variables 19584 } else if (isa<VarDecl>(VD)) { 19585 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19586 Type = RefTy->getPointeeType(); 19587 } else if (Type->isFunctionType()) { 19588 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19589 << VD << E->getSourceRange(); 19590 return ExprError(); 19591 } 19592 19593 // - nothing else 19594 } else { 19595 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19596 << VD << E->getSourceRange(); 19597 return ExprError(); 19598 } 19599 19600 // Modifying the declaration like this is friendly to IR-gen but 19601 // also really dangerous. 19602 VD->setType(DestType); 19603 E->setType(Type); 19604 E->setValueKind(ValueKind); 19605 return E; 19606 } 19607 19608 /// Check a cast of an unknown-any type. We intentionally only 19609 /// trigger this for C-style casts. 19610 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19611 Expr *CastExpr, CastKind &CastKind, 19612 ExprValueKind &VK, CXXCastPath &Path) { 19613 // The type we're casting to must be either void or complete. 19614 if (!CastType->isVoidType() && 19615 RequireCompleteType(TypeRange.getBegin(), CastType, 19616 diag::err_typecheck_cast_to_incomplete)) 19617 return ExprError(); 19618 19619 // Rewrite the casted expression from scratch. 19620 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19621 if (!result.isUsable()) return ExprError(); 19622 19623 CastExpr = result.get(); 19624 VK = CastExpr->getValueKind(); 19625 CastKind = CK_NoOp; 19626 19627 return CastExpr; 19628 } 19629 19630 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19631 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19632 } 19633 19634 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19635 Expr *arg, QualType ¶mType) { 19636 // If the syntactic form of the argument is not an explicit cast of 19637 // any sort, just do default argument promotion. 19638 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19639 if (!castArg) { 19640 ExprResult result = DefaultArgumentPromotion(arg); 19641 if (result.isInvalid()) return ExprError(); 19642 paramType = result.get()->getType(); 19643 return result; 19644 } 19645 19646 // Otherwise, use the type that was written in the explicit cast. 19647 assert(!arg->hasPlaceholderType()); 19648 paramType = castArg->getTypeAsWritten(); 19649 19650 // Copy-initialize a parameter of that type. 19651 InitializedEntity entity = 19652 InitializedEntity::InitializeParameter(Context, paramType, 19653 /*consumed*/ false); 19654 return PerformCopyInitialization(entity, callLoc, arg); 19655 } 19656 19657 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19658 Expr *orig = E; 19659 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19660 while (true) { 19661 E = E->IgnoreParenImpCasts(); 19662 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19663 E = call->getCallee(); 19664 diagID = diag::err_uncasted_call_of_unknown_any; 19665 } else { 19666 break; 19667 } 19668 } 19669 19670 SourceLocation loc; 19671 NamedDecl *d; 19672 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19673 loc = ref->getLocation(); 19674 d = ref->getDecl(); 19675 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19676 loc = mem->getMemberLoc(); 19677 d = mem->getMemberDecl(); 19678 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19679 diagID = diag::err_uncasted_call_of_unknown_any; 19680 loc = msg->getSelectorStartLoc(); 19681 d = msg->getMethodDecl(); 19682 if (!d) { 19683 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19684 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19685 << orig->getSourceRange(); 19686 return ExprError(); 19687 } 19688 } else { 19689 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19690 << E->getSourceRange(); 19691 return ExprError(); 19692 } 19693 19694 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19695 19696 // Never recoverable. 19697 return ExprError(); 19698 } 19699 19700 /// Check for operands with placeholder types and complain if found. 19701 /// Returns ExprError() if there was an error and no recovery was possible. 19702 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19703 if (!Context.isDependenceAllowed()) { 19704 // C cannot handle TypoExpr nodes on either side of a binop because it 19705 // doesn't handle dependent types properly, so make sure any TypoExprs have 19706 // been dealt with before checking the operands. 19707 ExprResult Result = CorrectDelayedTyposInExpr(E); 19708 if (!Result.isUsable()) return ExprError(); 19709 E = Result.get(); 19710 } 19711 19712 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19713 if (!placeholderType) return E; 19714 19715 switch (placeholderType->getKind()) { 19716 19717 // Overloaded expressions. 19718 case BuiltinType::Overload: { 19719 // Try to resolve a single function template specialization. 19720 // This is obligatory. 19721 ExprResult Result = E; 19722 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19723 return Result; 19724 19725 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19726 // leaves Result unchanged on failure. 19727 Result = E; 19728 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19729 return Result; 19730 19731 // If that failed, try to recover with a call. 19732 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19733 /*complain*/ true); 19734 return Result; 19735 } 19736 19737 // Bound member functions. 19738 case BuiltinType::BoundMember: { 19739 ExprResult result = E; 19740 const Expr *BME = E->IgnoreParens(); 19741 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19742 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19743 if (isa<CXXPseudoDestructorExpr>(BME)) { 19744 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19745 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19746 if (ME->getMemberNameInfo().getName().getNameKind() == 19747 DeclarationName::CXXDestructorName) 19748 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19749 } 19750 tryToRecoverWithCall(result, PD, 19751 /*complain*/ true); 19752 return result; 19753 } 19754 19755 // ARC unbridged casts. 19756 case BuiltinType::ARCUnbridgedCast: { 19757 Expr *realCast = stripARCUnbridgedCast(E); 19758 diagnoseARCUnbridgedCast(realCast); 19759 return realCast; 19760 } 19761 19762 // Expressions of unknown type. 19763 case BuiltinType::UnknownAny: 19764 return diagnoseUnknownAnyExpr(*this, E); 19765 19766 // Pseudo-objects. 19767 case BuiltinType::PseudoObject: 19768 return checkPseudoObjectRValue(E); 19769 19770 case BuiltinType::BuiltinFn: { 19771 // Accept __noop without parens by implicitly converting it to a call expr. 19772 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19773 if (DRE) { 19774 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19775 if (FD->getBuiltinID() == Builtin::BI__noop) { 19776 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19777 CK_BuiltinFnToFnPtr) 19778 .get(); 19779 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19780 VK_PRValue, SourceLocation(), 19781 FPOptionsOverride()); 19782 } 19783 } 19784 19785 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19786 return ExprError(); 19787 } 19788 19789 case BuiltinType::IncompleteMatrixIdx: 19790 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19791 ->getRowIdx() 19792 ->getBeginLoc(), 19793 diag::err_matrix_incomplete_index); 19794 return ExprError(); 19795 19796 // Expressions of unknown type. 19797 case BuiltinType::OMPArraySection: 19798 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19799 return ExprError(); 19800 19801 // Expressions of unknown type. 19802 case BuiltinType::OMPArrayShaping: 19803 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19804 19805 case BuiltinType::OMPIterator: 19806 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19807 19808 // Everything else should be impossible. 19809 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19810 case BuiltinType::Id: 19811 #include "clang/Basic/OpenCLImageTypes.def" 19812 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19813 case BuiltinType::Id: 19814 #include "clang/Basic/OpenCLExtensionTypes.def" 19815 #define SVE_TYPE(Name, Id, SingletonId) \ 19816 case BuiltinType::Id: 19817 #include "clang/Basic/AArch64SVEACLETypes.def" 19818 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19819 case BuiltinType::Id: 19820 #include "clang/Basic/PPCTypes.def" 19821 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19822 #include "clang/Basic/RISCVVTypes.def" 19823 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19824 #define PLACEHOLDER_TYPE(Id, SingletonId) 19825 #include "clang/AST/BuiltinTypes.def" 19826 break; 19827 } 19828 19829 llvm_unreachable("invalid placeholder type!"); 19830 } 19831 19832 bool Sema::CheckCaseExpression(Expr *E) { 19833 if (E->isTypeDependent()) 19834 return true; 19835 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19836 return E->getType()->isIntegralOrEnumerationType(); 19837 return false; 19838 } 19839 19840 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19841 ExprResult 19842 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19843 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19844 "Unknown Objective-C Boolean value!"); 19845 QualType BoolT = Context.ObjCBuiltinBoolTy; 19846 if (!Context.getBOOLDecl()) { 19847 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19848 Sema::LookupOrdinaryName); 19849 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19850 NamedDecl *ND = Result.getFoundDecl(); 19851 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19852 Context.setBOOLDecl(TD); 19853 } 19854 } 19855 if (Context.getBOOLDecl()) 19856 BoolT = Context.getBOOLType(); 19857 return new (Context) 19858 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19859 } 19860 19861 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19862 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19863 SourceLocation RParen) { 19864 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { 19865 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19866 return Spec.getPlatform() == Platform; 19867 }); 19868 // Transcribe the "ios" availability check to "maccatalyst" when compiling 19869 // for "maccatalyst" if "maccatalyst" is not specified. 19870 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { 19871 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19872 return Spec.getPlatform() == "ios"; 19873 }); 19874 } 19875 if (Spec == AvailSpecs.end()) 19876 return None; 19877 return Spec->getVersion(); 19878 }; 19879 19880 VersionTuple Version; 19881 if (auto MaybeVersion = 19882 FindSpecVersion(Context.getTargetInfo().getPlatformName())) 19883 Version = *MaybeVersion; 19884 19885 // The use of `@available` in the enclosing context should be analyzed to 19886 // warn when it's used inappropriately (i.e. not if(@available)). 19887 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 19888 Context->HasPotentialAvailabilityViolations = true; 19889 19890 return new (Context) 19891 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19892 } 19893 19894 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19895 ArrayRef<Expr *> SubExprs, QualType T) { 19896 if (!Context.getLangOpts().RecoveryAST) 19897 return ExprError(); 19898 19899 if (isSFINAEContext()) 19900 return ExprError(); 19901 19902 if (T.isNull() || T->isUndeducedType() || 19903 !Context.getLangOpts().RecoveryASTType) 19904 // We don't know the concrete type, fallback to dependent type. 19905 T = Context.DependentTy; 19906 19907 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19908 } 19909