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/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/Builtins.h" 30 #include "clang/Basic/FixedPoint.h" 31 #include "clang/Basic/PartialDiagnostic.h" 32 #include "clang/Basic/SourceManager.h" 33 #include "clang/Basic/TargetInfo.h" 34 #include "clang/Lex/LiteralSupport.h" 35 #include "clang/Lex/Preprocessor.h" 36 #include "clang/Sema/AnalysisBasedWarnings.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Designator.h" 40 #include "clang/Sema/Initialization.h" 41 #include "clang/Sema/Lookup.h" 42 #include "clang/Sema/Overload.h" 43 #include "clang/Sema/ParsedTemplate.h" 44 #include "clang/Sema/Scope.h" 45 #include "clang/Sema/ScopeInfo.h" 46 #include "clang/Sema/SemaFixItUtils.h" 47 #include "clang/Sema/SemaInternal.h" 48 #include "clang/Sema/Template.h" 49 #include "llvm/Support/ConvertUTF.h" 50 #include "llvm/Support/SaveAndRestore.h" 51 using namespace clang; 52 using namespace sema; 53 using llvm::RoundingMode; 54 55 /// Determine whether the use of this declaration is valid, without 56 /// emitting diagnostics. 57 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 58 // See if this is an auto-typed variable whose initializer we are parsing. 59 if (ParsingInitForAutoVars.count(D)) 60 return false; 61 62 // See if this is a deleted function. 63 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 64 if (FD->isDeleted()) 65 return false; 66 67 // If the function has a deduced return type, and we can't deduce it, 68 // then we can't use it either. 69 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 70 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 71 return false; 72 73 // See if this is an aligned allocation/deallocation function that is 74 // unavailable. 75 if (TreatUnavailableAsInvalid && 76 isUnavailableAlignedAllocationFunction(*FD)) 77 return false; 78 } 79 80 // See if this function is unavailable. 81 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 82 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 83 return false; 84 85 return true; 86 } 87 88 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 89 // Warn if this is used but marked unused. 90 if (const auto *A = D->getAttr<UnusedAttr>()) { 91 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 92 // should diagnose them. 93 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 94 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 95 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 96 if (DC && !DC->hasAttr<UnusedAttr>()) 97 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 98 } 99 } 100 } 101 102 /// Emit a note explaining that this function is deleted. 103 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 104 assert(Decl && Decl->isDeleted()); 105 106 if (Decl->isDefaulted()) { 107 // If the method was explicitly defaulted, point at that declaration. 108 if (!Decl->isImplicit()) 109 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 110 111 // Try to diagnose why this special member function was implicitly 112 // deleted. This might fail, if that reason no longer applies. 113 DiagnoseDeletedDefaultedFunction(Decl); 114 return; 115 } 116 117 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 118 if (Ctor && Ctor->isInheritingConstructor()) 119 return NoteDeletedInheritingConstructor(Ctor); 120 121 Diag(Decl->getLocation(), diag::note_availability_specified_here) 122 << Decl << 1; 123 } 124 125 /// Determine whether a FunctionDecl was ever declared with an 126 /// explicit storage class. 127 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 128 for (auto I : D->redecls()) { 129 if (I->getStorageClass() != SC_None) 130 return true; 131 } 132 return false; 133 } 134 135 /// Check whether we're in an extern inline function and referring to a 136 /// variable or function with internal linkage (C11 6.7.4p3). 137 /// 138 /// This is only a warning because we used to silently accept this code, but 139 /// in many cases it will not behave correctly. This is not enabled in C++ mode 140 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 141 /// and so while there may still be user mistakes, most of the time we can't 142 /// prove that there are errors. 143 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 144 const NamedDecl *D, 145 SourceLocation Loc) { 146 // This is disabled under C++; there are too many ways for this to fire in 147 // contexts where the warning is a false positive, or where it is technically 148 // correct but benign. 149 if (S.getLangOpts().CPlusPlus) 150 return; 151 152 // Check if this is an inlined function or method. 153 FunctionDecl *Current = S.getCurFunctionDecl(); 154 if (!Current) 155 return; 156 if (!Current->isInlined()) 157 return; 158 if (!Current->isExternallyVisible()) 159 return; 160 161 // Check if the decl has internal linkage. 162 if (D->getFormalLinkage() != InternalLinkage) 163 return; 164 165 // Downgrade from ExtWarn to Extension if 166 // (1) the supposedly external inline function is in the main file, 167 // and probably won't be included anywhere else. 168 // (2) the thing we're referencing is a pure function. 169 // (3) the thing we're referencing is another inline function. 170 // This last can give us false negatives, but it's better than warning on 171 // wrappers for simple C library functions. 172 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 173 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 174 if (!DowngradeWarning && UsedFn) 175 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 176 177 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 178 : diag::ext_internal_in_extern_inline) 179 << /*IsVar=*/!UsedFn << D; 180 181 S.MaybeSuggestAddingStaticToDecl(Current); 182 183 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 184 << D; 185 } 186 187 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 188 const FunctionDecl *First = Cur->getFirstDecl(); 189 190 // Suggest "static" on the function, if possible. 191 if (!hasAnyExplicitStorageClass(First)) { 192 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 193 Diag(DeclBegin, diag::note_convert_inline_to_static) 194 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 195 } 196 } 197 198 /// Determine whether the use of this declaration is valid, and 199 /// emit any corresponding diagnostics. 200 /// 201 /// This routine diagnoses various problems with referencing 202 /// declarations that can occur when using a declaration. For example, 203 /// it might warn if a deprecated or unavailable declaration is being 204 /// used, or produce an error (and return true) if a C++0x deleted 205 /// function is being used. 206 /// 207 /// \returns true if there was an error (this declaration cannot be 208 /// referenced), false otherwise. 209 /// 210 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 211 const ObjCInterfaceDecl *UnknownObjCClass, 212 bool ObjCPropertyAccess, 213 bool AvoidPartialAvailabilityChecks, 214 ObjCInterfaceDecl *ClassReceiver) { 215 SourceLocation Loc = Locs.front(); 216 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 217 // If there were any diagnostics suppressed by template argument deduction, 218 // emit them now. 219 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 220 if (Pos != SuppressedDiagnostics.end()) { 221 for (const PartialDiagnosticAt &Suppressed : Pos->second) 222 Diag(Suppressed.first, Suppressed.second); 223 224 // Clear out the list of suppressed diagnostics, so that we don't emit 225 // them again for this specialization. However, we don't obsolete this 226 // entry from the table, because we want to avoid ever emitting these 227 // diagnostics again. 228 Pos->second.clear(); 229 } 230 231 // C++ [basic.start.main]p3: 232 // The function 'main' shall not be used within a program. 233 if (cast<FunctionDecl>(D)->isMain()) 234 Diag(Loc, diag::ext_main_used); 235 236 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 237 } 238 239 // See if this is an auto-typed variable whose initializer we are parsing. 240 if (ParsingInitForAutoVars.count(D)) { 241 if (isa<BindingDecl>(D)) { 242 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 243 << D->getDeclName(); 244 } else { 245 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 246 << D->getDeclName() << cast<VarDecl>(D)->getType(); 247 } 248 return true; 249 } 250 251 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 252 // See if this is a deleted function. 253 if (FD->isDeleted()) { 254 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 255 if (Ctor && Ctor->isInheritingConstructor()) 256 Diag(Loc, diag::err_deleted_inherited_ctor_use) 257 << Ctor->getParent() 258 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 259 else 260 Diag(Loc, diag::err_deleted_function_use); 261 NoteDeletedFunction(FD); 262 return true; 263 } 264 265 // [expr.prim.id]p4 266 // A program that refers explicitly or implicitly to a function with a 267 // trailing requires-clause whose constraint-expression is not satisfied, 268 // other than to declare it, is ill-formed. [...] 269 // 270 // See if this is a function with constraints that need to be satisfied. 271 // Check this before deducing the return type, as it might instantiate the 272 // definition. 273 if (FD->getTrailingRequiresClause()) { 274 ConstraintSatisfaction Satisfaction; 275 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 276 // A diagnostic will have already been generated (non-constant 277 // constraint expression, for example) 278 return true; 279 if (!Satisfaction.IsSatisfied) { 280 Diag(Loc, 281 diag::err_reference_to_function_with_unsatisfied_constraints) 282 << D; 283 DiagnoseUnsatisfiedConstraint(Satisfaction); 284 return true; 285 } 286 } 287 288 // If the function has a deduced return type, and we can't deduce it, 289 // then we can't use it either. 290 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 291 DeduceReturnType(FD, Loc)) 292 return true; 293 294 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 295 return true; 296 } 297 298 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 299 // Lambdas are only default-constructible or assignable in C++2a onwards. 300 if (MD->getParent()->isLambda() && 301 ((isa<CXXConstructorDecl>(MD) && 302 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 303 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 304 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 305 << !isa<CXXConstructorDecl>(MD); 306 } 307 } 308 309 auto getReferencedObjCProp = [](const NamedDecl *D) -> 310 const ObjCPropertyDecl * { 311 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 312 return MD->findPropertyDecl(); 313 return nullptr; 314 }; 315 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 316 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 317 return true; 318 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 319 return true; 320 } 321 322 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 323 // Only the variables omp_in and omp_out are allowed in the combiner. 324 // Only the variables omp_priv and omp_orig are allowed in the 325 // initializer-clause. 326 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 327 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 328 isa<VarDecl>(D)) { 329 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 330 << getCurFunction()->HasOMPDeclareReductionCombiner; 331 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 332 return true; 333 } 334 335 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 336 // List-items in map clauses on this construct may only refer to the declared 337 // variable var and entities that could be referenced by a procedure defined 338 // at the same location 339 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext); 340 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) && 341 isa<VarDecl>(D)) { 342 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 343 << DMD->getVarName().getAsString(); 344 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 345 return true; 346 } 347 348 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 349 AvoidPartialAvailabilityChecks, ClassReceiver); 350 351 DiagnoseUnusedOfDecl(*this, D, Loc); 352 353 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 354 355 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 356 !isUnevaluatedContext()) { 357 // C++ [expr.prim.req.nested] p3 358 // A local parameter shall only appear as an unevaluated operand 359 // (Clause 8) within the constraint-expression. 360 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 361 << D; 362 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 363 return true; 364 } 365 366 return false; 367 } 368 369 /// DiagnoseSentinelCalls - This routine checks whether a call or 370 /// message-send is to a declaration with the sentinel attribute, and 371 /// if so, it checks that the requirements of the sentinel are 372 /// satisfied. 373 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 374 ArrayRef<Expr *> Args) { 375 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 376 if (!attr) 377 return; 378 379 // The number of formal parameters of the declaration. 380 unsigned numFormalParams; 381 382 // The kind of declaration. This is also an index into a %select in 383 // the diagnostic. 384 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 385 386 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 387 numFormalParams = MD->param_size(); 388 calleeType = CT_Method; 389 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 390 numFormalParams = FD->param_size(); 391 calleeType = CT_Function; 392 } else if (isa<VarDecl>(D)) { 393 QualType type = cast<ValueDecl>(D)->getType(); 394 const FunctionType *fn = nullptr; 395 if (const PointerType *ptr = type->getAs<PointerType>()) { 396 fn = ptr->getPointeeType()->getAs<FunctionType>(); 397 if (!fn) return; 398 calleeType = CT_Function; 399 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 400 fn = ptr->getPointeeType()->castAs<FunctionType>(); 401 calleeType = CT_Block; 402 } else { 403 return; 404 } 405 406 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 407 numFormalParams = proto->getNumParams(); 408 } else { 409 numFormalParams = 0; 410 } 411 } else { 412 return; 413 } 414 415 // "nullPos" is the number of formal parameters at the end which 416 // effectively count as part of the variadic arguments. This is 417 // useful if you would prefer to not have *any* formal parameters, 418 // but the language forces you to have at least one. 419 unsigned nullPos = attr->getNullPos(); 420 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 421 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 422 423 // The number of arguments which should follow the sentinel. 424 unsigned numArgsAfterSentinel = attr->getSentinel(); 425 426 // If there aren't enough arguments for all the formal parameters, 427 // the sentinel, and the args after the sentinel, complain. 428 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 429 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 430 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 431 return; 432 } 433 434 // Otherwise, find the sentinel expression. 435 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 436 if (!sentinelExpr) return; 437 if (sentinelExpr->isValueDependent()) return; 438 if (Context.isSentinelNullExpr(sentinelExpr)) return; 439 440 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 441 // or 'NULL' if those are actually defined in the context. Only use 442 // 'nil' for ObjC methods, where it's much more likely that the 443 // variadic arguments form a list of object pointers. 444 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 445 std::string NullValue; 446 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 447 NullValue = "nil"; 448 else if (getLangOpts().CPlusPlus11) 449 NullValue = "nullptr"; 450 else if (PP.isMacroDefined("NULL")) 451 NullValue = "NULL"; 452 else 453 NullValue = "(void*) 0"; 454 455 if (MissingNilLoc.isInvalid()) 456 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 457 else 458 Diag(MissingNilLoc, diag::warn_missing_sentinel) 459 << int(calleeType) 460 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 461 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 462 } 463 464 SourceRange Sema::getExprRange(Expr *E) const { 465 return E ? E->getSourceRange() : SourceRange(); 466 } 467 468 //===----------------------------------------------------------------------===// 469 // Standard Promotions and Conversions 470 //===----------------------------------------------------------------------===// 471 472 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 473 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 474 // Handle any placeholder expressions which made it here. 475 if (E->getType()->isPlaceholderType()) { 476 ExprResult result = CheckPlaceholderExpr(E); 477 if (result.isInvalid()) return ExprError(); 478 E = result.get(); 479 } 480 481 QualType Ty = E->getType(); 482 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 483 484 if (Ty->isFunctionType()) { 485 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 486 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 487 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 488 return ExprError(); 489 490 E = ImpCastExprToType(E, Context.getPointerType(Ty), 491 CK_FunctionToPointerDecay).get(); 492 } else if (Ty->isArrayType()) { 493 // In C90 mode, arrays only promote to pointers if the array expression is 494 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 495 // type 'array of type' is converted to an expression that has type 'pointer 496 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 497 // that has type 'array of type' ...". The relevant change is "an lvalue" 498 // (C90) to "an expression" (C99). 499 // 500 // C++ 4.2p1: 501 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 502 // T" can be converted to an rvalue of type "pointer to T". 503 // 504 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 505 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 506 CK_ArrayToPointerDecay).get(); 507 } 508 return E; 509 } 510 511 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 512 // Check to see if we are dereferencing a null pointer. If so, 513 // and if not volatile-qualified, this is undefined behavior that the 514 // optimizer will delete, so warn about it. People sometimes try to use this 515 // to get a deterministic trap and are surprised by clang's behavior. This 516 // only handles the pattern "*null", which is a very syntactic check. 517 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 518 if (UO && UO->getOpcode() == UO_Deref && 519 UO->getSubExpr()->getType()->isPointerType()) { 520 const LangAS AS = 521 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 522 if ((!isTargetAddressSpace(AS) || 523 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 524 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 525 S.Context, Expr::NPC_ValueDependentIsNotNull) && 526 !UO->getType().isVolatileQualified()) { 527 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 528 S.PDiag(diag::warn_indirection_through_null) 529 << UO->getSubExpr()->getSourceRange()); 530 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 531 S.PDiag(diag::note_indirection_through_null)); 532 } 533 } 534 } 535 536 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 537 SourceLocation AssignLoc, 538 const Expr* RHS) { 539 const ObjCIvarDecl *IV = OIRE->getDecl(); 540 if (!IV) 541 return; 542 543 DeclarationName MemberName = IV->getDeclName(); 544 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 545 if (!Member || !Member->isStr("isa")) 546 return; 547 548 const Expr *Base = OIRE->getBase(); 549 QualType BaseType = Base->getType(); 550 if (OIRE->isArrow()) 551 BaseType = BaseType->getPointeeType(); 552 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 553 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 554 ObjCInterfaceDecl *ClassDeclared = nullptr; 555 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 556 if (!ClassDeclared->getSuperClass() 557 && (*ClassDeclared->ivar_begin()) == IV) { 558 if (RHS) { 559 NamedDecl *ObjectSetClass = 560 S.LookupSingleName(S.TUScope, 561 &S.Context.Idents.get("object_setClass"), 562 SourceLocation(), S.LookupOrdinaryName); 563 if (ObjectSetClass) { 564 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 565 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 566 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 567 "object_setClass(") 568 << FixItHint::CreateReplacement( 569 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 570 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 571 } 572 else 573 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 574 } else { 575 NamedDecl *ObjectGetClass = 576 S.LookupSingleName(S.TUScope, 577 &S.Context.Idents.get("object_getClass"), 578 SourceLocation(), S.LookupOrdinaryName); 579 if (ObjectGetClass) 580 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 581 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 582 "object_getClass(") 583 << FixItHint::CreateReplacement( 584 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 585 else 586 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 587 } 588 S.Diag(IV->getLocation(), diag::note_ivar_decl); 589 } 590 } 591 } 592 593 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 594 // Handle any placeholder expressions which made it here. 595 if (E->getType()->isPlaceholderType()) { 596 ExprResult result = CheckPlaceholderExpr(E); 597 if (result.isInvalid()) return ExprError(); 598 E = result.get(); 599 } 600 601 // C++ [conv.lval]p1: 602 // A glvalue of a non-function, non-array type T can be 603 // converted to a prvalue. 604 if (!E->isGLValue()) return E; 605 606 QualType T = E->getType(); 607 assert(!T.isNull() && "r-value conversion on typeless expression?"); 608 609 // We don't want to throw lvalue-to-rvalue casts on top of 610 // expressions of certain types in C++. 611 if (getLangOpts().CPlusPlus && 612 (E->getType() == Context.OverloadTy || 613 T->isDependentType() || 614 T->isRecordType())) 615 return E; 616 617 // The C standard is actually really unclear on this point, and 618 // DR106 tells us what the result should be but not why. It's 619 // generally best to say that void types just doesn't undergo 620 // lvalue-to-rvalue at all. Note that expressions of unqualified 621 // 'void' type are never l-values, but qualified void can be. 622 if (T->isVoidType()) 623 return E; 624 625 // OpenCL usually rejects direct accesses to values of 'half' type. 626 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 627 T->isHalfType()) { 628 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 629 << 0 << T; 630 return ExprError(); 631 } 632 633 CheckForNullPointerDereference(*this, E); 634 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 635 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 636 &Context.Idents.get("object_getClass"), 637 SourceLocation(), LookupOrdinaryName); 638 if (ObjectGetClass) 639 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 640 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 641 << FixItHint::CreateReplacement( 642 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 643 else 644 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 645 } 646 else if (const ObjCIvarRefExpr *OIRE = 647 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 648 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 649 650 // C++ [conv.lval]p1: 651 // [...] If T is a non-class type, the type of the prvalue is the 652 // cv-unqualified version of T. Otherwise, the type of the 653 // rvalue is T. 654 // 655 // C99 6.3.2.1p2: 656 // If the lvalue has qualified type, the value has the unqualified 657 // version of the type of the lvalue; otherwise, the value has the 658 // type of the lvalue. 659 if (T.hasQualifiers()) 660 T = T.getUnqualifiedType(); 661 662 // Under the MS ABI, lock down the inheritance model now. 663 if (T->isMemberPointerType() && 664 Context.getTargetInfo().getCXXABI().isMicrosoft()) 665 (void)isCompleteType(E->getExprLoc(), T); 666 667 ExprResult Res = CheckLValueToRValueConversionOperand(E); 668 if (Res.isInvalid()) 669 return Res; 670 E = Res.get(); 671 672 // Loading a __weak object implicitly retains the value, so we need a cleanup to 673 // balance that. 674 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 675 Cleanup.setExprNeedsCleanups(true); 676 677 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 678 Cleanup.setExprNeedsCleanups(true); 679 680 // C++ [conv.lval]p3: 681 // If T is cv std::nullptr_t, the result is a null pointer constant. 682 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 683 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue); 684 685 // C11 6.3.2.1p2: 686 // ... if the lvalue has atomic type, the value has the non-atomic version 687 // of the type of the lvalue ... 688 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 689 T = Atomic->getValueType().getUnqualifiedType(); 690 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 691 nullptr, VK_RValue); 692 } 693 694 return Res; 695 } 696 697 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 698 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 699 if (Res.isInvalid()) 700 return ExprError(); 701 Res = DefaultLvalueConversion(Res.get()); 702 if (Res.isInvalid()) 703 return ExprError(); 704 return Res; 705 } 706 707 /// CallExprUnaryConversions - a special case of an unary conversion 708 /// performed on a function designator of a call expression. 709 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 710 QualType Ty = E->getType(); 711 ExprResult Res = E; 712 // Only do implicit cast for a function type, but not for a pointer 713 // to function type. 714 if (Ty->isFunctionType()) { 715 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 716 CK_FunctionToPointerDecay).get(); 717 if (Res.isInvalid()) 718 return ExprError(); 719 } 720 Res = DefaultLvalueConversion(Res.get()); 721 if (Res.isInvalid()) 722 return ExprError(); 723 return Res.get(); 724 } 725 726 /// UsualUnaryConversions - Performs various conversions that are common to most 727 /// operators (C99 6.3). The conversions of array and function types are 728 /// sometimes suppressed. For example, the array->pointer conversion doesn't 729 /// apply if the array is an argument to the sizeof or address (&) operators. 730 /// In these instances, this routine should *not* be called. 731 ExprResult Sema::UsualUnaryConversions(Expr *E) { 732 // First, convert to an r-value. 733 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 734 if (Res.isInvalid()) 735 return ExprError(); 736 E = Res.get(); 737 738 QualType Ty = E->getType(); 739 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 740 741 // Half FP have to be promoted to float unless it is natively supported 742 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 743 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 744 745 // Try to perform integral promotions if the object has a theoretically 746 // promotable type. 747 if (Ty->isIntegralOrUnscopedEnumerationType()) { 748 // C99 6.3.1.1p2: 749 // 750 // The following may be used in an expression wherever an int or 751 // unsigned int may be used: 752 // - an object or expression with an integer type whose integer 753 // conversion rank is less than or equal to the rank of int 754 // and unsigned int. 755 // - A bit-field of type _Bool, int, signed int, or unsigned int. 756 // 757 // If an int can represent all values of the original type, the 758 // value is converted to an int; otherwise, it is converted to an 759 // unsigned int. These are called the integer promotions. All 760 // other types are unchanged by the integer promotions. 761 762 QualType PTy = Context.isPromotableBitField(E); 763 if (!PTy.isNull()) { 764 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 765 return E; 766 } 767 if (Ty->isPromotableIntegerType()) { 768 QualType PT = Context.getPromotedIntegerType(Ty); 769 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 770 return E; 771 } 772 } 773 return E; 774 } 775 776 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 777 /// do not have a prototype. Arguments that have type float or __fp16 778 /// are promoted to double. All other argument types are converted by 779 /// UsualUnaryConversions(). 780 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 781 QualType Ty = E->getType(); 782 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 783 784 ExprResult Res = UsualUnaryConversions(E); 785 if (Res.isInvalid()) 786 return ExprError(); 787 E = Res.get(); 788 789 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 790 // promote to double. 791 // Note that default argument promotion applies only to float (and 792 // half/fp16); it does not apply to _Float16. 793 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 794 if (BTy && (BTy->getKind() == BuiltinType::Half || 795 BTy->getKind() == BuiltinType::Float)) { 796 if (getLangOpts().OpenCL && 797 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 798 if (BTy->getKind() == BuiltinType::Half) { 799 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 800 } 801 } else { 802 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 803 } 804 } 805 806 // C++ performs lvalue-to-rvalue conversion as a default argument 807 // promotion, even on class types, but note: 808 // C++11 [conv.lval]p2: 809 // When an lvalue-to-rvalue conversion occurs in an unevaluated 810 // operand or a subexpression thereof the value contained in the 811 // referenced object is not accessed. Otherwise, if the glvalue 812 // has a class type, the conversion copy-initializes a temporary 813 // of type T from the glvalue and the result of the conversion 814 // is a prvalue for the temporary. 815 // FIXME: add some way to gate this entire thing for correctness in 816 // potentially potentially evaluated contexts. 817 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 818 ExprResult Temp = PerformCopyInitialization( 819 InitializedEntity::InitializeTemporary(E->getType()), 820 E->getExprLoc(), E); 821 if (Temp.isInvalid()) 822 return ExprError(); 823 E = Temp.get(); 824 } 825 826 return E; 827 } 828 829 /// Determine the degree of POD-ness for an expression. 830 /// Incomplete types are considered POD, since this check can be performed 831 /// when we're in an unevaluated context. 832 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 833 if (Ty->isIncompleteType()) { 834 // C++11 [expr.call]p7: 835 // After these conversions, if the argument does not have arithmetic, 836 // enumeration, pointer, pointer to member, or class type, the program 837 // is ill-formed. 838 // 839 // Since we've already performed array-to-pointer and function-to-pointer 840 // decay, the only such type in C++ is cv void. This also handles 841 // initializer lists as variadic arguments. 842 if (Ty->isVoidType()) 843 return VAK_Invalid; 844 845 if (Ty->isObjCObjectType()) 846 return VAK_Invalid; 847 return VAK_Valid; 848 } 849 850 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 851 return VAK_Invalid; 852 853 if (Ty.isCXX98PODType(Context)) 854 return VAK_Valid; 855 856 // C++11 [expr.call]p7: 857 // Passing a potentially-evaluated argument of class type (Clause 9) 858 // having a non-trivial copy constructor, a non-trivial move constructor, 859 // or a non-trivial destructor, with no corresponding parameter, 860 // is conditionally-supported with implementation-defined semantics. 861 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 862 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 863 if (!Record->hasNonTrivialCopyConstructor() && 864 !Record->hasNonTrivialMoveConstructor() && 865 !Record->hasNonTrivialDestructor()) 866 return VAK_ValidInCXX11; 867 868 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 869 return VAK_Valid; 870 871 if (Ty->isObjCObjectType()) 872 return VAK_Invalid; 873 874 if (getLangOpts().MSVCCompat) 875 return VAK_MSVCUndefined; 876 877 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 878 // permitted to reject them. We should consider doing so. 879 return VAK_Undefined; 880 } 881 882 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 883 // Don't allow one to pass an Objective-C interface to a vararg. 884 const QualType &Ty = E->getType(); 885 VarArgKind VAK = isValidVarArgType(Ty); 886 887 // Complain about passing non-POD types through varargs. 888 switch (VAK) { 889 case VAK_ValidInCXX11: 890 DiagRuntimeBehavior( 891 E->getBeginLoc(), nullptr, 892 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 893 LLVM_FALLTHROUGH; 894 case VAK_Valid: 895 if (Ty->isRecordType()) { 896 // This is unlikely to be what the user intended. If the class has a 897 // 'c_str' member function, the user probably meant to call that. 898 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 899 PDiag(diag::warn_pass_class_arg_to_vararg) 900 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 901 } 902 break; 903 904 case VAK_Undefined: 905 case VAK_MSVCUndefined: 906 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 907 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 908 << getLangOpts().CPlusPlus11 << Ty << CT); 909 break; 910 911 case VAK_Invalid: 912 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 913 Diag(E->getBeginLoc(), 914 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 915 << Ty << CT; 916 else if (Ty->isObjCObjectType()) 917 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 918 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 919 << Ty << CT); 920 else 921 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 922 << isa<InitListExpr>(E) << Ty << CT; 923 break; 924 } 925 } 926 927 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 928 /// will create a trap if the resulting type is not a POD type. 929 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 930 FunctionDecl *FDecl) { 931 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 932 // Strip the unbridged-cast placeholder expression off, if applicable. 933 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 934 (CT == VariadicMethod || 935 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 936 E = stripARCUnbridgedCast(E); 937 938 // Otherwise, do normal placeholder checking. 939 } else { 940 ExprResult ExprRes = CheckPlaceholderExpr(E); 941 if (ExprRes.isInvalid()) 942 return ExprError(); 943 E = ExprRes.get(); 944 } 945 } 946 947 ExprResult ExprRes = DefaultArgumentPromotion(E); 948 if (ExprRes.isInvalid()) 949 return ExprError(); 950 E = ExprRes.get(); 951 952 // Diagnostics regarding non-POD argument types are 953 // emitted along with format string checking in Sema::CheckFunctionCall(). 954 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 955 // Turn this into a trap. 956 CXXScopeSpec SS; 957 SourceLocation TemplateKWLoc; 958 UnqualifiedId Name; 959 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 960 E->getBeginLoc()); 961 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 962 /*HasTrailingLParen=*/true, 963 /*IsAddressOfOperand=*/false); 964 if (TrapFn.isInvalid()) 965 return ExprError(); 966 967 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 968 None, E->getEndLoc()); 969 if (Call.isInvalid()) 970 return ExprError(); 971 972 ExprResult Comma = 973 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 974 if (Comma.isInvalid()) 975 return ExprError(); 976 return Comma.get(); 977 } 978 979 if (!getLangOpts().CPlusPlus && 980 RequireCompleteType(E->getExprLoc(), E->getType(), 981 diag::err_call_incomplete_argument)) 982 return ExprError(); 983 984 return E; 985 } 986 987 /// Converts an integer to complex float type. Helper function of 988 /// UsualArithmeticConversions() 989 /// 990 /// \return false if the integer expression is an integer type and is 991 /// successfully converted to the complex type. 992 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 993 ExprResult &ComplexExpr, 994 QualType IntTy, 995 QualType ComplexTy, 996 bool SkipCast) { 997 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 998 if (SkipCast) return false; 999 if (IntTy->isIntegerType()) { 1000 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1001 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1002 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1003 CK_FloatingRealToComplex); 1004 } else { 1005 assert(IntTy->isComplexIntegerType()); 1006 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1007 CK_IntegralComplexToFloatingComplex); 1008 } 1009 return false; 1010 } 1011 1012 /// Handle arithmetic conversion with complex types. Helper function of 1013 /// UsualArithmeticConversions() 1014 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1015 ExprResult &RHS, QualType LHSType, 1016 QualType RHSType, 1017 bool IsCompAssign) { 1018 // if we have an integer operand, the result is the complex type. 1019 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1020 /*skipCast*/false)) 1021 return LHSType; 1022 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1023 /*skipCast*/IsCompAssign)) 1024 return RHSType; 1025 1026 // This handles complex/complex, complex/float, or float/complex. 1027 // When both operands are complex, the shorter operand is converted to the 1028 // type of the longer, and that is the type of the result. This corresponds 1029 // to what is done when combining two real floating-point operands. 1030 // The fun begins when size promotion occur across type domains. 1031 // From H&S 6.3.4: When one operand is complex and the other is a real 1032 // floating-point type, the less precise type is converted, within it's 1033 // real or complex domain, to the precision of the other type. For example, 1034 // when combining a "long double" with a "double _Complex", the 1035 // "double _Complex" is promoted to "long double _Complex". 1036 1037 // Compute the rank of the two types, regardless of whether they are complex. 1038 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1039 1040 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1041 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1042 QualType LHSElementType = 1043 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1044 QualType RHSElementType = 1045 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1046 1047 QualType ResultType = S.Context.getComplexType(LHSElementType); 1048 if (Order < 0) { 1049 // Promote the precision of the LHS if not an assignment. 1050 ResultType = S.Context.getComplexType(RHSElementType); 1051 if (!IsCompAssign) { 1052 if (LHSComplexType) 1053 LHS = 1054 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1055 else 1056 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1057 } 1058 } else if (Order > 0) { 1059 // Promote the precision of the RHS. 1060 if (RHSComplexType) 1061 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1062 else 1063 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1064 } 1065 return ResultType; 1066 } 1067 1068 /// Handle arithmetic conversion from integer to float. Helper function 1069 /// of UsualArithmeticConversions() 1070 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1071 ExprResult &IntExpr, 1072 QualType FloatTy, QualType IntTy, 1073 bool ConvertFloat, bool ConvertInt) { 1074 if (IntTy->isIntegerType()) { 1075 if (ConvertInt) 1076 // Convert intExpr to the lhs floating point type. 1077 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1078 CK_IntegralToFloating); 1079 return FloatTy; 1080 } 1081 1082 // Convert both sides to the appropriate complex float. 1083 assert(IntTy->isComplexIntegerType()); 1084 QualType result = S.Context.getComplexType(FloatTy); 1085 1086 // _Complex int -> _Complex float 1087 if (ConvertInt) 1088 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1089 CK_IntegralComplexToFloatingComplex); 1090 1091 // float -> _Complex float 1092 if (ConvertFloat) 1093 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1094 CK_FloatingRealToComplex); 1095 1096 return result; 1097 } 1098 1099 /// Handle arithmethic conversion with floating point types. Helper 1100 /// function of UsualArithmeticConversions() 1101 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1102 ExprResult &RHS, QualType LHSType, 1103 QualType RHSType, bool IsCompAssign) { 1104 bool LHSFloat = LHSType->isRealFloatingType(); 1105 bool RHSFloat = RHSType->isRealFloatingType(); 1106 1107 // If we have two real floating types, convert the smaller operand 1108 // to the bigger result. 1109 if (LHSFloat && RHSFloat) { 1110 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1111 if (order > 0) { 1112 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1113 return LHSType; 1114 } 1115 1116 assert(order < 0 && "illegal float comparison"); 1117 if (!IsCompAssign) 1118 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1119 return RHSType; 1120 } 1121 1122 if (LHSFloat) { 1123 // Half FP has to be promoted to float unless it is natively supported 1124 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1125 LHSType = S.Context.FloatTy; 1126 1127 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1128 /*ConvertFloat=*/!IsCompAssign, 1129 /*ConvertInt=*/ true); 1130 } 1131 assert(RHSFloat); 1132 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1133 /*convertInt=*/ true, 1134 /*convertFloat=*/!IsCompAssign); 1135 } 1136 1137 /// Diagnose attempts to convert between __float128 and long double if 1138 /// there is no support for such conversion. Helper function of 1139 /// UsualArithmeticConversions(). 1140 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1141 QualType RHSType) { 1142 /* No issue converting if at least one of the types is not a floating point 1143 type or the two types have the same rank. 1144 */ 1145 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1146 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1147 return false; 1148 1149 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1150 "The remaining types must be floating point types."); 1151 1152 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1153 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1154 1155 QualType LHSElemType = LHSComplex ? 1156 LHSComplex->getElementType() : LHSType; 1157 QualType RHSElemType = RHSComplex ? 1158 RHSComplex->getElementType() : RHSType; 1159 1160 // No issue if the two types have the same representation 1161 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1162 &S.Context.getFloatTypeSemantics(RHSElemType)) 1163 return false; 1164 1165 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1166 RHSElemType == S.Context.LongDoubleTy); 1167 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1168 RHSElemType == S.Context.Float128Ty); 1169 1170 // We've handled the situation where __float128 and long double have the same 1171 // representation. We allow all conversions for all possible long double types 1172 // except PPC's double double. 1173 return Float128AndLongDouble && 1174 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1175 &llvm::APFloat::PPCDoubleDouble()); 1176 } 1177 1178 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1179 1180 namespace { 1181 /// These helper callbacks are placed in an anonymous namespace to 1182 /// permit their use as function template parameters. 1183 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1184 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1185 } 1186 1187 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1188 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1189 CK_IntegralComplexCast); 1190 } 1191 } 1192 1193 /// Handle integer arithmetic conversions. Helper function of 1194 /// UsualArithmeticConversions() 1195 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1196 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1197 ExprResult &RHS, QualType LHSType, 1198 QualType RHSType, bool IsCompAssign) { 1199 // The rules for this case are in C99 6.3.1.8 1200 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1201 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1202 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1203 if (LHSSigned == RHSSigned) { 1204 // Same signedness; use the higher-ranked type 1205 if (order >= 0) { 1206 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1207 return LHSType; 1208 } else if (!IsCompAssign) 1209 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1210 return RHSType; 1211 } else if (order != (LHSSigned ? 1 : -1)) { 1212 // The unsigned type has greater than or equal rank to the 1213 // signed type, so use the unsigned type 1214 if (RHSSigned) { 1215 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1216 return LHSType; 1217 } else if (!IsCompAssign) 1218 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1219 return RHSType; 1220 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1221 // The two types are different widths; if we are here, that 1222 // means the signed type is larger than the unsigned type, so 1223 // use the signed type. 1224 if (LHSSigned) { 1225 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1226 return LHSType; 1227 } else if (!IsCompAssign) 1228 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1229 return RHSType; 1230 } else { 1231 // The signed type is higher-ranked than the unsigned type, 1232 // but isn't actually any bigger (like unsigned int and long 1233 // on most 32-bit systems). Use the unsigned type corresponding 1234 // to the signed type. 1235 QualType result = 1236 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1237 RHS = (*doRHSCast)(S, RHS.get(), result); 1238 if (!IsCompAssign) 1239 LHS = (*doLHSCast)(S, LHS.get(), result); 1240 return result; 1241 } 1242 } 1243 1244 /// Handle conversions with GCC complex int extension. Helper function 1245 /// of UsualArithmeticConversions() 1246 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1247 ExprResult &RHS, QualType LHSType, 1248 QualType RHSType, 1249 bool IsCompAssign) { 1250 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1251 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1252 1253 if (LHSComplexInt && RHSComplexInt) { 1254 QualType LHSEltType = LHSComplexInt->getElementType(); 1255 QualType RHSEltType = RHSComplexInt->getElementType(); 1256 QualType ScalarType = 1257 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1258 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1259 1260 return S.Context.getComplexType(ScalarType); 1261 } 1262 1263 if (LHSComplexInt) { 1264 QualType LHSEltType = LHSComplexInt->getElementType(); 1265 QualType ScalarType = 1266 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1267 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1268 QualType ComplexType = S.Context.getComplexType(ScalarType); 1269 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1270 CK_IntegralRealToComplex); 1271 1272 return ComplexType; 1273 } 1274 1275 assert(RHSComplexInt); 1276 1277 QualType RHSEltType = RHSComplexInt->getElementType(); 1278 QualType ScalarType = 1279 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1280 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1281 QualType ComplexType = S.Context.getComplexType(ScalarType); 1282 1283 if (!IsCompAssign) 1284 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1285 CK_IntegralRealToComplex); 1286 return ComplexType; 1287 } 1288 1289 /// Return the rank of a given fixed point or integer type. The value itself 1290 /// doesn't matter, but the values must be increasing with proper increasing 1291 /// rank as described in N1169 4.1.1. 1292 static unsigned GetFixedPointRank(QualType Ty) { 1293 const auto *BTy = Ty->getAs<BuiltinType>(); 1294 assert(BTy && "Expected a builtin type."); 1295 1296 switch (BTy->getKind()) { 1297 case BuiltinType::ShortFract: 1298 case BuiltinType::UShortFract: 1299 case BuiltinType::SatShortFract: 1300 case BuiltinType::SatUShortFract: 1301 return 1; 1302 case BuiltinType::Fract: 1303 case BuiltinType::UFract: 1304 case BuiltinType::SatFract: 1305 case BuiltinType::SatUFract: 1306 return 2; 1307 case BuiltinType::LongFract: 1308 case BuiltinType::ULongFract: 1309 case BuiltinType::SatLongFract: 1310 case BuiltinType::SatULongFract: 1311 return 3; 1312 case BuiltinType::ShortAccum: 1313 case BuiltinType::UShortAccum: 1314 case BuiltinType::SatShortAccum: 1315 case BuiltinType::SatUShortAccum: 1316 return 4; 1317 case BuiltinType::Accum: 1318 case BuiltinType::UAccum: 1319 case BuiltinType::SatAccum: 1320 case BuiltinType::SatUAccum: 1321 return 5; 1322 case BuiltinType::LongAccum: 1323 case BuiltinType::ULongAccum: 1324 case BuiltinType::SatLongAccum: 1325 case BuiltinType::SatULongAccum: 1326 return 6; 1327 default: 1328 if (BTy->isInteger()) 1329 return 0; 1330 llvm_unreachable("Unexpected fixed point or integer type"); 1331 } 1332 } 1333 1334 /// handleFixedPointConversion - Fixed point operations between fixed 1335 /// point types and integers or other fixed point types do not fall under 1336 /// usual arithmetic conversion since these conversions could result in loss 1337 /// of precsision (N1169 4.1.4). These operations should be calculated with 1338 /// the full precision of their result type (N1169 4.1.6.2.1). 1339 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1340 QualType RHSTy) { 1341 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1342 "Expected at least one of the operands to be a fixed point type"); 1343 assert((LHSTy->isFixedPointOrIntegerType() || 1344 RHSTy->isFixedPointOrIntegerType()) && 1345 "Special fixed point arithmetic operation conversions are only " 1346 "applied to ints or other fixed point types"); 1347 1348 // If one operand has signed fixed-point type and the other operand has 1349 // unsigned fixed-point type, then the unsigned fixed-point operand is 1350 // converted to its corresponding signed fixed-point type and the resulting 1351 // type is the type of the converted operand. 1352 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1353 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1354 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1355 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1356 1357 // The result type is the type with the highest rank, whereby a fixed-point 1358 // conversion rank is always greater than an integer conversion rank; if the 1359 // type of either of the operands is a saturating fixedpoint type, the result 1360 // type shall be the saturating fixed-point type corresponding to the type 1361 // with the highest rank; the resulting value is converted (taking into 1362 // account rounding and overflow) to the precision of the resulting type. 1363 // Same ranks between signed and unsigned types are resolved earlier, so both 1364 // types are either signed or both unsigned at this point. 1365 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1366 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1367 1368 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1369 1370 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1371 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1372 1373 return ResultTy; 1374 } 1375 1376 /// Check that the usual arithmetic conversions can be performed on this pair of 1377 /// expressions that might be of enumeration type. 1378 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1379 SourceLocation Loc, 1380 Sema::ArithConvKind ACK) { 1381 // C++2a [expr.arith.conv]p1: 1382 // If one operand is of enumeration type and the other operand is of a 1383 // different enumeration type or a floating-point type, this behavior is 1384 // deprecated ([depr.arith.conv.enum]). 1385 // 1386 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1387 // Eventually we will presumably reject these cases (in C++23 onwards?). 1388 QualType L = LHS->getType(), R = RHS->getType(); 1389 bool LEnum = L->isUnscopedEnumerationType(), 1390 REnum = R->isUnscopedEnumerationType(); 1391 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1392 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1393 (REnum && L->isFloatingType())) { 1394 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1395 ? diag::warn_arith_conv_enum_float_cxx20 1396 : diag::warn_arith_conv_enum_float) 1397 << LHS->getSourceRange() << RHS->getSourceRange() 1398 << (int)ACK << LEnum << L << R; 1399 } else if (!IsCompAssign && LEnum && REnum && 1400 !S.Context.hasSameUnqualifiedType(L, R)) { 1401 unsigned DiagID; 1402 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1403 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1404 // If either enumeration type is unnamed, it's less likely that the 1405 // user cares about this, but this situation is still deprecated in 1406 // C++2a. Use a different warning group. 1407 DiagID = S.getLangOpts().CPlusPlus20 1408 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1409 : diag::warn_arith_conv_mixed_anon_enum_types; 1410 } else if (ACK == Sema::ACK_Conditional) { 1411 // Conditional expressions are separated out because they have 1412 // historically had a different warning flag. 1413 DiagID = S.getLangOpts().CPlusPlus20 1414 ? diag::warn_conditional_mixed_enum_types_cxx20 1415 : diag::warn_conditional_mixed_enum_types; 1416 } else if (ACK == Sema::ACK_Comparison) { 1417 // Comparison expressions are separated out because they have 1418 // historically had a different warning flag. 1419 DiagID = S.getLangOpts().CPlusPlus20 1420 ? diag::warn_comparison_mixed_enum_types_cxx20 1421 : diag::warn_comparison_mixed_enum_types; 1422 } else { 1423 DiagID = S.getLangOpts().CPlusPlus20 1424 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1425 : diag::warn_arith_conv_mixed_enum_types; 1426 } 1427 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1428 << (int)ACK << L << R; 1429 } 1430 } 1431 1432 /// UsualArithmeticConversions - Performs various conversions that are common to 1433 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1434 /// routine returns the first non-arithmetic type found. The client is 1435 /// responsible for emitting appropriate error diagnostics. 1436 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1437 SourceLocation Loc, 1438 ArithConvKind ACK) { 1439 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1440 1441 if (ACK != ACK_CompAssign) { 1442 LHS = UsualUnaryConversions(LHS.get()); 1443 if (LHS.isInvalid()) 1444 return QualType(); 1445 } 1446 1447 RHS = UsualUnaryConversions(RHS.get()); 1448 if (RHS.isInvalid()) 1449 return QualType(); 1450 1451 // For conversion purposes, we ignore any qualifiers. 1452 // For example, "const float" and "float" are equivalent. 1453 QualType LHSType = 1454 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1455 QualType RHSType = 1456 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1457 1458 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1459 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1460 LHSType = AtomicLHS->getValueType(); 1461 1462 // If both types are identical, no conversion is needed. 1463 if (LHSType == RHSType) 1464 return LHSType; 1465 1466 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1467 // The caller can deal with this (e.g. pointer + int). 1468 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1469 return QualType(); 1470 1471 // Apply unary and bitfield promotions to the LHS's type. 1472 QualType LHSUnpromotedType = LHSType; 1473 if (LHSType->isPromotableIntegerType()) 1474 LHSType = Context.getPromotedIntegerType(LHSType); 1475 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1476 if (!LHSBitfieldPromoteTy.isNull()) 1477 LHSType = LHSBitfieldPromoteTy; 1478 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1479 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1480 1481 // If both types are identical, no conversion is needed. 1482 if (LHSType == RHSType) 1483 return LHSType; 1484 1485 // ExtInt types aren't subject to conversions between them or normal integers, 1486 // so this fails. 1487 if(LHSType->isExtIntType() || RHSType->isExtIntType()) 1488 return QualType(); 1489 1490 // At this point, we have two different arithmetic types. 1491 1492 // Diagnose attempts to convert between __float128 and long double where 1493 // such conversions currently can't be handled. 1494 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1495 return QualType(); 1496 1497 // Handle complex types first (C99 6.3.1.8p1). 1498 if (LHSType->isComplexType() || RHSType->isComplexType()) 1499 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1500 ACK == ACK_CompAssign); 1501 1502 // Now handle "real" floating types (i.e. float, double, long double). 1503 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1504 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1505 ACK == ACK_CompAssign); 1506 1507 // Handle GCC complex int extension. 1508 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1509 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1510 ACK == ACK_CompAssign); 1511 1512 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1513 return handleFixedPointConversion(*this, LHSType, RHSType); 1514 1515 // Finally, we have two differing integer types. 1516 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1517 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1518 } 1519 1520 //===----------------------------------------------------------------------===// 1521 // Semantic Analysis for various Expression Types 1522 //===----------------------------------------------------------------------===// 1523 1524 1525 ExprResult 1526 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1527 SourceLocation DefaultLoc, 1528 SourceLocation RParenLoc, 1529 Expr *ControllingExpr, 1530 ArrayRef<ParsedType> ArgTypes, 1531 ArrayRef<Expr *> ArgExprs) { 1532 unsigned NumAssocs = ArgTypes.size(); 1533 assert(NumAssocs == ArgExprs.size()); 1534 1535 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1536 for (unsigned i = 0; i < NumAssocs; ++i) { 1537 if (ArgTypes[i]) 1538 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1539 else 1540 Types[i] = nullptr; 1541 } 1542 1543 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1544 ControllingExpr, 1545 llvm::makeArrayRef(Types, NumAssocs), 1546 ArgExprs); 1547 delete [] Types; 1548 return ER; 1549 } 1550 1551 ExprResult 1552 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1553 SourceLocation DefaultLoc, 1554 SourceLocation RParenLoc, 1555 Expr *ControllingExpr, 1556 ArrayRef<TypeSourceInfo *> Types, 1557 ArrayRef<Expr *> Exprs) { 1558 unsigned NumAssocs = Types.size(); 1559 assert(NumAssocs == Exprs.size()); 1560 1561 // Decay and strip qualifiers for the controlling expression type, and handle 1562 // placeholder type replacement. See committee discussion from WG14 DR423. 1563 { 1564 EnterExpressionEvaluationContext Unevaluated( 1565 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1566 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1567 if (R.isInvalid()) 1568 return ExprError(); 1569 ControllingExpr = R.get(); 1570 } 1571 1572 // The controlling expression is an unevaluated operand, so side effects are 1573 // likely unintended. 1574 if (!inTemplateInstantiation() && 1575 ControllingExpr->HasSideEffects(Context, false)) 1576 Diag(ControllingExpr->getExprLoc(), 1577 diag::warn_side_effects_unevaluated_context); 1578 1579 bool TypeErrorFound = false, 1580 IsResultDependent = ControllingExpr->isTypeDependent(), 1581 ContainsUnexpandedParameterPack 1582 = ControllingExpr->containsUnexpandedParameterPack(); 1583 1584 for (unsigned i = 0; i < NumAssocs; ++i) { 1585 if (Exprs[i]->containsUnexpandedParameterPack()) 1586 ContainsUnexpandedParameterPack = true; 1587 1588 if (Types[i]) { 1589 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1590 ContainsUnexpandedParameterPack = true; 1591 1592 if (Types[i]->getType()->isDependentType()) { 1593 IsResultDependent = true; 1594 } else { 1595 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1596 // complete object type other than a variably modified type." 1597 unsigned D = 0; 1598 if (Types[i]->getType()->isIncompleteType()) 1599 D = diag::err_assoc_type_incomplete; 1600 else if (!Types[i]->getType()->isObjectType()) 1601 D = diag::err_assoc_type_nonobject; 1602 else if (Types[i]->getType()->isVariablyModifiedType()) 1603 D = diag::err_assoc_type_variably_modified; 1604 1605 if (D != 0) { 1606 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1607 << Types[i]->getTypeLoc().getSourceRange() 1608 << Types[i]->getType(); 1609 TypeErrorFound = true; 1610 } 1611 1612 // C11 6.5.1.1p2 "No two generic associations in the same generic 1613 // selection shall specify compatible types." 1614 for (unsigned j = i+1; j < NumAssocs; ++j) 1615 if (Types[j] && !Types[j]->getType()->isDependentType() && 1616 Context.typesAreCompatible(Types[i]->getType(), 1617 Types[j]->getType())) { 1618 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1619 diag::err_assoc_compatible_types) 1620 << Types[j]->getTypeLoc().getSourceRange() 1621 << Types[j]->getType() 1622 << Types[i]->getType(); 1623 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1624 diag::note_compat_assoc) 1625 << Types[i]->getTypeLoc().getSourceRange() 1626 << Types[i]->getType(); 1627 TypeErrorFound = true; 1628 } 1629 } 1630 } 1631 } 1632 if (TypeErrorFound) 1633 return ExprError(); 1634 1635 // If we determined that the generic selection is result-dependent, don't 1636 // try to compute the result expression. 1637 if (IsResultDependent) 1638 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1639 Exprs, DefaultLoc, RParenLoc, 1640 ContainsUnexpandedParameterPack); 1641 1642 SmallVector<unsigned, 1> CompatIndices; 1643 unsigned DefaultIndex = -1U; 1644 for (unsigned i = 0; i < NumAssocs; ++i) { 1645 if (!Types[i]) 1646 DefaultIndex = i; 1647 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1648 Types[i]->getType())) 1649 CompatIndices.push_back(i); 1650 } 1651 1652 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1653 // type compatible with at most one of the types named in its generic 1654 // association list." 1655 if (CompatIndices.size() > 1) { 1656 // We strip parens here because the controlling expression is typically 1657 // parenthesized in macro definitions. 1658 ControllingExpr = ControllingExpr->IgnoreParens(); 1659 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1660 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1661 << (unsigned)CompatIndices.size(); 1662 for (unsigned I : CompatIndices) { 1663 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1664 diag::note_compat_assoc) 1665 << Types[I]->getTypeLoc().getSourceRange() 1666 << Types[I]->getType(); 1667 } 1668 return ExprError(); 1669 } 1670 1671 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1672 // its controlling expression shall have type compatible with exactly one of 1673 // the types named in its generic association list." 1674 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1675 // We strip parens here because the controlling expression is typically 1676 // parenthesized in macro definitions. 1677 ControllingExpr = ControllingExpr->IgnoreParens(); 1678 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1679 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1680 return ExprError(); 1681 } 1682 1683 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1684 // type name that is compatible with the type of the controlling expression, 1685 // then the result expression of the generic selection is the expression 1686 // in that generic association. Otherwise, the result expression of the 1687 // generic selection is the expression in the default generic association." 1688 unsigned ResultIndex = 1689 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1690 1691 return GenericSelectionExpr::Create( 1692 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1693 ContainsUnexpandedParameterPack, ResultIndex); 1694 } 1695 1696 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1697 /// location of the token and the offset of the ud-suffix within it. 1698 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1699 unsigned Offset) { 1700 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1701 S.getLangOpts()); 1702 } 1703 1704 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1705 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1706 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1707 IdentifierInfo *UDSuffix, 1708 SourceLocation UDSuffixLoc, 1709 ArrayRef<Expr*> Args, 1710 SourceLocation LitEndLoc) { 1711 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1712 1713 QualType ArgTy[2]; 1714 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1715 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1716 if (ArgTy[ArgIdx]->isArrayType()) 1717 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1718 } 1719 1720 DeclarationName OpName = 1721 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1722 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1723 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1724 1725 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1726 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1727 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1728 /*AllowStringTemplate*/ false, 1729 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1730 return ExprError(); 1731 1732 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1733 } 1734 1735 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1736 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1737 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1738 /// multiple tokens. However, the common case is that StringToks points to one 1739 /// string. 1740 /// 1741 ExprResult 1742 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1743 assert(!StringToks.empty() && "Must have at least one string!"); 1744 1745 StringLiteralParser Literal(StringToks, PP); 1746 if (Literal.hadError) 1747 return ExprError(); 1748 1749 SmallVector<SourceLocation, 4> StringTokLocs; 1750 for (const Token &Tok : StringToks) 1751 StringTokLocs.push_back(Tok.getLocation()); 1752 1753 QualType CharTy = Context.CharTy; 1754 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1755 if (Literal.isWide()) { 1756 CharTy = Context.getWideCharType(); 1757 Kind = StringLiteral::Wide; 1758 } else if (Literal.isUTF8()) { 1759 if (getLangOpts().Char8) 1760 CharTy = Context.Char8Ty; 1761 Kind = StringLiteral::UTF8; 1762 } else if (Literal.isUTF16()) { 1763 CharTy = Context.Char16Ty; 1764 Kind = StringLiteral::UTF16; 1765 } else if (Literal.isUTF32()) { 1766 CharTy = Context.Char32Ty; 1767 Kind = StringLiteral::UTF32; 1768 } else if (Literal.isPascal()) { 1769 CharTy = Context.UnsignedCharTy; 1770 } 1771 1772 // Warn on initializing an array of char from a u8 string literal; this 1773 // becomes ill-formed in C++2a. 1774 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1775 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1776 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1777 1778 // Create removals for all 'u8' prefixes in the string literal(s). This 1779 // ensures C++2a compatibility (but may change the program behavior when 1780 // built by non-Clang compilers for which the execution character set is 1781 // not always UTF-8). 1782 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1783 SourceLocation RemovalDiagLoc; 1784 for (const Token &Tok : StringToks) { 1785 if (Tok.getKind() == tok::utf8_string_literal) { 1786 if (RemovalDiagLoc.isInvalid()) 1787 RemovalDiagLoc = Tok.getLocation(); 1788 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1789 Tok.getLocation(), 1790 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1791 getSourceManager(), getLangOpts()))); 1792 } 1793 } 1794 Diag(RemovalDiagLoc, RemovalDiag); 1795 } 1796 1797 QualType StrTy = 1798 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1799 1800 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1801 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1802 Kind, Literal.Pascal, StrTy, 1803 &StringTokLocs[0], 1804 StringTokLocs.size()); 1805 if (Literal.getUDSuffix().empty()) 1806 return Lit; 1807 1808 // We're building a user-defined literal. 1809 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1810 SourceLocation UDSuffixLoc = 1811 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1812 Literal.getUDSuffixOffset()); 1813 1814 // Make sure we're allowed user-defined literals here. 1815 if (!UDLScope) 1816 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1817 1818 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1819 // operator "" X (str, len) 1820 QualType SizeType = Context.getSizeType(); 1821 1822 DeclarationName OpName = 1823 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1824 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1825 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1826 1827 QualType ArgTy[] = { 1828 Context.getArrayDecayedType(StrTy), SizeType 1829 }; 1830 1831 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1832 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1833 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1834 /*AllowStringTemplate*/ true, 1835 /*DiagnoseMissing*/ true)) { 1836 1837 case LOLR_Cooked: { 1838 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1839 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1840 StringTokLocs[0]); 1841 Expr *Args[] = { Lit, LenArg }; 1842 1843 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1844 } 1845 1846 case LOLR_StringTemplate: { 1847 TemplateArgumentListInfo ExplicitArgs; 1848 1849 unsigned CharBits = Context.getIntWidth(CharTy); 1850 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1851 llvm::APSInt Value(CharBits, CharIsUnsigned); 1852 1853 TemplateArgument TypeArg(CharTy); 1854 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1855 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1856 1857 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1858 Value = Lit->getCodeUnit(I); 1859 TemplateArgument Arg(Context, Value, CharTy); 1860 TemplateArgumentLocInfo ArgInfo; 1861 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1862 } 1863 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1864 &ExplicitArgs); 1865 } 1866 case LOLR_Raw: 1867 case LOLR_Template: 1868 case LOLR_ErrorNoDiagnostic: 1869 llvm_unreachable("unexpected literal operator lookup result"); 1870 case LOLR_Error: 1871 return ExprError(); 1872 } 1873 llvm_unreachable("unexpected literal operator lookup result"); 1874 } 1875 1876 DeclRefExpr * 1877 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1878 SourceLocation Loc, 1879 const CXXScopeSpec *SS) { 1880 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1881 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1882 } 1883 1884 DeclRefExpr * 1885 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1886 const DeclarationNameInfo &NameInfo, 1887 const CXXScopeSpec *SS, NamedDecl *FoundD, 1888 SourceLocation TemplateKWLoc, 1889 const TemplateArgumentListInfo *TemplateArgs) { 1890 NestedNameSpecifierLoc NNS = 1891 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1892 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1893 TemplateArgs); 1894 } 1895 1896 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1897 // A declaration named in an unevaluated operand never constitutes an odr-use. 1898 if (isUnevaluatedContext()) 1899 return NOUR_Unevaluated; 1900 1901 // C++2a [basic.def.odr]p4: 1902 // A variable x whose name appears as a potentially-evaluated expression e 1903 // is odr-used by e unless [...] x is a reference that is usable in 1904 // constant expressions. 1905 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1906 if (VD->getType()->isReferenceType() && 1907 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1908 VD->isUsableInConstantExpressions(Context)) 1909 return NOUR_Constant; 1910 } 1911 1912 // All remaining non-variable cases constitute an odr-use. For variables, we 1913 // need to wait and see how the expression is used. 1914 return NOUR_None; 1915 } 1916 1917 /// BuildDeclRefExpr - Build an expression that references a 1918 /// declaration that does not require a closure capture. 1919 DeclRefExpr * 1920 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1921 const DeclarationNameInfo &NameInfo, 1922 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 1923 SourceLocation TemplateKWLoc, 1924 const TemplateArgumentListInfo *TemplateArgs) { 1925 bool RefersToCapturedVariable = 1926 isa<VarDecl>(D) && 1927 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1928 1929 DeclRefExpr *E = DeclRefExpr::Create( 1930 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 1931 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 1932 MarkDeclRefReferenced(E); 1933 1934 // C++ [except.spec]p17: 1935 // An exception-specification is considered to be needed when: 1936 // - in an expression, the function is the unique lookup result or 1937 // the selected member of a set of overloaded functions. 1938 // 1939 // We delay doing this until after we've built the function reference and 1940 // marked it as used so that: 1941 // a) if the function is defaulted, we get errors from defining it before / 1942 // instead of errors from computing its exception specification, and 1943 // b) if the function is a defaulted comparison, we can use the body we 1944 // build when defining it as input to the exception specification 1945 // computation rather than computing a new body. 1946 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 1947 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 1948 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 1949 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 1950 } 1951 } 1952 1953 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1954 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1955 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1956 getCurFunction()->recordUseOfWeak(E); 1957 1958 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1959 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1960 FD = IFD->getAnonField(); 1961 if (FD) { 1962 UnusedPrivateFields.remove(FD); 1963 // Just in case we're building an illegal pointer-to-member. 1964 if (FD->isBitField()) 1965 E->setObjectKind(OK_BitField); 1966 } 1967 1968 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1969 // designates a bit-field. 1970 if (auto *BD = dyn_cast<BindingDecl>(D)) 1971 if (auto *BE = BD->getBinding()) 1972 E->setObjectKind(BE->getObjectKind()); 1973 1974 return E; 1975 } 1976 1977 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1978 /// possibly a list of template arguments. 1979 /// 1980 /// If this produces template arguments, it is permitted to call 1981 /// DecomposeTemplateName. 1982 /// 1983 /// This actually loses a lot of source location information for 1984 /// non-standard name kinds; we should consider preserving that in 1985 /// some way. 1986 void 1987 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1988 TemplateArgumentListInfo &Buffer, 1989 DeclarationNameInfo &NameInfo, 1990 const TemplateArgumentListInfo *&TemplateArgs) { 1991 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1992 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1993 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1994 1995 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1996 Id.TemplateId->NumArgs); 1997 translateTemplateArguments(TemplateArgsPtr, Buffer); 1998 1999 TemplateName TName = Id.TemplateId->Template.get(); 2000 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2001 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2002 TemplateArgs = &Buffer; 2003 } else { 2004 NameInfo = GetNameFromUnqualifiedId(Id); 2005 TemplateArgs = nullptr; 2006 } 2007 } 2008 2009 static void emitEmptyLookupTypoDiagnostic( 2010 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2011 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2012 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2013 DeclContext *Ctx = 2014 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2015 if (!TC) { 2016 // Emit a special diagnostic for failed member lookups. 2017 // FIXME: computing the declaration context might fail here (?) 2018 if (Ctx) 2019 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2020 << SS.getRange(); 2021 else 2022 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2023 return; 2024 } 2025 2026 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2027 bool DroppedSpecifier = 2028 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2029 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2030 ? diag::note_implicit_param_decl 2031 : diag::note_previous_decl; 2032 if (!Ctx) 2033 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2034 SemaRef.PDiag(NoteID)); 2035 else 2036 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2037 << Typo << Ctx << DroppedSpecifier 2038 << SS.getRange(), 2039 SemaRef.PDiag(NoteID)); 2040 } 2041 2042 /// Diagnose an empty lookup. 2043 /// 2044 /// \return false if new lookup candidates were found 2045 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2046 CorrectionCandidateCallback &CCC, 2047 TemplateArgumentListInfo *ExplicitTemplateArgs, 2048 ArrayRef<Expr *> Args, TypoExpr **Out) { 2049 DeclarationName Name = R.getLookupName(); 2050 2051 unsigned diagnostic = diag::err_undeclared_var_use; 2052 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2053 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2054 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2055 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2056 diagnostic = diag::err_undeclared_use; 2057 diagnostic_suggest = diag::err_undeclared_use_suggest; 2058 } 2059 2060 // If the original lookup was an unqualified lookup, fake an 2061 // unqualified lookup. This is useful when (for example) the 2062 // original lookup would not have found something because it was a 2063 // dependent name. 2064 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2065 while (DC) { 2066 if (isa<CXXRecordDecl>(DC)) { 2067 LookupQualifiedName(R, DC); 2068 2069 if (!R.empty()) { 2070 // Don't give errors about ambiguities in this lookup. 2071 R.suppressDiagnostics(); 2072 2073 // During a default argument instantiation the CurContext points 2074 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2075 // function parameter list, hence add an explicit check. 2076 bool isDefaultArgument = 2077 !CodeSynthesisContexts.empty() && 2078 CodeSynthesisContexts.back().Kind == 2079 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2080 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2081 bool isInstance = CurMethod && 2082 CurMethod->isInstance() && 2083 DC == CurMethod->getParent() && !isDefaultArgument; 2084 2085 // Give a code modification hint to insert 'this->'. 2086 // TODO: fixit for inserting 'Base<T>::' in the other cases. 2087 // Actually quite difficult! 2088 if (getLangOpts().MSVCCompat) 2089 diagnostic = diag::ext_found_via_dependent_bases_lookup; 2090 if (isInstance) { 2091 Diag(R.getNameLoc(), diagnostic) << Name 2092 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2093 CheckCXXThisCapture(R.getNameLoc()); 2094 } else { 2095 Diag(R.getNameLoc(), diagnostic) << Name; 2096 } 2097 2098 // Do we really want to note all of these? 2099 for (NamedDecl *D : R) 2100 Diag(D->getLocation(), diag::note_dependent_var_use); 2101 2102 // Return true if we are inside a default argument instantiation 2103 // and the found name refers to an instance member function, otherwise 2104 // the function calling DiagnoseEmptyLookup will try to create an 2105 // implicit member call and this is wrong for default argument. 2106 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2107 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2108 return true; 2109 } 2110 2111 // Tell the callee to try to recover. 2112 return false; 2113 } 2114 2115 R.clear(); 2116 } 2117 2118 DC = DC->getLookupParent(); 2119 } 2120 2121 // We didn't find anything, so try to correct for a typo. 2122 TypoCorrection Corrected; 2123 if (S && Out) { 2124 SourceLocation TypoLoc = R.getNameLoc(); 2125 assert(!ExplicitTemplateArgs && 2126 "Diagnosing an empty lookup with explicit template args!"); 2127 *Out = CorrectTypoDelayed( 2128 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2129 [=](const TypoCorrection &TC) { 2130 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2131 diagnostic, diagnostic_suggest); 2132 }, 2133 nullptr, CTK_ErrorRecovery); 2134 if (*Out) 2135 return true; 2136 } else if (S && 2137 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2138 S, &SS, CCC, CTK_ErrorRecovery))) { 2139 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2140 bool DroppedSpecifier = 2141 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2142 R.setLookupName(Corrected.getCorrection()); 2143 2144 bool AcceptableWithRecovery = false; 2145 bool AcceptableWithoutRecovery = false; 2146 NamedDecl *ND = Corrected.getFoundDecl(); 2147 if (ND) { 2148 if (Corrected.isOverloaded()) { 2149 OverloadCandidateSet OCS(R.getNameLoc(), 2150 OverloadCandidateSet::CSK_Normal); 2151 OverloadCandidateSet::iterator Best; 2152 for (NamedDecl *CD : Corrected) { 2153 if (FunctionTemplateDecl *FTD = 2154 dyn_cast<FunctionTemplateDecl>(CD)) 2155 AddTemplateOverloadCandidate( 2156 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2157 Args, OCS); 2158 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2159 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2160 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2161 Args, OCS); 2162 } 2163 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2164 case OR_Success: 2165 ND = Best->FoundDecl; 2166 Corrected.setCorrectionDecl(ND); 2167 break; 2168 default: 2169 // FIXME: Arbitrarily pick the first declaration for the note. 2170 Corrected.setCorrectionDecl(ND); 2171 break; 2172 } 2173 } 2174 R.addDecl(ND); 2175 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2176 CXXRecordDecl *Record = nullptr; 2177 if (Corrected.getCorrectionSpecifier()) { 2178 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2179 Record = Ty->getAsCXXRecordDecl(); 2180 } 2181 if (!Record) 2182 Record = cast<CXXRecordDecl>( 2183 ND->getDeclContext()->getRedeclContext()); 2184 R.setNamingClass(Record); 2185 } 2186 2187 auto *UnderlyingND = ND->getUnderlyingDecl(); 2188 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2189 isa<FunctionTemplateDecl>(UnderlyingND); 2190 // FIXME: If we ended up with a typo for a type name or 2191 // Objective-C class name, we're in trouble because the parser 2192 // is in the wrong place to recover. Suggest the typo 2193 // correction, but don't make it a fix-it since we're not going 2194 // to recover well anyway. 2195 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2196 getAsTypeTemplateDecl(UnderlyingND) || 2197 isa<ObjCInterfaceDecl>(UnderlyingND); 2198 } else { 2199 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2200 // because we aren't able to recover. 2201 AcceptableWithoutRecovery = true; 2202 } 2203 2204 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2205 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2206 ? diag::note_implicit_param_decl 2207 : diag::note_previous_decl; 2208 if (SS.isEmpty()) 2209 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2210 PDiag(NoteID), AcceptableWithRecovery); 2211 else 2212 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2213 << Name << computeDeclContext(SS, false) 2214 << DroppedSpecifier << SS.getRange(), 2215 PDiag(NoteID), AcceptableWithRecovery); 2216 2217 // Tell the callee whether to try to recover. 2218 return !AcceptableWithRecovery; 2219 } 2220 } 2221 R.clear(); 2222 2223 // Emit a special diagnostic for failed member lookups. 2224 // FIXME: computing the declaration context might fail here (?) 2225 if (!SS.isEmpty()) { 2226 Diag(R.getNameLoc(), diag::err_no_member) 2227 << Name << computeDeclContext(SS, false) 2228 << SS.getRange(); 2229 return true; 2230 } 2231 2232 // Give up, we can't recover. 2233 Diag(R.getNameLoc(), diagnostic) << Name; 2234 return true; 2235 } 2236 2237 /// In Microsoft mode, if we are inside a template class whose parent class has 2238 /// dependent base classes, and we can't resolve an unqualified identifier, then 2239 /// assume the identifier is a member of a dependent base class. We can only 2240 /// recover successfully in static methods, instance methods, and other contexts 2241 /// where 'this' is available. This doesn't precisely match MSVC's 2242 /// instantiation model, but it's close enough. 2243 static Expr * 2244 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2245 DeclarationNameInfo &NameInfo, 2246 SourceLocation TemplateKWLoc, 2247 const TemplateArgumentListInfo *TemplateArgs) { 2248 // Only try to recover from lookup into dependent bases in static methods or 2249 // contexts where 'this' is available. 2250 QualType ThisType = S.getCurrentThisType(); 2251 const CXXRecordDecl *RD = nullptr; 2252 if (!ThisType.isNull()) 2253 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2254 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2255 RD = MD->getParent(); 2256 if (!RD || !RD->hasAnyDependentBases()) 2257 return nullptr; 2258 2259 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2260 // is available, suggest inserting 'this->' as a fixit. 2261 SourceLocation Loc = NameInfo.getLoc(); 2262 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2263 DB << NameInfo.getName() << RD; 2264 2265 if (!ThisType.isNull()) { 2266 DB << FixItHint::CreateInsertion(Loc, "this->"); 2267 return CXXDependentScopeMemberExpr::Create( 2268 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2269 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2270 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2271 } 2272 2273 // Synthesize a fake NNS that points to the derived class. This will 2274 // perform name lookup during template instantiation. 2275 CXXScopeSpec SS; 2276 auto *NNS = 2277 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2278 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2279 return DependentScopeDeclRefExpr::Create( 2280 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2281 TemplateArgs); 2282 } 2283 2284 ExprResult 2285 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2286 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2287 bool HasTrailingLParen, bool IsAddressOfOperand, 2288 CorrectionCandidateCallback *CCC, 2289 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2290 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2291 "cannot be direct & operand and have a trailing lparen"); 2292 if (SS.isInvalid()) 2293 return ExprError(); 2294 2295 TemplateArgumentListInfo TemplateArgsBuffer; 2296 2297 // Decompose the UnqualifiedId into the following data. 2298 DeclarationNameInfo NameInfo; 2299 const TemplateArgumentListInfo *TemplateArgs; 2300 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2301 2302 DeclarationName Name = NameInfo.getName(); 2303 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2304 SourceLocation NameLoc = NameInfo.getLoc(); 2305 2306 if (II && II->isEditorPlaceholder()) { 2307 // FIXME: When typed placeholders are supported we can create a typed 2308 // placeholder expression node. 2309 return ExprError(); 2310 } 2311 2312 // C++ [temp.dep.expr]p3: 2313 // An id-expression is type-dependent if it contains: 2314 // -- an identifier that was declared with a dependent type, 2315 // (note: handled after lookup) 2316 // -- a template-id that is dependent, 2317 // (note: handled in BuildTemplateIdExpr) 2318 // -- a conversion-function-id that specifies a dependent type, 2319 // -- a nested-name-specifier that contains a class-name that 2320 // names a dependent type. 2321 // Determine whether this is a member of an unknown specialization; 2322 // we need to handle these differently. 2323 bool DependentID = false; 2324 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2325 Name.getCXXNameType()->isDependentType()) { 2326 DependentID = true; 2327 } else if (SS.isSet()) { 2328 if (DeclContext *DC = computeDeclContext(SS, false)) { 2329 if (RequireCompleteDeclContext(SS, DC)) 2330 return ExprError(); 2331 } else { 2332 DependentID = true; 2333 } 2334 } 2335 2336 if (DependentID) 2337 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2338 IsAddressOfOperand, TemplateArgs); 2339 2340 // Perform the required lookup. 2341 LookupResult R(*this, NameInfo, 2342 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2343 ? LookupObjCImplicitSelfParam 2344 : LookupOrdinaryName); 2345 if (TemplateKWLoc.isValid() || TemplateArgs) { 2346 // Lookup the template name again to correctly establish the context in 2347 // which it was found. This is really unfortunate as we already did the 2348 // lookup to determine that it was a template name in the first place. If 2349 // this becomes a performance hit, we can work harder to preserve those 2350 // results until we get here but it's likely not worth it. 2351 bool MemberOfUnknownSpecialization; 2352 AssumedTemplateKind AssumedTemplate; 2353 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2354 MemberOfUnknownSpecialization, TemplateKWLoc, 2355 &AssumedTemplate)) 2356 return ExprError(); 2357 2358 if (MemberOfUnknownSpecialization || 2359 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2360 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2361 IsAddressOfOperand, TemplateArgs); 2362 } else { 2363 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2364 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2365 2366 // If the result might be in a dependent base class, this is a dependent 2367 // id-expression. 2368 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2369 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2370 IsAddressOfOperand, TemplateArgs); 2371 2372 // If this reference is in an Objective-C method, then we need to do 2373 // some special Objective-C lookup, too. 2374 if (IvarLookupFollowUp) { 2375 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2376 if (E.isInvalid()) 2377 return ExprError(); 2378 2379 if (Expr *Ex = E.getAs<Expr>()) 2380 return Ex; 2381 } 2382 } 2383 2384 if (R.isAmbiguous()) 2385 return ExprError(); 2386 2387 // This could be an implicitly declared function reference (legal in C90, 2388 // extension in C99, forbidden in C++). 2389 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2390 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2391 if (D) R.addDecl(D); 2392 } 2393 2394 // Determine whether this name might be a candidate for 2395 // argument-dependent lookup. 2396 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2397 2398 if (R.empty() && !ADL) { 2399 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2400 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2401 TemplateKWLoc, TemplateArgs)) 2402 return E; 2403 } 2404 2405 // Don't diagnose an empty lookup for inline assembly. 2406 if (IsInlineAsmIdentifier) 2407 return ExprError(); 2408 2409 // If this name wasn't predeclared and if this is not a function 2410 // call, diagnose the problem. 2411 TypoExpr *TE = nullptr; 2412 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2413 : nullptr); 2414 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2415 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2416 "Typo correction callback misconfigured"); 2417 if (CCC) { 2418 // Make sure the callback knows what the typo being diagnosed is. 2419 CCC->setTypoName(II); 2420 if (SS.isValid()) 2421 CCC->setTypoNNS(SS.getScopeRep()); 2422 } 2423 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2424 // a template name, but we happen to have always already looked up the name 2425 // before we get here if it must be a template name. 2426 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2427 None, &TE)) { 2428 if (TE && KeywordReplacement) { 2429 auto &State = getTypoExprState(TE); 2430 auto BestTC = State.Consumer->getNextCorrection(); 2431 if (BestTC.isKeyword()) { 2432 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2433 if (State.DiagHandler) 2434 State.DiagHandler(BestTC); 2435 KeywordReplacement->startToken(); 2436 KeywordReplacement->setKind(II->getTokenID()); 2437 KeywordReplacement->setIdentifierInfo(II); 2438 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2439 // Clean up the state associated with the TypoExpr, since it has 2440 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2441 clearDelayedTypo(TE); 2442 // Signal that a correction to a keyword was performed by returning a 2443 // valid-but-null ExprResult. 2444 return (Expr*)nullptr; 2445 } 2446 State.Consumer->resetCorrectionStream(); 2447 } 2448 return TE ? TE : ExprError(); 2449 } 2450 2451 assert(!R.empty() && 2452 "DiagnoseEmptyLookup returned false but added no results"); 2453 2454 // If we found an Objective-C instance variable, let 2455 // LookupInObjCMethod build the appropriate expression to 2456 // reference the ivar. 2457 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2458 R.clear(); 2459 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2460 // In a hopelessly buggy code, Objective-C instance variable 2461 // lookup fails and no expression will be built to reference it. 2462 if (!E.isInvalid() && !E.get()) 2463 return ExprError(); 2464 return E; 2465 } 2466 } 2467 2468 // This is guaranteed from this point on. 2469 assert(!R.empty() || ADL); 2470 2471 // Check whether this might be a C++ implicit instance member access. 2472 // C++ [class.mfct.non-static]p3: 2473 // When an id-expression that is not part of a class member access 2474 // syntax and not used to form a pointer to member is used in the 2475 // body of a non-static member function of class X, if name lookup 2476 // resolves the name in the id-expression to a non-static non-type 2477 // member of some class C, the id-expression is transformed into a 2478 // class member access expression using (*this) as the 2479 // postfix-expression to the left of the . operator. 2480 // 2481 // But we don't actually need to do this for '&' operands if R 2482 // resolved to a function or overloaded function set, because the 2483 // expression is ill-formed if it actually works out to be a 2484 // non-static member function: 2485 // 2486 // C++ [expr.ref]p4: 2487 // Otherwise, if E1.E2 refers to a non-static member function. . . 2488 // [t]he expression can be used only as the left-hand operand of a 2489 // member function call. 2490 // 2491 // There are other safeguards against such uses, but it's important 2492 // to get this right here so that we don't end up making a 2493 // spuriously dependent expression if we're inside a dependent 2494 // instance method. 2495 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2496 bool MightBeImplicitMember; 2497 if (!IsAddressOfOperand) 2498 MightBeImplicitMember = true; 2499 else if (!SS.isEmpty()) 2500 MightBeImplicitMember = false; 2501 else if (R.isOverloadedResult()) 2502 MightBeImplicitMember = false; 2503 else if (R.isUnresolvableResult()) 2504 MightBeImplicitMember = true; 2505 else 2506 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2507 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2508 isa<MSPropertyDecl>(R.getFoundDecl()); 2509 2510 if (MightBeImplicitMember) 2511 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2512 R, TemplateArgs, S); 2513 } 2514 2515 if (TemplateArgs || TemplateKWLoc.isValid()) { 2516 2517 // In C++1y, if this is a variable template id, then check it 2518 // in BuildTemplateIdExpr(). 2519 // The single lookup result must be a variable template declaration. 2520 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2521 Id.TemplateId->Kind == TNK_Var_template) { 2522 assert(R.getAsSingle<VarTemplateDecl>() && 2523 "There should only be one declaration found."); 2524 } 2525 2526 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2527 } 2528 2529 return BuildDeclarationNameExpr(SS, R, ADL); 2530 } 2531 2532 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2533 /// declaration name, generally during template instantiation. 2534 /// There's a large number of things which don't need to be done along 2535 /// this path. 2536 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2537 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2538 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2539 DeclContext *DC = computeDeclContext(SS, false); 2540 if (!DC) 2541 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2542 NameInfo, /*TemplateArgs=*/nullptr); 2543 2544 if (RequireCompleteDeclContext(SS, DC)) 2545 return ExprError(); 2546 2547 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2548 LookupQualifiedName(R, DC); 2549 2550 if (R.isAmbiguous()) 2551 return ExprError(); 2552 2553 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2554 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2555 NameInfo, /*TemplateArgs=*/nullptr); 2556 2557 if (R.empty()) { 2558 Diag(NameInfo.getLoc(), diag::err_no_member) 2559 << NameInfo.getName() << DC << SS.getRange(); 2560 return ExprError(); 2561 } 2562 2563 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2564 // Diagnose a missing typename if this resolved unambiguously to a type in 2565 // a dependent context. If we can recover with a type, downgrade this to 2566 // a warning in Microsoft compatibility mode. 2567 unsigned DiagID = diag::err_typename_missing; 2568 if (RecoveryTSI && getLangOpts().MSVCCompat) 2569 DiagID = diag::ext_typename_missing; 2570 SourceLocation Loc = SS.getBeginLoc(); 2571 auto D = Diag(Loc, DiagID); 2572 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2573 << SourceRange(Loc, NameInfo.getEndLoc()); 2574 2575 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2576 // context. 2577 if (!RecoveryTSI) 2578 return ExprError(); 2579 2580 // Only issue the fixit if we're prepared to recover. 2581 D << FixItHint::CreateInsertion(Loc, "typename "); 2582 2583 // Recover by pretending this was an elaborated type. 2584 QualType Ty = Context.getTypeDeclType(TD); 2585 TypeLocBuilder TLB; 2586 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2587 2588 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2589 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2590 QTL.setElaboratedKeywordLoc(SourceLocation()); 2591 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2592 2593 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2594 2595 return ExprEmpty(); 2596 } 2597 2598 // Defend against this resolving to an implicit member access. We usually 2599 // won't get here if this might be a legitimate a class member (we end up in 2600 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2601 // a pointer-to-member or in an unevaluated context in C++11. 2602 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2603 return BuildPossibleImplicitMemberExpr(SS, 2604 /*TemplateKWLoc=*/SourceLocation(), 2605 R, /*TemplateArgs=*/nullptr, S); 2606 2607 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2608 } 2609 2610 /// The parser has read a name in, and Sema has detected that we're currently 2611 /// inside an ObjC method. Perform some additional checks and determine if we 2612 /// should form a reference to an ivar. 2613 /// 2614 /// Ideally, most of this would be done by lookup, but there's 2615 /// actually quite a lot of extra work involved. 2616 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2617 IdentifierInfo *II) { 2618 SourceLocation Loc = Lookup.getNameLoc(); 2619 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2620 2621 // Check for error condition which is already reported. 2622 if (!CurMethod) 2623 return DeclResult(true); 2624 2625 // There are two cases to handle here. 1) scoped lookup could have failed, 2626 // in which case we should look for an ivar. 2) scoped lookup could have 2627 // found a decl, but that decl is outside the current instance method (i.e. 2628 // a global variable). In these two cases, we do a lookup for an ivar with 2629 // this name, if the lookup sucedes, we replace it our current decl. 2630 2631 // If we're in a class method, we don't normally want to look for 2632 // ivars. But if we don't find anything else, and there's an 2633 // ivar, that's an error. 2634 bool IsClassMethod = CurMethod->isClassMethod(); 2635 2636 bool LookForIvars; 2637 if (Lookup.empty()) 2638 LookForIvars = true; 2639 else if (IsClassMethod) 2640 LookForIvars = false; 2641 else 2642 LookForIvars = (Lookup.isSingleResult() && 2643 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2644 ObjCInterfaceDecl *IFace = nullptr; 2645 if (LookForIvars) { 2646 IFace = CurMethod->getClassInterface(); 2647 ObjCInterfaceDecl *ClassDeclared; 2648 ObjCIvarDecl *IV = nullptr; 2649 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2650 // Diagnose using an ivar in a class method. 2651 if (IsClassMethod) { 2652 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2653 return DeclResult(true); 2654 } 2655 2656 // Diagnose the use of an ivar outside of the declaring class. 2657 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2658 !declaresSameEntity(ClassDeclared, IFace) && 2659 !getLangOpts().DebuggerSupport) 2660 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2661 2662 // Success. 2663 return IV; 2664 } 2665 } else if (CurMethod->isInstanceMethod()) { 2666 // We should warn if a local variable hides an ivar. 2667 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2668 ObjCInterfaceDecl *ClassDeclared; 2669 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2670 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2671 declaresSameEntity(IFace, ClassDeclared)) 2672 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2673 } 2674 } 2675 } else if (Lookup.isSingleResult() && 2676 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2677 // If accessing a stand-alone ivar in a class method, this is an error. 2678 if (const ObjCIvarDecl *IV = 2679 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2680 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2681 return DeclResult(true); 2682 } 2683 } 2684 2685 // Didn't encounter an error, didn't find an ivar. 2686 return DeclResult(false); 2687 } 2688 2689 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2690 ObjCIvarDecl *IV) { 2691 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2692 assert(CurMethod && CurMethod->isInstanceMethod() && 2693 "should not reference ivar from this context"); 2694 2695 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2696 assert(IFace && "should not reference ivar from this context"); 2697 2698 // If we're referencing an invalid decl, just return this as a silent 2699 // error node. The error diagnostic was already emitted on the decl. 2700 if (IV->isInvalidDecl()) 2701 return ExprError(); 2702 2703 // Check if referencing a field with __attribute__((deprecated)). 2704 if (DiagnoseUseOfDecl(IV, Loc)) 2705 return ExprError(); 2706 2707 // FIXME: This should use a new expr for a direct reference, don't 2708 // turn this into Self->ivar, just return a BareIVarExpr or something. 2709 IdentifierInfo &II = Context.Idents.get("self"); 2710 UnqualifiedId SelfName; 2711 SelfName.setIdentifier(&II, SourceLocation()); 2712 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2713 CXXScopeSpec SelfScopeSpec; 2714 SourceLocation TemplateKWLoc; 2715 ExprResult SelfExpr = 2716 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2717 /*HasTrailingLParen=*/false, 2718 /*IsAddressOfOperand=*/false); 2719 if (SelfExpr.isInvalid()) 2720 return ExprError(); 2721 2722 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2723 if (SelfExpr.isInvalid()) 2724 return ExprError(); 2725 2726 MarkAnyDeclReferenced(Loc, IV, true); 2727 2728 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2729 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2730 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2731 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2732 2733 ObjCIvarRefExpr *Result = new (Context) 2734 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2735 IV->getLocation(), SelfExpr.get(), true, true); 2736 2737 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2738 if (!isUnevaluatedContext() && 2739 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2740 getCurFunction()->recordUseOfWeak(Result); 2741 } 2742 if (getLangOpts().ObjCAutoRefCount) 2743 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2744 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2745 2746 return Result; 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. If so, build an expression referencing 2752 /// that ivar. 2753 ExprResult 2754 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2755 IdentifierInfo *II, bool AllowBuiltinCreation) { 2756 // FIXME: Integrate this lookup step into LookupParsedName. 2757 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2758 if (Ivar.isInvalid()) 2759 return ExprError(); 2760 if (Ivar.isUsable()) 2761 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2762 cast<ObjCIvarDecl>(Ivar.get())); 2763 2764 if (Lookup.empty() && II && AllowBuiltinCreation) 2765 LookupBuiltin(Lookup); 2766 2767 // Sentinel value saying that we didn't do anything special. 2768 return ExprResult(false); 2769 } 2770 2771 /// Cast a base object to a member's actual type. 2772 /// 2773 /// Logically this happens in three phases: 2774 /// 2775 /// * First we cast from the base type to the naming class. 2776 /// The naming class is the class into which we were looking 2777 /// when we found the member; it's the qualifier type if a 2778 /// qualifier was provided, and otherwise it's the base type. 2779 /// 2780 /// * Next we cast from the naming class to the declaring class. 2781 /// If the member we found was brought into a class's scope by 2782 /// a using declaration, this is that class; otherwise it's 2783 /// the class declaring the member. 2784 /// 2785 /// * Finally we cast from the declaring class to the "true" 2786 /// declaring class of the member. This conversion does not 2787 /// obey access control. 2788 ExprResult 2789 Sema::PerformObjectMemberConversion(Expr *From, 2790 NestedNameSpecifier *Qualifier, 2791 NamedDecl *FoundDecl, 2792 NamedDecl *Member) { 2793 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2794 if (!RD) 2795 return From; 2796 2797 QualType DestRecordType; 2798 QualType DestType; 2799 QualType FromRecordType; 2800 QualType FromType = From->getType(); 2801 bool PointerConversions = false; 2802 if (isa<FieldDecl>(Member)) { 2803 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2804 auto FromPtrType = FromType->getAs<PointerType>(); 2805 DestRecordType = Context.getAddrSpaceQualType( 2806 DestRecordType, FromPtrType 2807 ? FromType->getPointeeType().getAddressSpace() 2808 : FromType.getAddressSpace()); 2809 2810 if (FromPtrType) { 2811 DestType = Context.getPointerType(DestRecordType); 2812 FromRecordType = FromPtrType->getPointeeType(); 2813 PointerConversions = true; 2814 } else { 2815 DestType = DestRecordType; 2816 FromRecordType = FromType; 2817 } 2818 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2819 if (Method->isStatic()) 2820 return From; 2821 2822 DestType = Method->getThisType(); 2823 DestRecordType = DestType->getPointeeType(); 2824 2825 if (FromType->getAs<PointerType>()) { 2826 FromRecordType = FromType->getPointeeType(); 2827 PointerConversions = true; 2828 } else { 2829 FromRecordType = FromType; 2830 DestType = DestRecordType; 2831 } 2832 2833 LangAS FromAS = FromRecordType.getAddressSpace(); 2834 LangAS DestAS = DestRecordType.getAddressSpace(); 2835 if (FromAS != DestAS) { 2836 QualType FromRecordTypeWithoutAS = 2837 Context.removeAddrSpaceQualType(FromRecordType); 2838 QualType FromTypeWithDestAS = 2839 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2840 if (PointerConversions) 2841 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2842 From = ImpCastExprToType(From, FromTypeWithDestAS, 2843 CK_AddressSpaceConversion, From->getValueKind()) 2844 .get(); 2845 } 2846 } else { 2847 // No conversion necessary. 2848 return From; 2849 } 2850 2851 if (DestType->isDependentType() || FromType->isDependentType()) 2852 return From; 2853 2854 // If the unqualified types are the same, no conversion is necessary. 2855 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2856 return From; 2857 2858 SourceRange FromRange = From->getSourceRange(); 2859 SourceLocation FromLoc = FromRange.getBegin(); 2860 2861 ExprValueKind VK = From->getValueKind(); 2862 2863 // C++ [class.member.lookup]p8: 2864 // [...] Ambiguities can often be resolved by qualifying a name with its 2865 // class name. 2866 // 2867 // If the member was a qualified name and the qualified referred to a 2868 // specific base subobject type, we'll cast to that intermediate type 2869 // first and then to the object in which the member is declared. That allows 2870 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2871 // 2872 // class Base { public: int x; }; 2873 // class Derived1 : public Base { }; 2874 // class Derived2 : public Base { }; 2875 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2876 // 2877 // void VeryDerived::f() { 2878 // x = 17; // error: ambiguous base subobjects 2879 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2880 // } 2881 if (Qualifier && Qualifier->getAsType()) { 2882 QualType QType = QualType(Qualifier->getAsType(), 0); 2883 assert(QType->isRecordType() && "lookup done with non-record type"); 2884 2885 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2886 2887 // In C++98, the qualifier type doesn't actually have to be a base 2888 // type of the object type, in which case we just ignore it. 2889 // Otherwise build the appropriate casts. 2890 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2891 CXXCastPath BasePath; 2892 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2893 FromLoc, FromRange, &BasePath)) 2894 return ExprError(); 2895 2896 if (PointerConversions) 2897 QType = Context.getPointerType(QType); 2898 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2899 VK, &BasePath).get(); 2900 2901 FromType = QType; 2902 FromRecordType = QRecordType; 2903 2904 // If the qualifier type was the same as the destination type, 2905 // we're done. 2906 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2907 return From; 2908 } 2909 } 2910 2911 bool IgnoreAccess = false; 2912 2913 // If we actually found the member through a using declaration, cast 2914 // down to the using declaration's type. 2915 // 2916 // Pointer equality is fine here because only one declaration of a 2917 // class ever has member declarations. 2918 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2919 assert(isa<UsingShadowDecl>(FoundDecl)); 2920 QualType URecordType = Context.getTypeDeclType( 2921 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2922 2923 // We only need to do this if the naming-class to declaring-class 2924 // conversion is non-trivial. 2925 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2926 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2927 CXXCastPath BasePath; 2928 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2929 FromLoc, FromRange, &BasePath)) 2930 return ExprError(); 2931 2932 QualType UType = URecordType; 2933 if (PointerConversions) 2934 UType = Context.getPointerType(UType); 2935 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2936 VK, &BasePath).get(); 2937 FromType = UType; 2938 FromRecordType = URecordType; 2939 } 2940 2941 // We don't do access control for the conversion from the 2942 // declaring class to the true declaring class. 2943 IgnoreAccess = true; 2944 } 2945 2946 CXXCastPath BasePath; 2947 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2948 FromLoc, FromRange, &BasePath, 2949 IgnoreAccess)) 2950 return ExprError(); 2951 2952 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2953 VK, &BasePath); 2954 } 2955 2956 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2957 const LookupResult &R, 2958 bool HasTrailingLParen) { 2959 // Only when used directly as the postfix-expression of a call. 2960 if (!HasTrailingLParen) 2961 return false; 2962 2963 // Never if a scope specifier was provided. 2964 if (SS.isSet()) 2965 return false; 2966 2967 // Only in C++ or ObjC++. 2968 if (!getLangOpts().CPlusPlus) 2969 return false; 2970 2971 // Turn off ADL when we find certain kinds of declarations during 2972 // normal lookup: 2973 for (NamedDecl *D : R) { 2974 // C++0x [basic.lookup.argdep]p3: 2975 // -- a declaration of a class member 2976 // Since using decls preserve this property, we check this on the 2977 // original decl. 2978 if (D->isCXXClassMember()) 2979 return false; 2980 2981 // C++0x [basic.lookup.argdep]p3: 2982 // -- a block-scope function declaration that is not a 2983 // using-declaration 2984 // NOTE: we also trigger this for function templates (in fact, we 2985 // don't check the decl type at all, since all other decl types 2986 // turn off ADL anyway). 2987 if (isa<UsingShadowDecl>(D)) 2988 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2989 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2990 return false; 2991 2992 // C++0x [basic.lookup.argdep]p3: 2993 // -- a declaration that is neither a function or a function 2994 // template 2995 // And also for builtin functions. 2996 if (isa<FunctionDecl>(D)) { 2997 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2998 2999 // But also builtin functions. 3000 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3001 return false; 3002 } else if (!isa<FunctionTemplateDecl>(D)) 3003 return false; 3004 } 3005 3006 return true; 3007 } 3008 3009 3010 /// Diagnoses obvious problems with the use of the given declaration 3011 /// as an expression. This is only actually called for lookups that 3012 /// were not overloaded, and it doesn't promise that the declaration 3013 /// will in fact be used. 3014 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3015 if (D->isInvalidDecl()) 3016 return true; 3017 3018 if (isa<TypedefNameDecl>(D)) { 3019 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3020 return true; 3021 } 3022 3023 if (isa<ObjCInterfaceDecl>(D)) { 3024 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3025 return true; 3026 } 3027 3028 if (isa<NamespaceDecl>(D)) { 3029 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3030 return true; 3031 } 3032 3033 return false; 3034 } 3035 3036 // Certain multiversion types should be treated as overloaded even when there is 3037 // only one result. 3038 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3039 assert(R.isSingleResult() && "Expected only a single result"); 3040 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3041 return FD && 3042 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3043 } 3044 3045 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3046 LookupResult &R, bool NeedsADL, 3047 bool AcceptInvalidDecl) { 3048 // If this is a single, fully-resolved result and we don't need ADL, 3049 // just build an ordinary singleton decl ref. 3050 if (!NeedsADL && R.isSingleResult() && 3051 !R.getAsSingle<FunctionTemplateDecl>() && 3052 !ShouldLookupResultBeMultiVersionOverload(R)) 3053 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3054 R.getRepresentativeDecl(), nullptr, 3055 AcceptInvalidDecl); 3056 3057 // We only need to check the declaration if there's exactly one 3058 // result, because in the overloaded case the results can only be 3059 // functions and function templates. 3060 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3061 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3062 return ExprError(); 3063 3064 // Otherwise, just build an unresolved lookup expression. Suppress 3065 // any lookup-related diagnostics; we'll hash these out later, when 3066 // we've picked a target. 3067 R.suppressDiagnostics(); 3068 3069 UnresolvedLookupExpr *ULE 3070 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3071 SS.getWithLocInContext(Context), 3072 R.getLookupNameInfo(), 3073 NeedsADL, R.isOverloadedResult(), 3074 R.begin(), R.end()); 3075 3076 return ULE; 3077 } 3078 3079 static void 3080 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3081 ValueDecl *var, DeclContext *DC); 3082 3083 /// Complete semantic analysis for a reference to the given declaration. 3084 ExprResult Sema::BuildDeclarationNameExpr( 3085 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3086 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3087 bool AcceptInvalidDecl) { 3088 assert(D && "Cannot refer to a NULL declaration"); 3089 assert(!isa<FunctionTemplateDecl>(D) && 3090 "Cannot refer unambiguously to a function template"); 3091 3092 SourceLocation Loc = NameInfo.getLoc(); 3093 if (CheckDeclInExpr(*this, Loc, D)) 3094 return ExprError(); 3095 3096 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3097 // Specifically diagnose references to class templates that are missing 3098 // a template argument list. 3099 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3100 return ExprError(); 3101 } 3102 3103 // Make sure that we're referring to a value. 3104 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3105 if (!VD) { 3106 Diag(Loc, diag::err_ref_non_value) 3107 << D << SS.getRange(); 3108 Diag(D->getLocation(), diag::note_declared_at); 3109 return ExprError(); 3110 } 3111 3112 // Check whether this declaration can be used. Note that we suppress 3113 // this check when we're going to perform argument-dependent lookup 3114 // on this function name, because this might not be the function 3115 // that overload resolution actually selects. 3116 if (DiagnoseUseOfDecl(VD, Loc)) 3117 return ExprError(); 3118 3119 // Only create DeclRefExpr's for valid Decl's. 3120 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3121 return ExprError(); 3122 3123 // Handle members of anonymous structs and unions. If we got here, 3124 // and the reference is to a class member indirect field, then this 3125 // must be the subject of a pointer-to-member expression. 3126 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3127 if (!indirectField->isCXXClassMember()) 3128 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3129 indirectField); 3130 3131 { 3132 QualType type = VD->getType(); 3133 if (type.isNull()) 3134 return ExprError(); 3135 ExprValueKind valueKind = VK_RValue; 3136 3137 switch (D->getKind()) { 3138 // Ignore all the non-ValueDecl kinds. 3139 #define ABSTRACT_DECL(kind) 3140 #define VALUE(type, base) 3141 #define DECL(type, base) \ 3142 case Decl::type: 3143 #include "clang/AST/DeclNodes.inc" 3144 llvm_unreachable("invalid value decl kind"); 3145 3146 // These shouldn't make it here. 3147 case Decl::ObjCAtDefsField: 3148 llvm_unreachable("forming non-member reference to ivar?"); 3149 3150 // Enum constants are always r-values and never references. 3151 // Unresolved using declarations are dependent. 3152 case Decl::EnumConstant: 3153 case Decl::UnresolvedUsingValue: 3154 case Decl::OMPDeclareReduction: 3155 case Decl::OMPDeclareMapper: 3156 valueKind = VK_RValue; 3157 break; 3158 3159 // Fields and indirect fields that got here must be for 3160 // pointer-to-member expressions; we just call them l-values for 3161 // internal consistency, because this subexpression doesn't really 3162 // exist in the high-level semantics. 3163 case Decl::Field: 3164 case Decl::IndirectField: 3165 case Decl::ObjCIvar: 3166 assert(getLangOpts().CPlusPlus && 3167 "building reference to field in C?"); 3168 3169 // These can't have reference type in well-formed programs, but 3170 // for internal consistency we do this anyway. 3171 type = type.getNonReferenceType(); 3172 valueKind = VK_LValue; 3173 break; 3174 3175 // Non-type template parameters are either l-values or r-values 3176 // depending on the type. 3177 case Decl::NonTypeTemplateParm: { 3178 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3179 type = reftype->getPointeeType(); 3180 valueKind = VK_LValue; // even if the parameter is an r-value reference 3181 break; 3182 } 3183 3184 // For non-references, we need to strip qualifiers just in case 3185 // the template parameter was declared as 'const int' or whatever. 3186 valueKind = VK_RValue; 3187 type = type.getUnqualifiedType(); 3188 break; 3189 } 3190 3191 case Decl::Var: 3192 case Decl::VarTemplateSpecialization: 3193 case Decl::VarTemplatePartialSpecialization: 3194 case Decl::Decomposition: 3195 case Decl::OMPCapturedExpr: 3196 // In C, "extern void blah;" is valid and is an r-value. 3197 if (!getLangOpts().CPlusPlus && 3198 !type.hasQualifiers() && 3199 type->isVoidType()) { 3200 valueKind = VK_RValue; 3201 break; 3202 } 3203 LLVM_FALLTHROUGH; 3204 3205 case Decl::ImplicitParam: 3206 case Decl::ParmVar: { 3207 // These are always l-values. 3208 valueKind = VK_LValue; 3209 type = type.getNonReferenceType(); 3210 3211 // FIXME: Does the addition of const really only apply in 3212 // potentially-evaluated contexts? Since the variable isn't actually 3213 // captured in an unevaluated context, it seems that the answer is no. 3214 if (!isUnevaluatedContext()) { 3215 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3216 if (!CapturedType.isNull()) 3217 type = CapturedType; 3218 } 3219 3220 break; 3221 } 3222 3223 case Decl::Binding: { 3224 // These are always lvalues. 3225 valueKind = VK_LValue; 3226 type = type.getNonReferenceType(); 3227 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3228 // decides how that's supposed to work. 3229 auto *BD = cast<BindingDecl>(VD); 3230 if (BD->getDeclContext() != CurContext) { 3231 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3232 if (DD && DD->hasLocalStorage()) 3233 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3234 } 3235 break; 3236 } 3237 3238 case Decl::Function: { 3239 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3240 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3241 type = Context.BuiltinFnTy; 3242 valueKind = VK_RValue; 3243 break; 3244 } 3245 } 3246 3247 const FunctionType *fty = type->castAs<FunctionType>(); 3248 3249 // If we're referring to a function with an __unknown_anytype 3250 // result type, make the entire expression __unknown_anytype. 3251 if (fty->getReturnType() == Context.UnknownAnyTy) { 3252 type = Context.UnknownAnyTy; 3253 valueKind = VK_RValue; 3254 break; 3255 } 3256 3257 // Functions are l-values in C++. 3258 if (getLangOpts().CPlusPlus) { 3259 valueKind = VK_LValue; 3260 break; 3261 } 3262 3263 // C99 DR 316 says that, if a function type comes from a 3264 // function definition (without a prototype), that type is only 3265 // used for checking compatibility. Therefore, when referencing 3266 // the function, we pretend that we don't have the full function 3267 // type. 3268 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3269 isa<FunctionProtoType>(fty)) 3270 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3271 fty->getExtInfo()); 3272 3273 // Functions are r-values in C. 3274 valueKind = VK_RValue; 3275 break; 3276 } 3277 3278 case Decl::CXXDeductionGuide: 3279 llvm_unreachable("building reference to deduction guide"); 3280 3281 case Decl::MSProperty: 3282 case Decl::MSGuid: 3283 // FIXME: Should MSGuidDecl be subject to capture in OpenMP, 3284 // or duplicated between host and device? 3285 valueKind = VK_LValue; 3286 break; 3287 3288 case Decl::CXXMethod: 3289 // If we're referring to a method with an __unknown_anytype 3290 // result type, make the entire expression __unknown_anytype. 3291 // This should only be possible with a type written directly. 3292 if (const FunctionProtoType *proto 3293 = dyn_cast<FunctionProtoType>(VD->getType())) 3294 if (proto->getReturnType() == Context.UnknownAnyTy) { 3295 type = Context.UnknownAnyTy; 3296 valueKind = VK_RValue; 3297 break; 3298 } 3299 3300 // C++ methods are l-values if static, r-values if non-static. 3301 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3302 valueKind = VK_LValue; 3303 break; 3304 } 3305 LLVM_FALLTHROUGH; 3306 3307 case Decl::CXXConversion: 3308 case Decl::CXXDestructor: 3309 case Decl::CXXConstructor: 3310 valueKind = VK_RValue; 3311 break; 3312 } 3313 3314 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3315 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3316 TemplateArgs); 3317 } 3318 } 3319 3320 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3321 SmallString<32> &Target) { 3322 Target.resize(CharByteWidth * (Source.size() + 1)); 3323 char *ResultPtr = &Target[0]; 3324 const llvm::UTF8 *ErrorPtr; 3325 bool success = 3326 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3327 (void)success; 3328 assert(success); 3329 Target.resize(ResultPtr - &Target[0]); 3330 } 3331 3332 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3333 PredefinedExpr::IdentKind IK) { 3334 // Pick the current block, lambda, captured statement or function. 3335 Decl *currentDecl = nullptr; 3336 if (const BlockScopeInfo *BSI = getCurBlock()) 3337 currentDecl = BSI->TheDecl; 3338 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3339 currentDecl = LSI->CallOperator; 3340 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3341 currentDecl = CSI->TheCapturedDecl; 3342 else 3343 currentDecl = getCurFunctionOrMethodDecl(); 3344 3345 if (!currentDecl) { 3346 Diag(Loc, diag::ext_predef_outside_function); 3347 currentDecl = Context.getTranslationUnitDecl(); 3348 } 3349 3350 QualType ResTy; 3351 StringLiteral *SL = nullptr; 3352 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3353 ResTy = Context.DependentTy; 3354 else { 3355 // Pre-defined identifiers are of type char[x], where x is the length of 3356 // the string. 3357 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3358 unsigned Length = Str.length(); 3359 3360 llvm::APInt LengthI(32, Length + 1); 3361 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3362 ResTy = 3363 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3364 SmallString<32> RawChars; 3365 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3366 Str, RawChars); 3367 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3368 ArrayType::Normal, 3369 /*IndexTypeQuals*/ 0); 3370 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3371 /*Pascal*/ false, ResTy, Loc); 3372 } else { 3373 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3374 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3375 ArrayType::Normal, 3376 /*IndexTypeQuals*/ 0); 3377 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3378 /*Pascal*/ false, ResTy, Loc); 3379 } 3380 } 3381 3382 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3383 } 3384 3385 static std::pair<QualType, StringLiteral *> 3386 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType, 3387 SourceLocation OpLoc, PredefinedExpr::IdentKind K) { 3388 std::pair<QualType, StringLiteral*> Result{{}, nullptr}; 3389 3390 if (OpType->isDependentType()) { 3391 Result.first = Context.DependentTy; 3392 return Result; 3393 } 3394 3395 std::string Str = PredefinedExpr::ComputeName(Context, K, OpType); 3396 llvm::APInt Length(32, Str.length() + 1); 3397 Result.first = 3398 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3399 Result.first = Context.getConstantArrayType( 3400 Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0); 3401 Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3402 /*Pascal*/ false, Result.first, OpLoc); 3403 return Result; 3404 } 3405 3406 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc, 3407 TypeSourceInfo *Operand) { 3408 QualType ResultTy; 3409 StringLiteral *SL; 3410 std::tie(ResultTy, SL) = GetUniqueStableNameInfo( 3411 Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType); 3412 3413 return PredefinedExpr::Create(Context, OpLoc, ResultTy, 3414 PredefinedExpr::UniqueStableNameType, SL, 3415 Operand); 3416 } 3417 3418 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc, 3419 Expr *E) { 3420 QualType ResultTy; 3421 StringLiteral *SL; 3422 std::tie(ResultTy, SL) = GetUniqueStableNameInfo( 3423 Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr); 3424 3425 return PredefinedExpr::Create(Context, OpLoc, ResultTy, 3426 PredefinedExpr::UniqueStableNameExpr, SL, E); 3427 } 3428 3429 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc, 3430 SourceLocation L, SourceLocation R, 3431 ParsedType Ty) { 3432 TypeSourceInfo *TInfo = nullptr; 3433 QualType T = GetTypeFromParser(Ty, &TInfo); 3434 3435 if (T.isNull()) 3436 return ExprError(); 3437 if (!TInfo) 3438 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 3439 3440 return BuildUniqueStableName(OpLoc, TInfo); 3441 } 3442 3443 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc, 3444 SourceLocation L, SourceLocation R, 3445 Expr *E) { 3446 return BuildUniqueStableName(OpLoc, E); 3447 } 3448 3449 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3450 PredefinedExpr::IdentKind IK; 3451 3452 switch (Kind) { 3453 default: llvm_unreachable("Unknown simple primary expr!"); 3454 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3455 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3456 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3457 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3458 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3459 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3460 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3461 } 3462 3463 return BuildPredefinedExpr(Loc, IK); 3464 } 3465 3466 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3467 SmallString<16> CharBuffer; 3468 bool Invalid = false; 3469 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3470 if (Invalid) 3471 return ExprError(); 3472 3473 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3474 PP, Tok.getKind()); 3475 if (Literal.hadError()) 3476 return ExprError(); 3477 3478 QualType Ty; 3479 if (Literal.isWide()) 3480 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3481 else if (Literal.isUTF8() && getLangOpts().Char8) 3482 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3483 else if (Literal.isUTF16()) 3484 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3485 else if (Literal.isUTF32()) 3486 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3487 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3488 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3489 else 3490 Ty = Context.CharTy; // 'x' -> char in C++ 3491 3492 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3493 if (Literal.isWide()) 3494 Kind = CharacterLiteral::Wide; 3495 else if (Literal.isUTF16()) 3496 Kind = CharacterLiteral::UTF16; 3497 else if (Literal.isUTF32()) 3498 Kind = CharacterLiteral::UTF32; 3499 else if (Literal.isUTF8()) 3500 Kind = CharacterLiteral::UTF8; 3501 3502 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3503 Tok.getLocation()); 3504 3505 if (Literal.getUDSuffix().empty()) 3506 return Lit; 3507 3508 // We're building a user-defined literal. 3509 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3510 SourceLocation UDSuffixLoc = 3511 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3512 3513 // Make sure we're allowed user-defined literals here. 3514 if (!UDLScope) 3515 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3516 3517 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3518 // operator "" X (ch) 3519 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3520 Lit, Tok.getLocation()); 3521 } 3522 3523 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3524 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3525 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3526 Context.IntTy, Loc); 3527 } 3528 3529 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3530 QualType Ty, SourceLocation Loc) { 3531 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3532 3533 using llvm::APFloat; 3534 APFloat Val(Format); 3535 3536 APFloat::opStatus result = Literal.GetFloatValue(Val); 3537 3538 // Overflow is always an error, but underflow is only an error if 3539 // we underflowed to zero (APFloat reports denormals as underflow). 3540 if ((result & APFloat::opOverflow) || 3541 ((result & APFloat::opUnderflow) && Val.isZero())) { 3542 unsigned diagnostic; 3543 SmallString<20> buffer; 3544 if (result & APFloat::opOverflow) { 3545 diagnostic = diag::warn_float_overflow; 3546 APFloat::getLargest(Format).toString(buffer); 3547 } else { 3548 diagnostic = diag::warn_float_underflow; 3549 APFloat::getSmallest(Format).toString(buffer); 3550 } 3551 3552 S.Diag(Loc, diagnostic) 3553 << Ty 3554 << StringRef(buffer.data(), buffer.size()); 3555 } 3556 3557 bool isExact = (result == APFloat::opOK); 3558 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3559 } 3560 3561 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3562 assert(E && "Invalid expression"); 3563 3564 if (E->isValueDependent()) 3565 return false; 3566 3567 QualType QT = E->getType(); 3568 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3569 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3570 return true; 3571 } 3572 3573 llvm::APSInt ValueAPS; 3574 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3575 3576 if (R.isInvalid()) 3577 return true; 3578 3579 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3580 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3581 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3582 << ValueAPS.toString(10) << ValueIsPositive; 3583 return true; 3584 } 3585 3586 return false; 3587 } 3588 3589 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3590 // Fast path for a single digit (which is quite common). A single digit 3591 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3592 if (Tok.getLength() == 1) { 3593 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3594 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3595 } 3596 3597 SmallString<128> SpellingBuffer; 3598 // NumericLiteralParser wants to overread by one character. Add padding to 3599 // the buffer in case the token is copied to the buffer. If getSpelling() 3600 // returns a StringRef to the memory buffer, it should have a null char at 3601 // the EOF, so it is also safe. 3602 SpellingBuffer.resize(Tok.getLength() + 1); 3603 3604 // Get the spelling of the token, which eliminates trigraphs, etc. 3605 bool Invalid = false; 3606 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3607 if (Invalid) 3608 return ExprError(); 3609 3610 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3611 if (Literal.hadError) 3612 return ExprError(); 3613 3614 if (Literal.hasUDSuffix()) { 3615 // We're building a user-defined literal. 3616 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3617 SourceLocation UDSuffixLoc = 3618 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3619 3620 // Make sure we're allowed user-defined literals here. 3621 if (!UDLScope) 3622 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3623 3624 QualType CookedTy; 3625 if (Literal.isFloatingLiteral()) { 3626 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3627 // long double, the literal is treated as a call of the form 3628 // operator "" X (f L) 3629 CookedTy = Context.LongDoubleTy; 3630 } else { 3631 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3632 // unsigned long long, the literal is treated as a call of the form 3633 // operator "" X (n ULL) 3634 CookedTy = Context.UnsignedLongLongTy; 3635 } 3636 3637 DeclarationName OpName = 3638 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3639 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3640 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3641 3642 SourceLocation TokLoc = Tok.getLocation(); 3643 3644 // Perform literal operator lookup to determine if we're building a raw 3645 // literal or a cooked one. 3646 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3647 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3648 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3649 /*AllowStringTemplate*/ false, 3650 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3651 case LOLR_ErrorNoDiagnostic: 3652 // Lookup failure for imaginary constants isn't fatal, there's still the 3653 // GNU extension producing _Complex types. 3654 break; 3655 case LOLR_Error: 3656 return ExprError(); 3657 case LOLR_Cooked: { 3658 Expr *Lit; 3659 if (Literal.isFloatingLiteral()) { 3660 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3661 } else { 3662 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3663 if (Literal.GetIntegerValue(ResultVal)) 3664 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3665 << /* Unsigned */ 1; 3666 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3667 Tok.getLocation()); 3668 } 3669 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3670 } 3671 3672 case LOLR_Raw: { 3673 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3674 // literal is treated as a call of the form 3675 // operator "" X ("n") 3676 unsigned Length = Literal.getUDSuffixOffset(); 3677 QualType StrTy = Context.getConstantArrayType( 3678 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3679 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3680 Expr *Lit = StringLiteral::Create( 3681 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3682 /*Pascal*/false, StrTy, &TokLoc, 1); 3683 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3684 } 3685 3686 case LOLR_Template: { 3687 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3688 // template), L is treated as a call fo the form 3689 // operator "" X <'c1', 'c2', ... 'ck'>() 3690 // where n is the source character sequence c1 c2 ... ck. 3691 TemplateArgumentListInfo ExplicitArgs; 3692 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3693 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3694 llvm::APSInt Value(CharBits, CharIsUnsigned); 3695 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3696 Value = TokSpelling[I]; 3697 TemplateArgument Arg(Context, Value, Context.CharTy); 3698 TemplateArgumentLocInfo ArgInfo; 3699 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3700 } 3701 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3702 &ExplicitArgs); 3703 } 3704 case LOLR_StringTemplate: 3705 llvm_unreachable("unexpected literal operator lookup result"); 3706 } 3707 } 3708 3709 Expr *Res; 3710 3711 if (Literal.isFixedPointLiteral()) { 3712 QualType Ty; 3713 3714 if (Literal.isAccum) { 3715 if (Literal.isHalf) { 3716 Ty = Context.ShortAccumTy; 3717 } else if (Literal.isLong) { 3718 Ty = Context.LongAccumTy; 3719 } else { 3720 Ty = Context.AccumTy; 3721 } 3722 } else if (Literal.isFract) { 3723 if (Literal.isHalf) { 3724 Ty = Context.ShortFractTy; 3725 } else if (Literal.isLong) { 3726 Ty = Context.LongFractTy; 3727 } else { 3728 Ty = Context.FractTy; 3729 } 3730 } 3731 3732 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3733 3734 bool isSigned = !Literal.isUnsigned; 3735 unsigned scale = Context.getFixedPointScale(Ty); 3736 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3737 3738 llvm::APInt Val(bit_width, 0, isSigned); 3739 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3740 bool ValIsZero = Val.isNullValue() && !Overflowed; 3741 3742 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3743 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3744 // Clause 6.4.4 - The value of a constant shall be in the range of 3745 // representable values for its type, with exception for constants of a 3746 // fract type with a value of exactly 1; such a constant shall denote 3747 // the maximal value for the type. 3748 --Val; 3749 else if (Val.ugt(MaxVal) || Overflowed) 3750 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3751 3752 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3753 Tok.getLocation(), scale); 3754 } else if (Literal.isFloatingLiteral()) { 3755 QualType Ty; 3756 if (Literal.isHalf){ 3757 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3758 Ty = Context.HalfTy; 3759 else { 3760 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3761 return ExprError(); 3762 } 3763 } else if (Literal.isFloat) 3764 Ty = Context.FloatTy; 3765 else if (Literal.isLong) 3766 Ty = Context.LongDoubleTy; 3767 else if (Literal.isFloat16) 3768 Ty = Context.Float16Ty; 3769 else if (Literal.isFloat128) 3770 Ty = Context.Float128Ty; 3771 else 3772 Ty = Context.DoubleTy; 3773 3774 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3775 3776 if (Ty == Context.DoubleTy) { 3777 if (getLangOpts().SinglePrecisionConstants) { 3778 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3779 if (BTy->getKind() != BuiltinType::Float) { 3780 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3781 } 3782 } else if (getLangOpts().OpenCL && 3783 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3784 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3785 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3786 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3787 } 3788 } 3789 } else if (!Literal.isIntegerLiteral()) { 3790 return ExprError(); 3791 } else { 3792 QualType Ty; 3793 3794 // 'long long' is a C99 or C++11 feature. 3795 if (!getLangOpts().C99 && Literal.isLongLong) { 3796 if (getLangOpts().CPlusPlus) 3797 Diag(Tok.getLocation(), 3798 getLangOpts().CPlusPlus11 ? 3799 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3800 else 3801 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3802 } 3803 3804 // Get the value in the widest-possible width. 3805 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3806 llvm::APInt ResultVal(MaxWidth, 0); 3807 3808 if (Literal.GetIntegerValue(ResultVal)) { 3809 // If this value didn't fit into uintmax_t, error and force to ull. 3810 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3811 << /* Unsigned */ 1; 3812 Ty = Context.UnsignedLongLongTy; 3813 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3814 "long long is not intmax_t?"); 3815 } else { 3816 // If this value fits into a ULL, try to figure out what else it fits into 3817 // according to the rules of C99 6.4.4.1p5. 3818 3819 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3820 // be an unsigned int. 3821 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3822 3823 // Check from smallest to largest, picking the smallest type we can. 3824 unsigned Width = 0; 3825 3826 // Microsoft specific integer suffixes are explicitly sized. 3827 if (Literal.MicrosoftInteger) { 3828 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3829 Width = 8; 3830 Ty = Context.CharTy; 3831 } else { 3832 Width = Literal.MicrosoftInteger; 3833 Ty = Context.getIntTypeForBitwidth(Width, 3834 /*Signed=*/!Literal.isUnsigned); 3835 } 3836 } 3837 3838 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3839 // Are int/unsigned possibilities? 3840 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3841 3842 // Does it fit in a unsigned int? 3843 if (ResultVal.isIntN(IntSize)) { 3844 // Does it fit in a signed int? 3845 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3846 Ty = Context.IntTy; 3847 else if (AllowUnsigned) 3848 Ty = Context.UnsignedIntTy; 3849 Width = IntSize; 3850 } 3851 } 3852 3853 // Are long/unsigned long possibilities? 3854 if (Ty.isNull() && !Literal.isLongLong) { 3855 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3856 3857 // Does it fit in a unsigned long? 3858 if (ResultVal.isIntN(LongSize)) { 3859 // Does it fit in a signed long? 3860 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3861 Ty = Context.LongTy; 3862 else if (AllowUnsigned) 3863 Ty = Context.UnsignedLongTy; 3864 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3865 // is compatible. 3866 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3867 const unsigned LongLongSize = 3868 Context.getTargetInfo().getLongLongWidth(); 3869 Diag(Tok.getLocation(), 3870 getLangOpts().CPlusPlus 3871 ? Literal.isLong 3872 ? diag::warn_old_implicitly_unsigned_long_cxx 3873 : /*C++98 UB*/ diag:: 3874 ext_old_implicitly_unsigned_long_cxx 3875 : diag::warn_old_implicitly_unsigned_long) 3876 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3877 : /*will be ill-formed*/ 1); 3878 Ty = Context.UnsignedLongTy; 3879 } 3880 Width = LongSize; 3881 } 3882 } 3883 3884 // Check long long if needed. 3885 if (Ty.isNull()) { 3886 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3887 3888 // Does it fit in a unsigned long long? 3889 if (ResultVal.isIntN(LongLongSize)) { 3890 // Does it fit in a signed long long? 3891 // To be compatible with MSVC, hex integer literals ending with the 3892 // LL or i64 suffix are always signed in Microsoft mode. 3893 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3894 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3895 Ty = Context.LongLongTy; 3896 else if (AllowUnsigned) 3897 Ty = Context.UnsignedLongLongTy; 3898 Width = LongLongSize; 3899 } 3900 } 3901 3902 // If we still couldn't decide a type, we probably have something that 3903 // does not fit in a signed long long, but has no U suffix. 3904 if (Ty.isNull()) { 3905 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3906 Ty = Context.UnsignedLongLongTy; 3907 Width = Context.getTargetInfo().getLongLongWidth(); 3908 } 3909 3910 if (ResultVal.getBitWidth() != Width) 3911 ResultVal = ResultVal.trunc(Width); 3912 } 3913 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3914 } 3915 3916 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3917 if (Literal.isImaginary) { 3918 Res = new (Context) ImaginaryLiteral(Res, 3919 Context.getComplexType(Res->getType())); 3920 3921 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3922 } 3923 return Res; 3924 } 3925 3926 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3927 assert(E && "ActOnParenExpr() missing expr"); 3928 return new (Context) ParenExpr(L, R, E); 3929 } 3930 3931 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3932 SourceLocation Loc, 3933 SourceRange ArgRange) { 3934 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3935 // scalar or vector data type argument..." 3936 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3937 // type (C99 6.2.5p18) or void. 3938 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3939 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3940 << T << ArgRange; 3941 return true; 3942 } 3943 3944 assert((T->isVoidType() || !T->isIncompleteType()) && 3945 "Scalar types should always be complete"); 3946 return false; 3947 } 3948 3949 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3950 SourceLocation Loc, 3951 SourceRange ArgRange, 3952 UnaryExprOrTypeTrait TraitKind) { 3953 // Invalid types must be hard errors for SFINAE in C++. 3954 if (S.LangOpts.CPlusPlus) 3955 return true; 3956 3957 // C99 6.5.3.4p1: 3958 if (T->isFunctionType() && 3959 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3960 TraitKind == UETT_PreferredAlignOf)) { 3961 // sizeof(function)/alignof(function) is allowed as an extension. 3962 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3963 << TraitKind << ArgRange; 3964 return false; 3965 } 3966 3967 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3968 // this is an error (OpenCL v1.1 s6.3.k) 3969 if (T->isVoidType()) { 3970 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3971 : diag::ext_sizeof_alignof_void_type; 3972 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3973 return false; 3974 } 3975 3976 return true; 3977 } 3978 3979 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3980 SourceLocation Loc, 3981 SourceRange ArgRange, 3982 UnaryExprOrTypeTrait TraitKind) { 3983 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3984 // runtime doesn't allow it. 3985 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3986 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3987 << T << (TraitKind == UETT_SizeOf) 3988 << ArgRange; 3989 return true; 3990 } 3991 3992 return false; 3993 } 3994 3995 /// Check whether E is a pointer from a decayed array type (the decayed 3996 /// pointer type is equal to T) and emit a warning if it is. 3997 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3998 Expr *E) { 3999 // Don't warn if the operation changed the type. 4000 if (T != E->getType()) 4001 return; 4002 4003 // Now look for array decays. 4004 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4005 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4006 return; 4007 4008 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4009 << ICE->getType() 4010 << ICE->getSubExpr()->getType(); 4011 } 4012 4013 /// Check the constraints on expression operands to unary type expression 4014 /// and type traits. 4015 /// 4016 /// Completes any types necessary and validates the constraints on the operand 4017 /// expression. The logic mostly mirrors the type-based overload, but may modify 4018 /// the expression as it completes the type for that expression through template 4019 /// instantiation, etc. 4020 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4021 UnaryExprOrTypeTrait ExprKind) { 4022 QualType ExprTy = E->getType(); 4023 assert(!ExprTy->isReferenceType()); 4024 4025 bool IsUnevaluatedOperand = 4026 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4027 ExprKind == UETT_PreferredAlignOf); 4028 if (IsUnevaluatedOperand) { 4029 ExprResult Result = CheckUnevaluatedOperand(E); 4030 if (Result.isInvalid()) 4031 return true; 4032 E = Result.get(); 4033 } 4034 4035 if (ExprKind == UETT_VecStep) 4036 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4037 E->getSourceRange()); 4038 4039 // Whitelist some types as extensions 4040 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4041 E->getSourceRange(), ExprKind)) 4042 return false; 4043 4044 // 'alignof' applied to an expression only requires the base element type of 4045 // the expression to be complete. 'sizeof' requires the expression's type to 4046 // be complete (and will attempt to complete it if it's an array of unknown 4047 // bound). 4048 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4049 if (RequireCompleteSizedType( 4050 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4051 diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind, 4052 E->getSourceRange())) 4053 return true; 4054 } else { 4055 if (RequireCompleteSizedExprType( 4056 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind, 4057 E->getSourceRange())) 4058 return true; 4059 } 4060 4061 // Completing the expression's type may have changed it. 4062 ExprTy = E->getType(); 4063 assert(!ExprTy->isReferenceType()); 4064 4065 if (ExprTy->isFunctionType()) { 4066 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4067 << ExprKind << E->getSourceRange(); 4068 return true; 4069 } 4070 4071 // The operand for sizeof and alignof is in an unevaluated expression context, 4072 // so side effects could result in unintended consequences. 4073 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4074 E->HasSideEffects(Context, false)) 4075 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4076 4077 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4078 E->getSourceRange(), ExprKind)) 4079 return true; 4080 4081 if (ExprKind == UETT_SizeOf) { 4082 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4083 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4084 QualType OType = PVD->getOriginalType(); 4085 QualType Type = PVD->getType(); 4086 if (Type->isPointerType() && OType->isArrayType()) { 4087 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4088 << Type << OType; 4089 Diag(PVD->getLocation(), diag::note_declared_at); 4090 } 4091 } 4092 } 4093 4094 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4095 // decays into a pointer and returns an unintended result. This is most 4096 // likely a typo for "sizeof(array) op x". 4097 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4098 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4099 BO->getLHS()); 4100 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4101 BO->getRHS()); 4102 } 4103 } 4104 4105 return false; 4106 } 4107 4108 /// Check the constraints on operands to unary expression and type 4109 /// traits. 4110 /// 4111 /// This will complete any types necessary, and validate the various constraints 4112 /// on those operands. 4113 /// 4114 /// The UsualUnaryConversions() function is *not* called by this routine. 4115 /// C99 6.3.2.1p[2-4] all state: 4116 /// Except when it is the operand of the sizeof operator ... 4117 /// 4118 /// C++ [expr.sizeof]p4 4119 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4120 /// standard conversions are not applied to the operand of sizeof. 4121 /// 4122 /// This policy is followed for all of the unary trait expressions. 4123 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4124 SourceLocation OpLoc, 4125 SourceRange ExprRange, 4126 UnaryExprOrTypeTrait ExprKind) { 4127 if (ExprType->isDependentType()) 4128 return false; 4129 4130 // C++ [expr.sizeof]p2: 4131 // When applied to a reference or a reference type, the result 4132 // is the size of the referenced type. 4133 // C++11 [expr.alignof]p3: 4134 // When alignof is applied to a reference type, the result 4135 // shall be the alignment of the referenced type. 4136 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4137 ExprType = Ref->getPointeeType(); 4138 4139 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4140 // When alignof or _Alignof is applied to an array type, the result 4141 // is the alignment of the element type. 4142 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4143 ExprKind == UETT_OpenMPRequiredSimdAlign) 4144 ExprType = Context.getBaseElementType(ExprType); 4145 4146 if (ExprKind == UETT_VecStep) 4147 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4148 4149 // Whitelist some types as extensions 4150 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4151 ExprKind)) 4152 return false; 4153 4154 if (RequireCompleteSizedType( 4155 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4156 ExprKind, ExprRange)) 4157 return true; 4158 4159 if (ExprType->isFunctionType()) { 4160 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4161 << ExprKind << ExprRange; 4162 return true; 4163 } 4164 4165 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4166 ExprKind)) 4167 return true; 4168 4169 return false; 4170 } 4171 4172 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4173 // Cannot know anything else if the expression is dependent. 4174 if (E->isTypeDependent()) 4175 return false; 4176 4177 if (E->getObjectKind() == OK_BitField) { 4178 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4179 << 1 << E->getSourceRange(); 4180 return true; 4181 } 4182 4183 ValueDecl *D = nullptr; 4184 Expr *Inner = E->IgnoreParens(); 4185 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4186 D = DRE->getDecl(); 4187 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4188 D = ME->getMemberDecl(); 4189 } 4190 4191 // If it's a field, require the containing struct to have a 4192 // complete definition so that we can compute the layout. 4193 // 4194 // This can happen in C++11 onwards, either by naming the member 4195 // in a way that is not transformed into a member access expression 4196 // (in an unevaluated operand, for instance), or by naming the member 4197 // in a trailing-return-type. 4198 // 4199 // For the record, since __alignof__ on expressions is a GCC 4200 // extension, GCC seems to permit this but always gives the 4201 // nonsensical answer 0. 4202 // 4203 // We don't really need the layout here --- we could instead just 4204 // directly check for all the appropriate alignment-lowing 4205 // attributes --- but that would require duplicating a lot of 4206 // logic that just isn't worth duplicating for such a marginal 4207 // use-case. 4208 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4209 // Fast path this check, since we at least know the record has a 4210 // definition if we can find a member of it. 4211 if (!FD->getParent()->isCompleteDefinition()) { 4212 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4213 << E->getSourceRange(); 4214 return true; 4215 } 4216 4217 // Otherwise, if it's a field, and the field doesn't have 4218 // reference type, then it must have a complete type (or be a 4219 // flexible array member, which we explicitly want to 4220 // white-list anyway), which makes the following checks trivial. 4221 if (!FD->getType()->isReferenceType()) 4222 return false; 4223 } 4224 4225 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4226 } 4227 4228 bool Sema::CheckVecStepExpr(Expr *E) { 4229 E = E->IgnoreParens(); 4230 4231 // Cannot know anything else if the expression is dependent. 4232 if (E->isTypeDependent()) 4233 return false; 4234 4235 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4236 } 4237 4238 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4239 CapturingScopeInfo *CSI) { 4240 assert(T->isVariablyModifiedType()); 4241 assert(CSI != nullptr); 4242 4243 // We're going to walk down into the type and look for VLA expressions. 4244 do { 4245 const Type *Ty = T.getTypePtr(); 4246 switch (Ty->getTypeClass()) { 4247 #define TYPE(Class, Base) 4248 #define ABSTRACT_TYPE(Class, Base) 4249 #define NON_CANONICAL_TYPE(Class, Base) 4250 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4251 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4252 #include "clang/AST/TypeNodes.inc" 4253 T = QualType(); 4254 break; 4255 // These types are never variably-modified. 4256 case Type::Builtin: 4257 case Type::Complex: 4258 case Type::Vector: 4259 case Type::ExtVector: 4260 case Type::Record: 4261 case Type::Enum: 4262 case Type::Elaborated: 4263 case Type::TemplateSpecialization: 4264 case Type::ObjCObject: 4265 case Type::ObjCInterface: 4266 case Type::ObjCObjectPointer: 4267 case Type::ObjCTypeParam: 4268 case Type::Pipe: 4269 case Type::ExtInt: 4270 llvm_unreachable("type class is never variably-modified!"); 4271 case Type::Adjusted: 4272 T = cast<AdjustedType>(Ty)->getOriginalType(); 4273 break; 4274 case Type::Decayed: 4275 T = cast<DecayedType>(Ty)->getPointeeType(); 4276 break; 4277 case Type::Pointer: 4278 T = cast<PointerType>(Ty)->getPointeeType(); 4279 break; 4280 case Type::BlockPointer: 4281 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4282 break; 4283 case Type::LValueReference: 4284 case Type::RValueReference: 4285 T = cast<ReferenceType>(Ty)->getPointeeType(); 4286 break; 4287 case Type::MemberPointer: 4288 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4289 break; 4290 case Type::ConstantArray: 4291 case Type::IncompleteArray: 4292 // Losing element qualification here is fine. 4293 T = cast<ArrayType>(Ty)->getElementType(); 4294 break; 4295 case Type::VariableArray: { 4296 // Losing element qualification here is fine. 4297 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4298 4299 // Unknown size indication requires no size computation. 4300 // Otherwise, evaluate and record it. 4301 auto Size = VAT->getSizeExpr(); 4302 if (Size && !CSI->isVLATypeCaptured(VAT) && 4303 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4304 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4305 4306 T = VAT->getElementType(); 4307 break; 4308 } 4309 case Type::FunctionProto: 4310 case Type::FunctionNoProto: 4311 T = cast<FunctionType>(Ty)->getReturnType(); 4312 break; 4313 case Type::Paren: 4314 case Type::TypeOf: 4315 case Type::UnaryTransform: 4316 case Type::Attributed: 4317 case Type::SubstTemplateTypeParm: 4318 case Type::PackExpansion: 4319 case Type::MacroQualified: 4320 // Keep walking after single level desugaring. 4321 T = T.getSingleStepDesugaredType(Context); 4322 break; 4323 case Type::Typedef: 4324 T = cast<TypedefType>(Ty)->desugar(); 4325 break; 4326 case Type::Decltype: 4327 T = cast<DecltypeType>(Ty)->desugar(); 4328 break; 4329 case Type::Auto: 4330 case Type::DeducedTemplateSpecialization: 4331 T = cast<DeducedType>(Ty)->getDeducedType(); 4332 break; 4333 case Type::TypeOfExpr: 4334 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4335 break; 4336 case Type::Atomic: 4337 T = cast<AtomicType>(Ty)->getValueType(); 4338 break; 4339 } 4340 } while (!T.isNull() && T->isVariablyModifiedType()); 4341 } 4342 4343 /// Build a sizeof or alignof expression given a type operand. 4344 ExprResult 4345 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4346 SourceLocation OpLoc, 4347 UnaryExprOrTypeTrait ExprKind, 4348 SourceRange R) { 4349 if (!TInfo) 4350 return ExprError(); 4351 4352 QualType T = TInfo->getType(); 4353 4354 if (!T->isDependentType() && 4355 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4356 return ExprError(); 4357 4358 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4359 if (auto *TT = T->getAs<TypedefType>()) { 4360 for (auto I = FunctionScopes.rbegin(), 4361 E = std::prev(FunctionScopes.rend()); 4362 I != E; ++I) { 4363 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4364 if (CSI == nullptr) 4365 break; 4366 DeclContext *DC = nullptr; 4367 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4368 DC = LSI->CallOperator; 4369 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4370 DC = CRSI->TheCapturedDecl; 4371 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4372 DC = BSI->TheDecl; 4373 if (DC) { 4374 if (DC->containsDecl(TT->getDecl())) 4375 break; 4376 captureVariablyModifiedType(Context, T, CSI); 4377 } 4378 } 4379 } 4380 } 4381 4382 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4383 return new (Context) UnaryExprOrTypeTraitExpr( 4384 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4385 } 4386 4387 /// Build a sizeof or alignof expression given an expression 4388 /// operand. 4389 ExprResult 4390 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4391 UnaryExprOrTypeTrait ExprKind) { 4392 ExprResult PE = CheckPlaceholderExpr(E); 4393 if (PE.isInvalid()) 4394 return ExprError(); 4395 4396 E = PE.get(); 4397 4398 // Verify that the operand is valid. 4399 bool isInvalid = false; 4400 if (E->isTypeDependent()) { 4401 // Delay type-checking for type-dependent expressions. 4402 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4403 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4404 } else if (ExprKind == UETT_VecStep) { 4405 isInvalid = CheckVecStepExpr(E); 4406 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4407 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4408 isInvalid = true; 4409 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4410 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4411 isInvalid = true; 4412 } else { 4413 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4414 } 4415 4416 if (isInvalid) 4417 return ExprError(); 4418 4419 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4420 PE = TransformToPotentiallyEvaluated(E); 4421 if (PE.isInvalid()) return ExprError(); 4422 E = PE.get(); 4423 } 4424 4425 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4426 return new (Context) UnaryExprOrTypeTraitExpr( 4427 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4428 } 4429 4430 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4431 /// expr and the same for @c alignof and @c __alignof 4432 /// Note that the ArgRange is invalid if isType is false. 4433 ExprResult 4434 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4435 UnaryExprOrTypeTrait ExprKind, bool IsType, 4436 void *TyOrEx, SourceRange ArgRange) { 4437 // If error parsing type, ignore. 4438 if (!TyOrEx) return ExprError(); 4439 4440 if (IsType) { 4441 TypeSourceInfo *TInfo; 4442 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4443 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4444 } 4445 4446 Expr *ArgEx = (Expr *)TyOrEx; 4447 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4448 return Result; 4449 } 4450 4451 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4452 bool IsReal) { 4453 if (V.get()->isTypeDependent()) 4454 return S.Context.DependentTy; 4455 4456 // _Real and _Imag are only l-values for normal l-values. 4457 if (V.get()->getObjectKind() != OK_Ordinary) { 4458 V = S.DefaultLvalueConversion(V.get()); 4459 if (V.isInvalid()) 4460 return QualType(); 4461 } 4462 4463 // These operators return the element type of a complex type. 4464 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4465 return CT->getElementType(); 4466 4467 // Otherwise they pass through real integer and floating point types here. 4468 if (V.get()->getType()->isArithmeticType()) 4469 return V.get()->getType(); 4470 4471 // Test for placeholders. 4472 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4473 if (PR.isInvalid()) return QualType(); 4474 if (PR.get() != V.get()) { 4475 V = PR; 4476 return CheckRealImagOperand(S, V, Loc, IsReal); 4477 } 4478 4479 // Reject anything else. 4480 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4481 << (IsReal ? "__real" : "__imag"); 4482 return QualType(); 4483 } 4484 4485 4486 4487 ExprResult 4488 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4489 tok::TokenKind Kind, Expr *Input) { 4490 UnaryOperatorKind Opc; 4491 switch (Kind) { 4492 default: llvm_unreachable("Unknown unary op!"); 4493 case tok::plusplus: Opc = UO_PostInc; break; 4494 case tok::minusminus: Opc = UO_PostDec; break; 4495 } 4496 4497 // Since this might is a postfix expression, get rid of ParenListExprs. 4498 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4499 if (Result.isInvalid()) return ExprError(); 4500 Input = Result.get(); 4501 4502 return BuildUnaryOp(S, OpLoc, Opc, Input); 4503 } 4504 4505 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4506 /// 4507 /// \return true on error 4508 static bool checkArithmeticOnObjCPointer(Sema &S, 4509 SourceLocation opLoc, 4510 Expr *op) { 4511 assert(op->getType()->isObjCObjectPointerType()); 4512 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4513 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4514 return false; 4515 4516 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4517 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4518 << op->getSourceRange(); 4519 return true; 4520 } 4521 4522 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4523 auto *BaseNoParens = Base->IgnoreParens(); 4524 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4525 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4526 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4527 } 4528 4529 ExprResult 4530 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4531 Expr *idx, SourceLocation rbLoc) { 4532 if (base && !base->getType().isNull() && 4533 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4534 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4535 /*Length=*/nullptr, rbLoc); 4536 4537 // Since this might be a postfix expression, get rid of ParenListExprs. 4538 if (isa<ParenListExpr>(base)) { 4539 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4540 if (result.isInvalid()) return ExprError(); 4541 base = result.get(); 4542 } 4543 4544 // A comma-expression as the index is deprecated in C++2a onwards. 4545 if (getLangOpts().CPlusPlus20 && 4546 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4547 (isa<CXXOperatorCallExpr>(idx) && 4548 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4549 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4550 << SourceRange(base->getBeginLoc(), rbLoc); 4551 } 4552 4553 // Handle any non-overload placeholder types in the base and index 4554 // expressions. We can't handle overloads here because the other 4555 // operand might be an overloadable type, in which case the overload 4556 // resolution for the operator overload should get the first crack 4557 // at the overload. 4558 bool IsMSPropertySubscript = false; 4559 if (base->getType()->isNonOverloadPlaceholderType()) { 4560 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4561 if (!IsMSPropertySubscript) { 4562 ExprResult result = CheckPlaceholderExpr(base); 4563 if (result.isInvalid()) 4564 return ExprError(); 4565 base = result.get(); 4566 } 4567 } 4568 if (idx->getType()->isNonOverloadPlaceholderType()) { 4569 ExprResult result = CheckPlaceholderExpr(idx); 4570 if (result.isInvalid()) return ExprError(); 4571 idx = result.get(); 4572 } 4573 4574 // Build an unanalyzed expression if either operand is type-dependent. 4575 if (getLangOpts().CPlusPlus && 4576 (base->isTypeDependent() || idx->isTypeDependent())) { 4577 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4578 VK_LValue, OK_Ordinary, rbLoc); 4579 } 4580 4581 // MSDN, property (C++) 4582 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4583 // This attribute can also be used in the declaration of an empty array in a 4584 // class or structure definition. For example: 4585 // __declspec(property(get=GetX, put=PutX)) int x[]; 4586 // The above statement indicates that x[] can be used with one or more array 4587 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4588 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4589 if (IsMSPropertySubscript) { 4590 // Build MS property subscript expression if base is MS property reference 4591 // or MS property subscript. 4592 return new (Context) MSPropertySubscriptExpr( 4593 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4594 } 4595 4596 // Use C++ overloaded-operator rules if either operand has record 4597 // type. The spec says to do this if either type is *overloadable*, 4598 // but enum types can't declare subscript operators or conversion 4599 // operators, so there's nothing interesting for overload resolution 4600 // to do if there aren't any record types involved. 4601 // 4602 // ObjC pointers have their own subscripting logic that is not tied 4603 // to overload resolution and so should not take this path. 4604 if (getLangOpts().CPlusPlus && 4605 (base->getType()->isRecordType() || 4606 (!base->getType()->isObjCObjectPointerType() && 4607 idx->getType()->isRecordType()))) { 4608 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4609 } 4610 4611 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4612 4613 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4614 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4615 4616 return Res; 4617 } 4618 4619 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4620 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4621 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4622 4623 // For expressions like `&(*s).b`, the base is recorded and what should be 4624 // checked. 4625 const MemberExpr *Member = nullptr; 4626 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4627 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4628 4629 LastRecord.PossibleDerefs.erase(StrippedExpr); 4630 } 4631 4632 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4633 QualType ResultTy = E->getType(); 4634 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4635 4636 // Bail if the element is an array since it is not memory access. 4637 if (isa<ArrayType>(ResultTy)) 4638 return; 4639 4640 if (ResultTy->hasAttr(attr::NoDeref)) { 4641 LastRecord.PossibleDerefs.insert(E); 4642 return; 4643 } 4644 4645 // Check if the base type is a pointer to a member access of a struct 4646 // marked with noderef. 4647 const Expr *Base = E->getBase(); 4648 QualType BaseTy = Base->getType(); 4649 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4650 // Not a pointer access 4651 return; 4652 4653 const MemberExpr *Member = nullptr; 4654 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4655 Member->isArrow()) 4656 Base = Member->getBase(); 4657 4658 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4659 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4660 LastRecord.PossibleDerefs.insert(E); 4661 } 4662 } 4663 4664 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4665 Expr *LowerBound, 4666 SourceLocation ColonLoc, Expr *Length, 4667 SourceLocation RBLoc) { 4668 if (Base->getType()->isPlaceholderType() && 4669 !Base->getType()->isSpecificPlaceholderType( 4670 BuiltinType::OMPArraySection)) { 4671 ExprResult Result = CheckPlaceholderExpr(Base); 4672 if (Result.isInvalid()) 4673 return ExprError(); 4674 Base = Result.get(); 4675 } 4676 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4677 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4678 if (Result.isInvalid()) 4679 return ExprError(); 4680 Result = DefaultLvalueConversion(Result.get()); 4681 if (Result.isInvalid()) 4682 return ExprError(); 4683 LowerBound = Result.get(); 4684 } 4685 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4686 ExprResult Result = CheckPlaceholderExpr(Length); 4687 if (Result.isInvalid()) 4688 return ExprError(); 4689 Result = DefaultLvalueConversion(Result.get()); 4690 if (Result.isInvalid()) 4691 return ExprError(); 4692 Length = Result.get(); 4693 } 4694 4695 // Build an unanalyzed expression if either operand is type-dependent. 4696 if (Base->isTypeDependent() || 4697 (LowerBound && 4698 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4699 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4700 return new (Context) 4701 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4702 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4703 } 4704 4705 // Perform default conversions. 4706 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4707 QualType ResultTy; 4708 if (OriginalTy->isAnyPointerType()) { 4709 ResultTy = OriginalTy->getPointeeType(); 4710 } else if (OriginalTy->isArrayType()) { 4711 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4712 } else { 4713 return ExprError( 4714 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4715 << Base->getSourceRange()); 4716 } 4717 // C99 6.5.2.1p1 4718 if (LowerBound) { 4719 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4720 LowerBound); 4721 if (Res.isInvalid()) 4722 return ExprError(Diag(LowerBound->getExprLoc(), 4723 diag::err_omp_typecheck_section_not_integer) 4724 << 0 << LowerBound->getSourceRange()); 4725 LowerBound = Res.get(); 4726 4727 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4728 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4729 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4730 << 0 << LowerBound->getSourceRange(); 4731 } 4732 if (Length) { 4733 auto Res = 4734 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4735 if (Res.isInvalid()) 4736 return ExprError(Diag(Length->getExprLoc(), 4737 diag::err_omp_typecheck_section_not_integer) 4738 << 1 << Length->getSourceRange()); 4739 Length = Res.get(); 4740 4741 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4742 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4743 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4744 << 1 << Length->getSourceRange(); 4745 } 4746 4747 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4748 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4749 // type. Note that functions are not objects, and that (in C99 parlance) 4750 // incomplete types are not object types. 4751 if (ResultTy->isFunctionType()) { 4752 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4753 << ResultTy << Base->getSourceRange(); 4754 return ExprError(); 4755 } 4756 4757 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4758 diag::err_omp_section_incomplete_type, Base)) 4759 return ExprError(); 4760 4761 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4762 Expr::EvalResult Result; 4763 if (LowerBound->EvaluateAsInt(Result, Context)) { 4764 // OpenMP 4.5, [2.4 Array Sections] 4765 // The array section must be a subset of the original array. 4766 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4767 if (LowerBoundValue.isNegative()) { 4768 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4769 << LowerBound->getSourceRange(); 4770 return ExprError(); 4771 } 4772 } 4773 } 4774 4775 if (Length) { 4776 Expr::EvalResult Result; 4777 if (Length->EvaluateAsInt(Result, Context)) { 4778 // OpenMP 4.5, [2.4 Array Sections] 4779 // The length must evaluate to non-negative integers. 4780 llvm::APSInt LengthValue = Result.Val.getInt(); 4781 if (LengthValue.isNegative()) { 4782 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4783 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4784 << Length->getSourceRange(); 4785 return ExprError(); 4786 } 4787 } 4788 } else if (ColonLoc.isValid() && 4789 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4790 !OriginalTy->isVariableArrayType()))) { 4791 // OpenMP 4.5, [2.4 Array Sections] 4792 // When the size of the array dimension is not known, the length must be 4793 // specified explicitly. 4794 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4795 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4796 return ExprError(); 4797 } 4798 4799 if (!Base->getType()->isSpecificPlaceholderType( 4800 BuiltinType::OMPArraySection)) { 4801 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4802 if (Result.isInvalid()) 4803 return ExprError(); 4804 Base = Result.get(); 4805 } 4806 return new (Context) 4807 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4808 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4809 } 4810 4811 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 4812 SourceLocation RParenLoc, 4813 ArrayRef<Expr *> Dims, 4814 ArrayRef<SourceRange> Brackets) { 4815 if (Base->getType()->isPlaceholderType()) { 4816 ExprResult Result = CheckPlaceholderExpr(Base); 4817 if (Result.isInvalid()) 4818 return ExprError(); 4819 Result = DefaultLvalueConversion(Result.get()); 4820 if (Result.isInvalid()) 4821 return ExprError(); 4822 Base = Result.get(); 4823 } 4824 QualType BaseTy = Base->getType(); 4825 // Delay analysis of the types/expressions if instantiation/specialization is 4826 // required. 4827 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 4828 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 4829 LParenLoc, RParenLoc, Dims, Brackets); 4830 if (!BaseTy->isPointerType() || 4831 (!Base->isTypeDependent() && 4832 BaseTy->getPointeeType()->isIncompleteType())) 4833 return ExprError(Diag(Base->getExprLoc(), 4834 diag::err_omp_non_pointer_type_array_shaping_base) 4835 << Base->getSourceRange()); 4836 4837 SmallVector<Expr *, 4> NewDims; 4838 bool ErrorFound = false; 4839 for (Expr *Dim : Dims) { 4840 if (Dim->getType()->isPlaceholderType()) { 4841 ExprResult Result = CheckPlaceholderExpr(Dim); 4842 if (Result.isInvalid()) { 4843 ErrorFound = true; 4844 continue; 4845 } 4846 Result = DefaultLvalueConversion(Result.get()); 4847 if (Result.isInvalid()) { 4848 ErrorFound = true; 4849 continue; 4850 } 4851 Dim = Result.get(); 4852 } 4853 if (!Dim->isTypeDependent()) { 4854 ExprResult Result = 4855 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 4856 if (Result.isInvalid()) { 4857 ErrorFound = true; 4858 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 4859 << Dim->getSourceRange(); 4860 continue; 4861 } 4862 Dim = Result.get(); 4863 Expr::EvalResult EvResult; 4864 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 4865 // OpenMP 5.0, [2.1.4 Array Shaping] 4866 // Each si is an integral type expression that must evaluate to a 4867 // positive integer. 4868 llvm::APSInt Value = EvResult.Val.getInt(); 4869 if (!Value.isStrictlyPositive()) { 4870 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 4871 << Value.toString(/*Radix=*/10, /*Signed=*/true) 4872 << Dim->getSourceRange(); 4873 ErrorFound = true; 4874 continue; 4875 } 4876 } 4877 } 4878 NewDims.push_back(Dim); 4879 } 4880 if (ErrorFound) 4881 return ExprError(); 4882 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 4883 LParenLoc, RParenLoc, NewDims, Brackets); 4884 } 4885 4886 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 4887 SourceLocation LLoc, SourceLocation RLoc, 4888 ArrayRef<OMPIteratorData> Data) { 4889 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 4890 bool IsCorrect = true; 4891 for (const OMPIteratorData &D : Data) { 4892 TypeSourceInfo *TInfo = nullptr; 4893 SourceLocation StartLoc; 4894 QualType DeclTy; 4895 if (!D.Type.getAsOpaquePtr()) { 4896 // OpenMP 5.0, 2.1.6 Iterators 4897 // In an iterator-specifier, if the iterator-type is not specified then 4898 // the type of that iterator is of int type. 4899 DeclTy = Context.IntTy; 4900 StartLoc = D.DeclIdentLoc; 4901 } else { 4902 DeclTy = GetTypeFromParser(D.Type, &TInfo); 4903 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 4904 } 4905 4906 bool IsDeclTyDependent = DeclTy->isDependentType() || 4907 DeclTy->containsUnexpandedParameterPack() || 4908 DeclTy->isInstantiationDependentType(); 4909 if (!IsDeclTyDependent) { 4910 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 4911 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 4912 // The iterator-type must be an integral or pointer type. 4913 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 4914 << DeclTy; 4915 IsCorrect = false; 4916 continue; 4917 } 4918 if (DeclTy.isConstant(Context)) { 4919 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 4920 // The iterator-type must not be const qualified. 4921 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 4922 << DeclTy; 4923 IsCorrect = false; 4924 continue; 4925 } 4926 } 4927 4928 // Iterator declaration. 4929 assert(D.DeclIdent && "Identifier expected."); 4930 // Always try to create iterator declarator to avoid extra error messages 4931 // about unknown declarations use. 4932 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 4933 D.DeclIdent, DeclTy, TInfo, SC_None); 4934 VD->setImplicit(); 4935 if (S) { 4936 // Check for conflicting previous declaration. 4937 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 4938 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4939 ForVisibleRedeclaration); 4940 Previous.suppressDiagnostics(); 4941 LookupName(Previous, S); 4942 4943 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 4944 /*AllowInlineNamespace=*/false); 4945 if (!Previous.empty()) { 4946 NamedDecl *Old = Previous.getRepresentativeDecl(); 4947 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 4948 Diag(Old->getLocation(), diag::note_previous_definition); 4949 } else { 4950 PushOnScopeChains(VD, S); 4951 } 4952 } else { 4953 CurContext->addDecl(VD); 4954 } 4955 Expr *Begin = D.Range.Begin; 4956 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 4957 ExprResult BeginRes = 4958 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 4959 Begin = BeginRes.get(); 4960 } 4961 Expr *End = D.Range.End; 4962 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 4963 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 4964 End = EndRes.get(); 4965 } 4966 Expr *Step = D.Range.Step; 4967 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 4968 if (!Step->getType()->isIntegralType(Context)) { 4969 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 4970 << Step << Step->getSourceRange(); 4971 IsCorrect = false; 4972 continue; 4973 } 4974 llvm::APSInt Result; 4975 bool IsConstant = Step->isIntegerConstantExpr(Result, Context); 4976 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 4977 // If the step expression of a range-specification equals zero, the 4978 // behavior is unspecified. 4979 if (IsConstant && Result.isNullValue()) { 4980 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 4981 << Step << Step->getSourceRange(); 4982 IsCorrect = false; 4983 continue; 4984 } 4985 } 4986 if (!Begin || !End || !IsCorrect) { 4987 IsCorrect = false; 4988 continue; 4989 } 4990 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 4991 IDElem.IteratorDecl = VD; 4992 IDElem.AssignmentLoc = D.AssignLoc; 4993 IDElem.Range.Begin = Begin; 4994 IDElem.Range.End = End; 4995 IDElem.Range.Step = Step; 4996 IDElem.ColonLoc = D.ColonLoc; 4997 IDElem.SecondColonLoc = D.SecColonLoc; 4998 } 4999 if (!IsCorrect) { 5000 // Invalidate all created iterator declarations if error is found. 5001 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5002 if (Decl *ID = D.IteratorDecl) 5003 ID->setInvalidDecl(); 5004 } 5005 return ExprError(); 5006 } 5007 SmallVector<OMPIteratorHelperData, 4> Helpers; 5008 if (!CurContext->isDependentContext()) { 5009 // Build number of ityeration for each iteration range. 5010 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5011 // ((Begini-Stepi-1-Endi) / -Stepi); 5012 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5013 // (Endi - Begini) 5014 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5015 D.Range.Begin); 5016 if(!Res.isUsable()) { 5017 IsCorrect = false; 5018 continue; 5019 } 5020 ExprResult St, St1; 5021 if (D.Range.Step) { 5022 St = D.Range.Step; 5023 // (Endi - Begini) + Stepi 5024 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5025 if (!Res.isUsable()) { 5026 IsCorrect = false; 5027 continue; 5028 } 5029 // (Endi - Begini) + Stepi - 1 5030 Res = 5031 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5032 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5033 if (!Res.isUsable()) { 5034 IsCorrect = false; 5035 continue; 5036 } 5037 // ((Endi - Begini) + Stepi - 1) / Stepi 5038 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5039 if (!Res.isUsable()) { 5040 IsCorrect = false; 5041 continue; 5042 } 5043 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5044 // (Begini - Endi) 5045 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5046 D.Range.Begin, D.Range.End); 5047 if (!Res1.isUsable()) { 5048 IsCorrect = false; 5049 continue; 5050 } 5051 // (Begini - Endi) - Stepi 5052 Res1 = 5053 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5054 if (!Res1.isUsable()) { 5055 IsCorrect = false; 5056 continue; 5057 } 5058 // (Begini - Endi) - Stepi - 1 5059 Res1 = 5060 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5061 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5062 if (!Res1.isUsable()) { 5063 IsCorrect = false; 5064 continue; 5065 } 5066 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5067 Res1 = 5068 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5069 if (!Res1.isUsable()) { 5070 IsCorrect = false; 5071 continue; 5072 } 5073 // Stepi > 0. 5074 ExprResult CmpRes = 5075 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5076 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5077 if (!CmpRes.isUsable()) { 5078 IsCorrect = false; 5079 continue; 5080 } 5081 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5082 Res.get(), Res1.get()); 5083 if (!Res.isUsable()) { 5084 IsCorrect = false; 5085 continue; 5086 } 5087 } 5088 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5089 if (!Res.isUsable()) { 5090 IsCorrect = false; 5091 continue; 5092 } 5093 5094 // Build counter update. 5095 // Build counter. 5096 auto *CounterVD = 5097 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5098 D.IteratorDecl->getBeginLoc(), nullptr, 5099 Res.get()->getType(), nullptr, SC_None); 5100 CounterVD->setImplicit(); 5101 ExprResult RefRes = 5102 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5103 D.IteratorDecl->getBeginLoc()); 5104 // Build counter update. 5105 // I = Begini + counter * Stepi; 5106 ExprResult UpdateRes; 5107 if (D.Range.Step) { 5108 UpdateRes = CreateBuiltinBinOp( 5109 D.AssignmentLoc, BO_Mul, 5110 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5111 } else { 5112 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5113 } 5114 if (!UpdateRes.isUsable()) { 5115 IsCorrect = false; 5116 continue; 5117 } 5118 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5119 UpdateRes.get()); 5120 if (!UpdateRes.isUsable()) { 5121 IsCorrect = false; 5122 continue; 5123 } 5124 ExprResult VDRes = 5125 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5126 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5127 D.IteratorDecl->getBeginLoc()); 5128 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5129 UpdateRes.get()); 5130 if (!UpdateRes.isUsable()) { 5131 IsCorrect = false; 5132 continue; 5133 } 5134 UpdateRes = 5135 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5136 if (!UpdateRes.isUsable()) { 5137 IsCorrect = false; 5138 continue; 5139 } 5140 ExprResult CounterUpdateRes = 5141 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5142 if (!CounterUpdateRes.isUsable()) { 5143 IsCorrect = false; 5144 continue; 5145 } 5146 CounterUpdateRes = 5147 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5148 if (!CounterUpdateRes.isUsable()) { 5149 IsCorrect = false; 5150 continue; 5151 } 5152 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5153 HD.CounterVD = CounterVD; 5154 HD.Upper = Res.get(); 5155 HD.Update = UpdateRes.get(); 5156 HD.CounterUpdate = CounterUpdateRes.get(); 5157 } 5158 } else { 5159 Helpers.assign(ID.size(), {}); 5160 } 5161 if (!IsCorrect) { 5162 // Invalidate all created iterator declarations if error is found. 5163 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5164 if (Decl *ID = D.IteratorDecl) 5165 ID->setInvalidDecl(); 5166 } 5167 return ExprError(); 5168 } 5169 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5170 LLoc, RLoc, ID, Helpers); 5171 } 5172 5173 ExprResult 5174 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5175 Expr *Idx, SourceLocation RLoc) { 5176 Expr *LHSExp = Base; 5177 Expr *RHSExp = Idx; 5178 5179 ExprValueKind VK = VK_LValue; 5180 ExprObjectKind OK = OK_Ordinary; 5181 5182 // Per C++ core issue 1213, the result is an xvalue if either operand is 5183 // a non-lvalue array, and an lvalue otherwise. 5184 if (getLangOpts().CPlusPlus11) { 5185 for (auto *Op : {LHSExp, RHSExp}) { 5186 Op = Op->IgnoreImplicit(); 5187 if (Op->getType()->isArrayType() && !Op->isLValue()) 5188 VK = VK_XValue; 5189 } 5190 } 5191 5192 // Perform default conversions. 5193 if (!LHSExp->getType()->getAs<VectorType>()) { 5194 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5195 if (Result.isInvalid()) 5196 return ExprError(); 5197 LHSExp = Result.get(); 5198 } 5199 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5200 if (Result.isInvalid()) 5201 return ExprError(); 5202 RHSExp = Result.get(); 5203 5204 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5205 5206 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5207 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5208 // in the subscript position. As a result, we need to derive the array base 5209 // and index from the expression types. 5210 Expr *BaseExpr, *IndexExpr; 5211 QualType ResultType; 5212 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5213 BaseExpr = LHSExp; 5214 IndexExpr = RHSExp; 5215 ResultType = Context.DependentTy; 5216 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5217 BaseExpr = LHSExp; 5218 IndexExpr = RHSExp; 5219 ResultType = PTy->getPointeeType(); 5220 } else if (const ObjCObjectPointerType *PTy = 5221 LHSTy->getAs<ObjCObjectPointerType>()) { 5222 BaseExpr = LHSExp; 5223 IndexExpr = RHSExp; 5224 5225 // Use custom logic if this should be the pseudo-object subscript 5226 // expression. 5227 if (!LangOpts.isSubscriptPointerArithmetic()) 5228 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5229 nullptr); 5230 5231 ResultType = PTy->getPointeeType(); 5232 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5233 // Handle the uncommon case of "123[Ptr]". 5234 BaseExpr = RHSExp; 5235 IndexExpr = LHSExp; 5236 ResultType = PTy->getPointeeType(); 5237 } else if (const ObjCObjectPointerType *PTy = 5238 RHSTy->getAs<ObjCObjectPointerType>()) { 5239 // Handle the uncommon case of "123[Ptr]". 5240 BaseExpr = RHSExp; 5241 IndexExpr = LHSExp; 5242 ResultType = PTy->getPointeeType(); 5243 if (!LangOpts.isSubscriptPointerArithmetic()) { 5244 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5245 << ResultType << BaseExpr->getSourceRange(); 5246 return ExprError(); 5247 } 5248 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5249 BaseExpr = LHSExp; // vectors: V[123] 5250 IndexExpr = RHSExp; 5251 // We apply C++ DR1213 to vector subscripting too. 5252 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 5253 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5254 if (Materialized.isInvalid()) 5255 return ExprError(); 5256 LHSExp = Materialized.get(); 5257 } 5258 VK = LHSExp->getValueKind(); 5259 if (VK != VK_RValue) 5260 OK = OK_VectorComponent; 5261 5262 ResultType = VTy->getElementType(); 5263 QualType BaseType = BaseExpr->getType(); 5264 Qualifiers BaseQuals = BaseType.getQualifiers(); 5265 Qualifiers MemberQuals = ResultType.getQualifiers(); 5266 Qualifiers Combined = BaseQuals + MemberQuals; 5267 if (Combined != MemberQuals) 5268 ResultType = Context.getQualifiedType(ResultType, Combined); 5269 } else if (LHSTy->isArrayType()) { 5270 // If we see an array that wasn't promoted by 5271 // DefaultFunctionArrayLvalueConversion, it must be an array that 5272 // wasn't promoted because of the C90 rule that doesn't 5273 // allow promoting non-lvalue arrays. Warn, then 5274 // force the promotion here. 5275 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5276 << LHSExp->getSourceRange(); 5277 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5278 CK_ArrayToPointerDecay).get(); 5279 LHSTy = LHSExp->getType(); 5280 5281 BaseExpr = LHSExp; 5282 IndexExpr = RHSExp; 5283 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 5284 } else if (RHSTy->isArrayType()) { 5285 // Same as previous, except for 123[f().a] case 5286 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5287 << RHSExp->getSourceRange(); 5288 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5289 CK_ArrayToPointerDecay).get(); 5290 RHSTy = RHSExp->getType(); 5291 5292 BaseExpr = RHSExp; 5293 IndexExpr = LHSExp; 5294 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 5295 } else { 5296 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5297 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5298 } 5299 // C99 6.5.2.1p1 5300 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5301 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5302 << IndexExpr->getSourceRange()); 5303 5304 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5305 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5306 && !IndexExpr->isTypeDependent()) 5307 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5308 5309 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5310 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5311 // type. Note that Functions are not objects, and that (in C99 parlance) 5312 // incomplete types are not object types. 5313 if (ResultType->isFunctionType()) { 5314 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5315 << ResultType << BaseExpr->getSourceRange(); 5316 return ExprError(); 5317 } 5318 5319 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5320 // GNU extension: subscripting on pointer to void 5321 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5322 << BaseExpr->getSourceRange(); 5323 5324 // C forbids expressions of unqualified void type from being l-values. 5325 // See IsCForbiddenLValueType. 5326 if (!ResultType.hasQualifiers()) VK = VK_RValue; 5327 } else if (!ResultType->isDependentType() && 5328 RequireCompleteSizedType( 5329 LLoc, ResultType, 5330 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5331 return ExprError(); 5332 5333 assert(VK == VK_RValue || LangOpts.CPlusPlus || 5334 !ResultType.isCForbiddenLValueType()); 5335 5336 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5337 FunctionScopes.size() > 1) { 5338 if (auto *TT = 5339 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5340 for (auto I = FunctionScopes.rbegin(), 5341 E = std::prev(FunctionScopes.rend()); 5342 I != E; ++I) { 5343 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5344 if (CSI == nullptr) 5345 break; 5346 DeclContext *DC = nullptr; 5347 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5348 DC = LSI->CallOperator; 5349 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5350 DC = CRSI->TheCapturedDecl; 5351 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5352 DC = BSI->TheDecl; 5353 if (DC) { 5354 if (DC->containsDecl(TT->getDecl())) 5355 break; 5356 captureVariablyModifiedType( 5357 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5358 } 5359 } 5360 } 5361 } 5362 5363 return new (Context) 5364 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5365 } 5366 5367 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5368 ParmVarDecl *Param) { 5369 if (Param->hasUnparsedDefaultArg()) { 5370 Diag(CallLoc, 5371 diag::err_use_of_default_argument_to_function_declared_later) << 5372 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 5373 Diag(UnparsedDefaultArgLocs[Param], 5374 diag::note_default_argument_declared_here); 5375 return true; 5376 } 5377 5378 if (Param->hasUninstantiatedDefaultArg()) { 5379 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 5380 5381 EnterExpressionEvaluationContext EvalContext( 5382 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5383 5384 // Instantiate the expression. 5385 // 5386 // FIXME: Pass in a correct Pattern argument, otherwise 5387 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 5388 // 5389 // template<typename T> 5390 // struct A { 5391 // static int FooImpl(); 5392 // 5393 // template<typename Tp> 5394 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 5395 // // template argument list [[T], [Tp]], should be [[Tp]]. 5396 // friend A<Tp> Foo(int a); 5397 // }; 5398 // 5399 // template<typename T> 5400 // A<T> Foo(int a = A<T>::FooImpl()); 5401 MultiLevelTemplateArgumentList MutiLevelArgList 5402 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 5403 5404 InstantiatingTemplate Inst(*this, CallLoc, Param, 5405 MutiLevelArgList.getInnermost()); 5406 if (Inst.isInvalid()) 5407 return true; 5408 if (Inst.isAlreadyInstantiating()) { 5409 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5410 Param->setInvalidDecl(); 5411 return true; 5412 } 5413 5414 ExprResult Result; 5415 { 5416 // C++ [dcl.fct.default]p5: 5417 // The names in the [default argument] expression are bound, and 5418 // the semantic constraints are checked, at the point where the 5419 // default argument expression appears. 5420 ContextRAII SavedContext(*this, FD); 5421 LocalInstantiationScope Local(*this); 5422 runWithSufficientStackSpace(CallLoc, [&] { 5423 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 5424 /*DirectInit*/false); 5425 }); 5426 } 5427 if (Result.isInvalid()) 5428 return true; 5429 5430 // Check the expression as an initializer for the parameter. 5431 InitializedEntity Entity 5432 = InitializedEntity::InitializeParameter(Context, Param); 5433 InitializationKind Kind = InitializationKind::CreateCopy( 5434 Param->getLocation(), 5435 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 5436 Expr *ResultE = Result.getAs<Expr>(); 5437 5438 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 5439 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 5440 if (Result.isInvalid()) 5441 return true; 5442 5443 Result = 5444 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 5445 /*DiscardedValue*/ false); 5446 if (Result.isInvalid()) 5447 return true; 5448 5449 // Remember the instantiated default argument. 5450 Param->setDefaultArg(Result.getAs<Expr>()); 5451 if (ASTMutationListener *L = getASTMutationListener()) { 5452 L->DefaultArgumentInstantiated(Param); 5453 } 5454 } 5455 5456 // If the default argument expression is not set yet, we are building it now. 5457 if (!Param->hasInit()) { 5458 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5459 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5460 Param->setInvalidDecl(); 5461 return true; 5462 } 5463 5464 // If the default expression creates temporaries, we need to 5465 // push them to the current stack of expression temporaries so they'll 5466 // be properly destroyed. 5467 // FIXME: We should really be rebuilding the default argument with new 5468 // bound temporaries; see the comment in PR5810. 5469 // We don't need to do that with block decls, though, because 5470 // blocks in default argument expression can never capture anything. 5471 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5472 // Set the "needs cleanups" bit regardless of whether there are 5473 // any explicit objects. 5474 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5475 5476 // Append all the objects to the cleanup list. Right now, this 5477 // should always be a no-op, because blocks in default argument 5478 // expressions should never be able to capture anything. 5479 assert(!Init->getNumObjects() && 5480 "default argument expression has capturing blocks?"); 5481 } 5482 5483 // We already type-checked the argument, so we know it works. 5484 // Just mark all of the declarations in this potentially-evaluated expression 5485 // as being "referenced". 5486 EnterExpressionEvaluationContext EvalContext( 5487 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5488 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5489 /*SkipLocalVariables=*/true); 5490 return false; 5491 } 5492 5493 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5494 FunctionDecl *FD, ParmVarDecl *Param) { 5495 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5496 return ExprError(); 5497 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5498 } 5499 5500 Sema::VariadicCallType 5501 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5502 Expr *Fn) { 5503 if (Proto && Proto->isVariadic()) { 5504 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5505 return VariadicConstructor; 5506 else if (Fn && Fn->getType()->isBlockPointerType()) 5507 return VariadicBlock; 5508 else if (FDecl) { 5509 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5510 if (Method->isInstance()) 5511 return VariadicMethod; 5512 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5513 return VariadicMethod; 5514 return VariadicFunction; 5515 } 5516 return VariadicDoesNotApply; 5517 } 5518 5519 namespace { 5520 class FunctionCallCCC final : public FunctionCallFilterCCC { 5521 public: 5522 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5523 unsigned NumArgs, MemberExpr *ME) 5524 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5525 FunctionName(FuncName) {} 5526 5527 bool ValidateCandidate(const TypoCorrection &candidate) override { 5528 if (!candidate.getCorrectionSpecifier() || 5529 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5530 return false; 5531 } 5532 5533 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5534 } 5535 5536 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5537 return std::make_unique<FunctionCallCCC>(*this); 5538 } 5539 5540 private: 5541 const IdentifierInfo *const FunctionName; 5542 }; 5543 } 5544 5545 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5546 FunctionDecl *FDecl, 5547 ArrayRef<Expr *> Args) { 5548 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5549 DeclarationName FuncName = FDecl->getDeclName(); 5550 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5551 5552 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5553 if (TypoCorrection Corrected = S.CorrectTypo( 5554 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5555 S.getScopeForContext(S.CurContext), nullptr, CCC, 5556 Sema::CTK_ErrorRecovery)) { 5557 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5558 if (Corrected.isOverloaded()) { 5559 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5560 OverloadCandidateSet::iterator Best; 5561 for (NamedDecl *CD : Corrected) { 5562 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5563 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5564 OCS); 5565 } 5566 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5567 case OR_Success: 5568 ND = Best->FoundDecl; 5569 Corrected.setCorrectionDecl(ND); 5570 break; 5571 default: 5572 break; 5573 } 5574 } 5575 ND = ND->getUnderlyingDecl(); 5576 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5577 return Corrected; 5578 } 5579 } 5580 return TypoCorrection(); 5581 } 5582 5583 /// ConvertArgumentsForCall - Converts the arguments specified in 5584 /// Args/NumArgs to the parameter types of the function FDecl with 5585 /// function prototype Proto. Call is the call expression itself, and 5586 /// Fn is the function expression. For a C++ member function, this 5587 /// routine does not attempt to convert the object argument. Returns 5588 /// true if the call is ill-formed. 5589 bool 5590 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5591 FunctionDecl *FDecl, 5592 const FunctionProtoType *Proto, 5593 ArrayRef<Expr *> Args, 5594 SourceLocation RParenLoc, 5595 bool IsExecConfig) { 5596 // Bail out early if calling a builtin with custom typechecking. 5597 if (FDecl) 5598 if (unsigned ID = FDecl->getBuiltinID()) 5599 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5600 return false; 5601 5602 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5603 // assignment, to the types of the corresponding parameter, ... 5604 unsigned NumParams = Proto->getNumParams(); 5605 bool Invalid = false; 5606 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5607 unsigned FnKind = Fn->getType()->isBlockPointerType() 5608 ? 1 /* block */ 5609 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5610 : 0 /* function */); 5611 5612 // If too few arguments are available (and we don't have default 5613 // arguments for the remaining parameters), don't make the call. 5614 if (Args.size() < NumParams) { 5615 if (Args.size() < MinArgs) { 5616 TypoCorrection TC; 5617 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5618 unsigned diag_id = 5619 MinArgs == NumParams && !Proto->isVariadic() 5620 ? diag::err_typecheck_call_too_few_args_suggest 5621 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5622 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5623 << static_cast<unsigned>(Args.size()) 5624 << TC.getCorrectionRange()); 5625 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5626 Diag(RParenLoc, 5627 MinArgs == NumParams && !Proto->isVariadic() 5628 ? diag::err_typecheck_call_too_few_args_one 5629 : diag::err_typecheck_call_too_few_args_at_least_one) 5630 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5631 else 5632 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5633 ? diag::err_typecheck_call_too_few_args 5634 : diag::err_typecheck_call_too_few_args_at_least) 5635 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5636 << Fn->getSourceRange(); 5637 5638 // Emit the location of the prototype. 5639 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5640 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5641 5642 return true; 5643 } 5644 // We reserve space for the default arguments when we create 5645 // the call expression, before calling ConvertArgumentsForCall. 5646 assert((Call->getNumArgs() == NumParams) && 5647 "We should have reserved space for the default arguments before!"); 5648 } 5649 5650 // If too many are passed and not variadic, error on the extras and drop 5651 // them. 5652 if (Args.size() > NumParams) { 5653 if (!Proto->isVariadic()) { 5654 TypoCorrection TC; 5655 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5656 unsigned diag_id = 5657 MinArgs == NumParams && !Proto->isVariadic() 5658 ? diag::err_typecheck_call_too_many_args_suggest 5659 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5660 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5661 << static_cast<unsigned>(Args.size()) 5662 << TC.getCorrectionRange()); 5663 } else if (NumParams == 1 && FDecl && 5664 FDecl->getParamDecl(0)->getDeclName()) 5665 Diag(Args[NumParams]->getBeginLoc(), 5666 MinArgs == NumParams 5667 ? diag::err_typecheck_call_too_many_args_one 5668 : diag::err_typecheck_call_too_many_args_at_most_one) 5669 << FnKind << FDecl->getParamDecl(0) 5670 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5671 << SourceRange(Args[NumParams]->getBeginLoc(), 5672 Args.back()->getEndLoc()); 5673 else 5674 Diag(Args[NumParams]->getBeginLoc(), 5675 MinArgs == NumParams 5676 ? diag::err_typecheck_call_too_many_args 5677 : diag::err_typecheck_call_too_many_args_at_most) 5678 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5679 << Fn->getSourceRange() 5680 << SourceRange(Args[NumParams]->getBeginLoc(), 5681 Args.back()->getEndLoc()); 5682 5683 // Emit the location of the prototype. 5684 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5685 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5686 5687 // This deletes the extra arguments. 5688 Call->shrinkNumArgs(NumParams); 5689 return true; 5690 } 5691 } 5692 SmallVector<Expr *, 8> AllArgs; 5693 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5694 5695 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5696 AllArgs, CallType); 5697 if (Invalid) 5698 return true; 5699 unsigned TotalNumArgs = AllArgs.size(); 5700 for (unsigned i = 0; i < TotalNumArgs; ++i) 5701 Call->setArg(i, AllArgs[i]); 5702 5703 return false; 5704 } 5705 5706 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5707 const FunctionProtoType *Proto, 5708 unsigned FirstParam, ArrayRef<Expr *> Args, 5709 SmallVectorImpl<Expr *> &AllArgs, 5710 VariadicCallType CallType, bool AllowExplicit, 5711 bool IsListInitialization) { 5712 unsigned NumParams = Proto->getNumParams(); 5713 bool Invalid = false; 5714 size_t ArgIx = 0; 5715 // Continue to check argument types (even if we have too few/many args). 5716 for (unsigned i = FirstParam; i < NumParams; i++) { 5717 QualType ProtoArgType = Proto->getParamType(i); 5718 5719 Expr *Arg; 5720 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5721 if (ArgIx < Args.size()) { 5722 Arg = Args[ArgIx++]; 5723 5724 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5725 diag::err_call_incomplete_argument, Arg)) 5726 return true; 5727 5728 // Strip the unbridged-cast placeholder expression off, if applicable. 5729 bool CFAudited = false; 5730 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5731 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5732 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5733 Arg = stripARCUnbridgedCast(Arg); 5734 else if (getLangOpts().ObjCAutoRefCount && 5735 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5736 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5737 CFAudited = true; 5738 5739 if (Proto->getExtParameterInfo(i).isNoEscape()) 5740 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5741 BE->getBlockDecl()->setDoesNotEscape(); 5742 5743 InitializedEntity Entity = 5744 Param ? InitializedEntity::InitializeParameter(Context, Param, 5745 ProtoArgType) 5746 : InitializedEntity::InitializeParameter( 5747 Context, ProtoArgType, Proto->isParamConsumed(i)); 5748 5749 // Remember that parameter belongs to a CF audited API. 5750 if (CFAudited) 5751 Entity.setParameterCFAudited(); 5752 5753 ExprResult ArgE = PerformCopyInitialization( 5754 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5755 if (ArgE.isInvalid()) 5756 return true; 5757 5758 Arg = ArgE.getAs<Expr>(); 5759 } else { 5760 assert(Param && "can't use default arguments without a known callee"); 5761 5762 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5763 if (ArgExpr.isInvalid()) 5764 return true; 5765 5766 Arg = ArgExpr.getAs<Expr>(); 5767 } 5768 5769 // Check for array bounds violations for each argument to the call. This 5770 // check only triggers warnings when the argument isn't a more complex Expr 5771 // with its own checking, such as a BinaryOperator. 5772 CheckArrayAccess(Arg); 5773 5774 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5775 CheckStaticArrayArgument(CallLoc, Param, Arg); 5776 5777 AllArgs.push_back(Arg); 5778 } 5779 5780 // If this is a variadic call, handle args passed through "...". 5781 if (CallType != VariadicDoesNotApply) { 5782 // Assume that extern "C" functions with variadic arguments that 5783 // return __unknown_anytype aren't *really* variadic. 5784 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5785 FDecl->isExternC()) { 5786 for (Expr *A : Args.slice(ArgIx)) { 5787 QualType paramType; // ignored 5788 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5789 Invalid |= arg.isInvalid(); 5790 AllArgs.push_back(arg.get()); 5791 } 5792 5793 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5794 } else { 5795 for (Expr *A : Args.slice(ArgIx)) { 5796 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5797 Invalid |= Arg.isInvalid(); 5798 // Copy blocks to the heap. 5799 if (A->getType()->isBlockPointerType()) 5800 maybeExtendBlockObject(Arg); 5801 AllArgs.push_back(Arg.get()); 5802 } 5803 } 5804 5805 // Check for array bounds violations. 5806 for (Expr *A : Args.slice(ArgIx)) 5807 CheckArrayAccess(A); 5808 } 5809 return Invalid; 5810 } 5811 5812 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5813 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5814 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5815 TL = DTL.getOriginalLoc(); 5816 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5817 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5818 << ATL.getLocalSourceRange(); 5819 } 5820 5821 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5822 /// array parameter, check that it is non-null, and that if it is formed by 5823 /// array-to-pointer decay, the underlying array is sufficiently large. 5824 /// 5825 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5826 /// array type derivation, then for each call to the function, the value of the 5827 /// corresponding actual argument shall provide access to the first element of 5828 /// an array with at least as many elements as specified by the size expression. 5829 void 5830 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5831 ParmVarDecl *Param, 5832 const Expr *ArgExpr) { 5833 // Static array parameters are not supported in C++. 5834 if (!Param || getLangOpts().CPlusPlus) 5835 return; 5836 5837 QualType OrigTy = Param->getOriginalType(); 5838 5839 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5840 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5841 return; 5842 5843 if (ArgExpr->isNullPointerConstant(Context, 5844 Expr::NPC_NeverValueDependent)) { 5845 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5846 DiagnoseCalleeStaticArrayParam(*this, Param); 5847 return; 5848 } 5849 5850 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5851 if (!CAT) 5852 return; 5853 5854 const ConstantArrayType *ArgCAT = 5855 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5856 if (!ArgCAT) 5857 return; 5858 5859 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5860 ArgCAT->getElementType())) { 5861 if (ArgCAT->getSize().ult(CAT->getSize())) { 5862 Diag(CallLoc, diag::warn_static_array_too_small) 5863 << ArgExpr->getSourceRange() 5864 << (unsigned)ArgCAT->getSize().getZExtValue() 5865 << (unsigned)CAT->getSize().getZExtValue() << 0; 5866 DiagnoseCalleeStaticArrayParam(*this, Param); 5867 } 5868 return; 5869 } 5870 5871 Optional<CharUnits> ArgSize = 5872 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5873 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5874 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5875 Diag(CallLoc, diag::warn_static_array_too_small) 5876 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5877 << (unsigned)ParmSize->getQuantity() << 1; 5878 DiagnoseCalleeStaticArrayParam(*this, Param); 5879 } 5880 } 5881 5882 /// Given a function expression of unknown-any type, try to rebuild it 5883 /// to have a function type. 5884 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5885 5886 /// Is the given type a placeholder that we need to lower out 5887 /// immediately during argument processing? 5888 static bool isPlaceholderToRemoveAsArg(QualType type) { 5889 // Placeholders are never sugared. 5890 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5891 if (!placeholder) return false; 5892 5893 switch (placeholder->getKind()) { 5894 // Ignore all the non-placeholder types. 5895 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5896 case BuiltinType::Id: 5897 #include "clang/Basic/OpenCLImageTypes.def" 5898 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5899 case BuiltinType::Id: 5900 #include "clang/Basic/OpenCLExtensionTypes.def" 5901 // In practice we'll never use this, since all SVE types are sugared 5902 // via TypedefTypes rather than exposed directly as BuiltinTypes. 5903 #define SVE_TYPE(Name, Id, SingletonId) \ 5904 case BuiltinType::Id: 5905 #include "clang/Basic/AArch64SVEACLETypes.def" 5906 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5907 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5908 #include "clang/AST/BuiltinTypes.def" 5909 return false; 5910 5911 // We cannot lower out overload sets; they might validly be resolved 5912 // by the call machinery. 5913 case BuiltinType::Overload: 5914 return false; 5915 5916 // Unbridged casts in ARC can be handled in some call positions and 5917 // should be left in place. 5918 case BuiltinType::ARCUnbridgedCast: 5919 return false; 5920 5921 // Pseudo-objects should be converted as soon as possible. 5922 case BuiltinType::PseudoObject: 5923 return true; 5924 5925 // The debugger mode could theoretically but currently does not try 5926 // to resolve unknown-typed arguments based on known parameter types. 5927 case BuiltinType::UnknownAny: 5928 return true; 5929 5930 // These are always invalid as call arguments and should be reported. 5931 case BuiltinType::BoundMember: 5932 case BuiltinType::BuiltinFn: 5933 case BuiltinType::OMPArraySection: 5934 case BuiltinType::OMPArrayShaping: 5935 case BuiltinType::OMPIterator: 5936 return true; 5937 5938 } 5939 llvm_unreachable("bad builtin type kind"); 5940 } 5941 5942 /// Check an argument list for placeholders that we won't try to 5943 /// handle later. 5944 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5945 // Apply this processing to all the arguments at once instead of 5946 // dying at the first failure. 5947 bool hasInvalid = false; 5948 for (size_t i = 0, e = args.size(); i != e; i++) { 5949 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5950 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5951 if (result.isInvalid()) hasInvalid = true; 5952 else args[i] = result.get(); 5953 } else if (hasInvalid) { 5954 (void)S.CorrectDelayedTyposInExpr(args[i]); 5955 } 5956 } 5957 return hasInvalid; 5958 } 5959 5960 /// If a builtin function has a pointer argument with no explicit address 5961 /// space, then it should be able to accept a pointer to any address 5962 /// space as input. In order to do this, we need to replace the 5963 /// standard builtin declaration with one that uses the same address space 5964 /// as the call. 5965 /// 5966 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5967 /// it does not contain any pointer arguments without 5968 /// an address space qualifer. Otherwise the rewritten 5969 /// FunctionDecl is returned. 5970 /// TODO: Handle pointer return types. 5971 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5972 FunctionDecl *FDecl, 5973 MultiExprArg ArgExprs) { 5974 5975 QualType DeclType = FDecl->getType(); 5976 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5977 5978 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 5979 ArgExprs.size() < FT->getNumParams()) 5980 return nullptr; 5981 5982 bool NeedsNewDecl = false; 5983 unsigned i = 0; 5984 SmallVector<QualType, 8> OverloadParams; 5985 5986 for (QualType ParamType : FT->param_types()) { 5987 5988 // Convert array arguments to pointer to simplify type lookup. 5989 ExprResult ArgRes = 5990 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5991 if (ArgRes.isInvalid()) 5992 return nullptr; 5993 Expr *Arg = ArgRes.get(); 5994 QualType ArgType = Arg->getType(); 5995 if (!ParamType->isPointerType() || 5996 ParamType.hasAddressSpace() || 5997 !ArgType->isPointerType() || 5998 !ArgType->getPointeeType().hasAddressSpace()) { 5999 OverloadParams.push_back(ParamType); 6000 continue; 6001 } 6002 6003 QualType PointeeType = ParamType->getPointeeType(); 6004 if (PointeeType.hasAddressSpace()) 6005 continue; 6006 6007 NeedsNewDecl = true; 6008 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6009 6010 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6011 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6012 } 6013 6014 if (!NeedsNewDecl) 6015 return nullptr; 6016 6017 FunctionProtoType::ExtProtoInfo EPI; 6018 EPI.Variadic = FT->isVariadic(); 6019 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6020 OverloadParams, EPI); 6021 DeclContext *Parent = FDecl->getParent(); 6022 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6023 FDecl->getLocation(), 6024 FDecl->getLocation(), 6025 FDecl->getIdentifier(), 6026 OverloadTy, 6027 /*TInfo=*/nullptr, 6028 SC_Extern, false, 6029 /*hasPrototype=*/true); 6030 SmallVector<ParmVarDecl*, 16> Params; 6031 FT = cast<FunctionProtoType>(OverloadTy); 6032 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6033 QualType ParamType = FT->getParamType(i); 6034 ParmVarDecl *Parm = 6035 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6036 SourceLocation(), nullptr, ParamType, 6037 /*TInfo=*/nullptr, SC_None, nullptr); 6038 Parm->setScopeInfo(0, i); 6039 Params.push_back(Parm); 6040 } 6041 OverloadDecl->setParams(Params); 6042 return OverloadDecl; 6043 } 6044 6045 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6046 FunctionDecl *Callee, 6047 MultiExprArg ArgExprs) { 6048 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6049 // similar attributes) really don't like it when functions are called with an 6050 // invalid number of args. 6051 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6052 /*PartialOverloading=*/false) && 6053 !Callee->isVariadic()) 6054 return; 6055 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6056 return; 6057 6058 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 6059 S.Diag(Fn->getBeginLoc(), 6060 isa<CXXMethodDecl>(Callee) 6061 ? diag::err_ovl_no_viable_member_function_in_call 6062 : diag::err_ovl_no_viable_function_in_call) 6063 << Callee << Callee->getSourceRange(); 6064 S.Diag(Callee->getLocation(), 6065 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6066 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6067 return; 6068 } 6069 } 6070 6071 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6072 const UnresolvedMemberExpr *const UME, Sema &S) { 6073 6074 const auto GetFunctionLevelDCIfCXXClass = 6075 [](Sema &S) -> const CXXRecordDecl * { 6076 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6077 if (!DC || !DC->getParent()) 6078 return nullptr; 6079 6080 // If the call to some member function was made from within a member 6081 // function body 'M' return return 'M's parent. 6082 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6083 return MD->getParent()->getCanonicalDecl(); 6084 // else the call was made from within a default member initializer of a 6085 // class, so return the class. 6086 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6087 return RD->getCanonicalDecl(); 6088 return nullptr; 6089 }; 6090 // If our DeclContext is neither a member function nor a class (in the 6091 // case of a lambda in a default member initializer), we can't have an 6092 // enclosing 'this'. 6093 6094 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6095 if (!CurParentClass) 6096 return false; 6097 6098 // The naming class for implicit member functions call is the class in which 6099 // name lookup starts. 6100 const CXXRecordDecl *const NamingClass = 6101 UME->getNamingClass()->getCanonicalDecl(); 6102 assert(NamingClass && "Must have naming class even for implicit access"); 6103 6104 // If the unresolved member functions were found in a 'naming class' that is 6105 // related (either the same or derived from) to the class that contains the 6106 // member function that itself contained the implicit member access. 6107 6108 return CurParentClass == NamingClass || 6109 CurParentClass->isDerivedFrom(NamingClass); 6110 } 6111 6112 static void 6113 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6114 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6115 6116 if (!UME) 6117 return; 6118 6119 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6120 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6121 // already been captured, or if this is an implicit member function call (if 6122 // it isn't, an attempt to capture 'this' should already have been made). 6123 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6124 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6125 return; 6126 6127 // Check if the naming class in which the unresolved members were found is 6128 // related (same as or is a base of) to the enclosing class. 6129 6130 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6131 return; 6132 6133 6134 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6135 // If the enclosing function is not dependent, then this lambda is 6136 // capture ready, so if we can capture this, do so. 6137 if (!EnclosingFunctionCtx->isDependentContext()) { 6138 // If the current lambda and all enclosing lambdas can capture 'this' - 6139 // then go ahead and capture 'this' (since our unresolved overload set 6140 // contains at least one non-static member function). 6141 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6142 S.CheckCXXThisCapture(CallLoc); 6143 } else if (S.CurContext->isDependentContext()) { 6144 // ... since this is an implicit member reference, that might potentially 6145 // involve a 'this' capture, mark 'this' for potential capture in 6146 // enclosing lambdas. 6147 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6148 CurLSI->addPotentialThisCapture(CallLoc); 6149 } 6150 } 6151 6152 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6153 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6154 Expr *ExecConfig) { 6155 ExprResult Call = 6156 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 6157 if (Call.isInvalid()) 6158 return Call; 6159 6160 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6161 // language modes. 6162 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6163 if (ULE->hasExplicitTemplateArgs() && 6164 ULE->decls_begin() == ULE->decls_end()) { 6165 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6166 ? diag::warn_cxx17_compat_adl_only_template_id 6167 : diag::ext_adl_only_template_id) 6168 << ULE->getName(); 6169 } 6170 } 6171 6172 if (LangOpts.OpenMP) 6173 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6174 ExecConfig); 6175 6176 return Call; 6177 } 6178 6179 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6180 /// This provides the location of the left/right parens and a list of comma 6181 /// locations. 6182 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6183 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6184 Expr *ExecConfig, bool IsExecConfig) { 6185 // Since this might be a postfix expression, get rid of ParenListExprs. 6186 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6187 if (Result.isInvalid()) return ExprError(); 6188 Fn = Result.get(); 6189 6190 if (checkArgsForPlaceholders(*this, ArgExprs)) 6191 return ExprError(); 6192 6193 if (getLangOpts().CPlusPlus) { 6194 // If this is a pseudo-destructor expression, build the call immediately. 6195 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6196 if (!ArgExprs.empty()) { 6197 // Pseudo-destructor calls should not have any arguments. 6198 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6199 << FixItHint::CreateRemoval( 6200 SourceRange(ArgExprs.front()->getBeginLoc(), 6201 ArgExprs.back()->getEndLoc())); 6202 } 6203 6204 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6205 VK_RValue, RParenLoc); 6206 } 6207 if (Fn->getType() == Context.PseudoObjectTy) { 6208 ExprResult result = CheckPlaceholderExpr(Fn); 6209 if (result.isInvalid()) return ExprError(); 6210 Fn = result.get(); 6211 } 6212 6213 // Determine whether this is a dependent call inside a C++ template, 6214 // in which case we won't do any semantic analysis now. 6215 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6216 if (ExecConfig) { 6217 return CUDAKernelCallExpr::Create( 6218 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 6219 Context.DependentTy, VK_RValue, RParenLoc); 6220 } else { 6221 6222 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6223 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6224 Fn->getBeginLoc()); 6225 6226 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6227 VK_RValue, RParenLoc); 6228 } 6229 } 6230 6231 // Determine whether this is a call to an object (C++ [over.call.object]). 6232 if (Fn->getType()->isRecordType()) 6233 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6234 RParenLoc); 6235 6236 if (Fn->getType() == Context.UnknownAnyTy) { 6237 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6238 if (result.isInvalid()) return ExprError(); 6239 Fn = result.get(); 6240 } 6241 6242 if (Fn->getType() == Context.BoundMemberTy) { 6243 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6244 RParenLoc); 6245 } 6246 } 6247 6248 // Check for overloaded calls. This can happen even in C due to extensions. 6249 if (Fn->getType() == Context.OverloadTy) { 6250 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6251 6252 // We aren't supposed to apply this logic if there's an '&' involved. 6253 if (!find.HasFormOfMemberPointer) { 6254 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6255 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6256 VK_RValue, RParenLoc); 6257 OverloadExpr *ovl = find.Expression; 6258 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6259 return BuildOverloadedCallExpr( 6260 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6261 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6262 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6263 RParenLoc); 6264 } 6265 } 6266 6267 // If we're directly calling a function, get the appropriate declaration. 6268 if (Fn->getType() == Context.UnknownAnyTy) { 6269 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6270 if (result.isInvalid()) return ExprError(); 6271 Fn = result.get(); 6272 } 6273 6274 Expr *NakedFn = Fn->IgnoreParens(); 6275 6276 bool CallingNDeclIndirectly = false; 6277 NamedDecl *NDecl = nullptr; 6278 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6279 if (UnOp->getOpcode() == UO_AddrOf) { 6280 CallingNDeclIndirectly = true; 6281 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6282 } 6283 } 6284 6285 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6286 NDecl = DRE->getDecl(); 6287 6288 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6289 if (FDecl && FDecl->getBuiltinID()) { 6290 // Rewrite the function decl for this builtin by replacing parameters 6291 // with no explicit address space with the address space of the arguments 6292 // in ArgExprs. 6293 if ((FDecl = 6294 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6295 NDecl = FDecl; 6296 Fn = DeclRefExpr::Create( 6297 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6298 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6299 nullptr, DRE->isNonOdrUse()); 6300 } 6301 } 6302 } else if (isa<MemberExpr>(NakedFn)) 6303 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6304 6305 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6306 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6307 FD, /*Complain=*/true, Fn->getBeginLoc())) 6308 return ExprError(); 6309 6310 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 6311 return ExprError(); 6312 6313 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6314 } 6315 6316 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6317 ExecConfig, IsExecConfig); 6318 } 6319 6320 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 6321 /// 6322 /// __builtin_astype( value, dst type ) 6323 /// 6324 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6325 SourceLocation BuiltinLoc, 6326 SourceLocation RParenLoc) { 6327 ExprValueKind VK = VK_RValue; 6328 ExprObjectKind OK = OK_Ordinary; 6329 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6330 QualType SrcTy = E->getType(); 6331 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 6332 return ExprError(Diag(BuiltinLoc, 6333 diag::err_invalid_astype_of_different_size) 6334 << DstTy 6335 << SrcTy 6336 << E->getSourceRange()); 6337 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6338 } 6339 6340 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6341 /// provided arguments. 6342 /// 6343 /// __builtin_convertvector( value, dst type ) 6344 /// 6345 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6346 SourceLocation BuiltinLoc, 6347 SourceLocation RParenLoc) { 6348 TypeSourceInfo *TInfo; 6349 GetTypeFromParser(ParsedDestTy, &TInfo); 6350 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6351 } 6352 6353 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6354 /// i.e. an expression not of \p OverloadTy. The expression should 6355 /// unary-convert to an expression of function-pointer or 6356 /// block-pointer type. 6357 /// 6358 /// \param NDecl the declaration being called, if available 6359 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6360 SourceLocation LParenLoc, 6361 ArrayRef<Expr *> Args, 6362 SourceLocation RParenLoc, Expr *Config, 6363 bool IsExecConfig, ADLCallKind UsesADL) { 6364 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6365 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6366 6367 // Functions with 'interrupt' attribute cannot be called directly. 6368 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6369 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6370 return ExprError(); 6371 } 6372 6373 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6374 // so there's some risk when calling out to non-interrupt handler functions 6375 // that the callee might not preserve them. This is easy to diagnose here, 6376 // but can be very challenging to debug. 6377 if (auto *Caller = getCurFunctionDecl()) 6378 if (Caller->hasAttr<ARMInterruptAttr>()) { 6379 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6380 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 6381 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6382 } 6383 6384 // Promote the function operand. 6385 // We special-case function promotion here because we only allow promoting 6386 // builtin functions to function pointers in the callee of a call. 6387 ExprResult Result; 6388 QualType ResultTy; 6389 if (BuiltinID && 6390 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6391 // Extract the return type from the (builtin) function pointer type. 6392 // FIXME Several builtins still have setType in 6393 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6394 // Builtins.def to ensure they are correct before removing setType calls. 6395 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6396 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6397 ResultTy = FDecl->getCallResultType(); 6398 } else { 6399 Result = CallExprUnaryConversions(Fn); 6400 ResultTy = Context.BoolTy; 6401 } 6402 if (Result.isInvalid()) 6403 return ExprError(); 6404 Fn = Result.get(); 6405 6406 // Check for a valid function type, but only if it is not a builtin which 6407 // requires custom type checking. These will be handled by 6408 // CheckBuiltinFunctionCall below just after creation of the call expression. 6409 const FunctionType *FuncT = nullptr; 6410 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6411 retry: 6412 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6413 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6414 // have type pointer to function". 6415 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6416 if (!FuncT) 6417 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6418 << Fn->getType() << Fn->getSourceRange()); 6419 } else if (const BlockPointerType *BPT = 6420 Fn->getType()->getAs<BlockPointerType>()) { 6421 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6422 } else { 6423 // Handle calls to expressions of unknown-any type. 6424 if (Fn->getType() == Context.UnknownAnyTy) { 6425 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6426 if (rewrite.isInvalid()) 6427 return ExprError(); 6428 Fn = rewrite.get(); 6429 goto retry; 6430 } 6431 6432 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6433 << Fn->getType() << Fn->getSourceRange()); 6434 } 6435 } 6436 6437 // Get the number of parameters in the function prototype, if any. 6438 // We will allocate space for max(Args.size(), NumParams) arguments 6439 // in the call expression. 6440 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6441 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6442 6443 CallExpr *TheCall; 6444 if (Config) { 6445 assert(UsesADL == ADLCallKind::NotADL && 6446 "CUDAKernelCallExpr should not use ADL"); 6447 TheCall = 6448 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 6449 ResultTy, VK_RValue, RParenLoc, NumParams); 6450 } else { 6451 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 6452 RParenLoc, NumParams, UsesADL); 6453 } 6454 6455 if (!getLangOpts().CPlusPlus) { 6456 // Forget about the nulled arguments since typo correction 6457 // do not handle them well. 6458 TheCall->shrinkNumArgs(Args.size()); 6459 // C cannot always handle TypoExpr nodes in builtin calls and direct 6460 // function calls as their argument checking don't necessarily handle 6461 // dependent types properly, so make sure any TypoExprs have been 6462 // dealt with. 6463 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6464 if (!Result.isUsable()) return ExprError(); 6465 CallExpr *TheOldCall = TheCall; 6466 TheCall = dyn_cast<CallExpr>(Result.get()); 6467 bool CorrectedTypos = TheCall != TheOldCall; 6468 if (!TheCall) return Result; 6469 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6470 6471 // A new call expression node was created if some typos were corrected. 6472 // However it may not have been constructed with enough storage. In this 6473 // case, rebuild the node with enough storage. The waste of space is 6474 // immaterial since this only happens when some typos were corrected. 6475 if (CorrectedTypos && Args.size() < NumParams) { 6476 if (Config) 6477 TheCall = CUDAKernelCallExpr::Create( 6478 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6479 RParenLoc, NumParams); 6480 else 6481 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 6482 RParenLoc, NumParams, UsesADL); 6483 } 6484 // We can now handle the nulled arguments for the default arguments. 6485 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6486 } 6487 6488 // Bail out early if calling a builtin with custom type checking. 6489 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6490 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6491 6492 if (getLangOpts().CUDA) { 6493 if (Config) { 6494 // CUDA: Kernel calls must be to global functions 6495 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6496 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6497 << FDecl << Fn->getSourceRange()); 6498 6499 // CUDA: Kernel function must have 'void' return type 6500 if (!FuncT->getReturnType()->isVoidType() && 6501 !FuncT->getReturnType()->getAs<AutoType>() && 6502 !FuncT->getReturnType()->isInstantiationDependentType()) 6503 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6504 << Fn->getType() << Fn->getSourceRange()); 6505 } else { 6506 // CUDA: Calls to global functions must be configured 6507 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6508 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6509 << FDecl << Fn->getSourceRange()); 6510 } 6511 } 6512 6513 // Check for a valid return type 6514 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6515 FDecl)) 6516 return ExprError(); 6517 6518 // We know the result type of the call, set it. 6519 TheCall->setType(FuncT->getCallResultType(Context)); 6520 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6521 6522 if (Proto) { 6523 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6524 IsExecConfig)) 6525 return ExprError(); 6526 } else { 6527 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6528 6529 if (FDecl) { 6530 // Check if we have too few/too many template arguments, based 6531 // on our knowledge of the function definition. 6532 const FunctionDecl *Def = nullptr; 6533 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6534 Proto = Def->getType()->getAs<FunctionProtoType>(); 6535 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6536 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6537 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6538 } 6539 6540 // If the function we're calling isn't a function prototype, but we have 6541 // a function prototype from a prior declaratiom, use that prototype. 6542 if (!FDecl->hasPrototype()) 6543 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6544 } 6545 6546 // Promote the arguments (C99 6.5.2.2p6). 6547 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6548 Expr *Arg = Args[i]; 6549 6550 if (Proto && i < Proto->getNumParams()) { 6551 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6552 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6553 ExprResult ArgE = 6554 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6555 if (ArgE.isInvalid()) 6556 return true; 6557 6558 Arg = ArgE.getAs<Expr>(); 6559 6560 } else { 6561 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6562 6563 if (ArgE.isInvalid()) 6564 return true; 6565 6566 Arg = ArgE.getAs<Expr>(); 6567 } 6568 6569 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6570 diag::err_call_incomplete_argument, Arg)) 6571 return ExprError(); 6572 6573 TheCall->setArg(i, Arg); 6574 } 6575 } 6576 6577 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6578 if (!Method->isStatic()) 6579 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6580 << Fn->getSourceRange()); 6581 6582 // Check for sentinels 6583 if (NDecl) 6584 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6585 6586 // Warn for unions passing across security boundary (CMSE). 6587 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6588 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6589 if (const auto *RT = 6590 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6591 if (RT->getDecl()->isOrContainsUnion()) 6592 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6593 << 0 << i; 6594 } 6595 } 6596 } 6597 6598 // Do special checking on direct calls to functions. 6599 if (FDecl) { 6600 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6601 return ExprError(); 6602 6603 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6604 6605 if (BuiltinID) 6606 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6607 } else if (NDecl) { 6608 if (CheckPointerCall(NDecl, TheCall, Proto)) 6609 return ExprError(); 6610 } else { 6611 if (CheckOtherCall(TheCall, Proto)) 6612 return ExprError(); 6613 } 6614 6615 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6616 } 6617 6618 ExprResult 6619 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6620 SourceLocation RParenLoc, Expr *InitExpr) { 6621 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6622 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6623 6624 TypeSourceInfo *TInfo; 6625 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6626 if (!TInfo) 6627 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6628 6629 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6630 } 6631 6632 ExprResult 6633 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6634 SourceLocation RParenLoc, Expr *LiteralExpr) { 6635 QualType literalType = TInfo->getType(); 6636 6637 if (literalType->isArrayType()) { 6638 if (RequireCompleteSizedType( 6639 LParenLoc, Context.getBaseElementType(literalType), 6640 diag::err_array_incomplete_or_sizeless_type, 6641 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6642 return ExprError(); 6643 if (literalType->isVariableArrayType()) 6644 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6645 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6646 } else if (!literalType->isDependentType() && 6647 RequireCompleteType(LParenLoc, literalType, 6648 diag::err_typecheck_decl_incomplete_type, 6649 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6650 return ExprError(); 6651 6652 InitializedEntity Entity 6653 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6654 InitializationKind Kind 6655 = InitializationKind::CreateCStyleCast(LParenLoc, 6656 SourceRange(LParenLoc, RParenLoc), 6657 /*InitList=*/true); 6658 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6659 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6660 &literalType); 6661 if (Result.isInvalid()) 6662 return ExprError(); 6663 LiteralExpr = Result.get(); 6664 6665 bool isFileScope = !CurContext->isFunctionOrMethod(); 6666 6667 // In C, compound literals are l-values for some reason. 6668 // For GCC compatibility, in C++, file-scope array compound literals with 6669 // constant initializers are also l-values, and compound literals are 6670 // otherwise prvalues. 6671 // 6672 // (GCC also treats C++ list-initialized file-scope array prvalues with 6673 // constant initializers as l-values, but that's non-conforming, so we don't 6674 // follow it there.) 6675 // 6676 // FIXME: It would be better to handle the lvalue cases as materializing and 6677 // lifetime-extending a temporary object, but our materialized temporaries 6678 // representation only supports lifetime extension from a variable, not "out 6679 // of thin air". 6680 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6681 // is bound to the result of applying array-to-pointer decay to the compound 6682 // literal. 6683 // FIXME: GCC supports compound literals of reference type, which should 6684 // obviously have a value kind derived from the kind of reference involved. 6685 ExprValueKind VK = 6686 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6687 ? VK_RValue 6688 : VK_LValue; 6689 6690 if (isFileScope) 6691 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6692 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6693 Expr *Init = ILE->getInit(i); 6694 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6695 } 6696 6697 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6698 VK, LiteralExpr, isFileScope); 6699 if (isFileScope) { 6700 if (!LiteralExpr->isTypeDependent() && 6701 !LiteralExpr->isValueDependent() && 6702 !literalType->isDependentType()) // C99 6.5.2.5p3 6703 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6704 return ExprError(); 6705 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6706 literalType.getAddressSpace() != LangAS::Default) { 6707 // Embedded-C extensions to C99 6.5.2.5: 6708 // "If the compound literal occurs inside the body of a function, the 6709 // type name shall not be qualified by an address-space qualifier." 6710 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6711 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6712 return ExprError(); 6713 } 6714 6715 if (!isFileScope && !getLangOpts().CPlusPlus) { 6716 // Compound literals that have automatic storage duration are destroyed at 6717 // the end of the scope in C; in C++, they're just temporaries. 6718 6719 // Emit diagnostics if it is or contains a C union type that is non-trivial 6720 // to destruct. 6721 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6722 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6723 NTCUC_CompoundLiteral, NTCUK_Destruct); 6724 6725 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6726 if (literalType.isDestructedType()) { 6727 Cleanup.setExprNeedsCleanups(true); 6728 ExprCleanupObjects.push_back(E); 6729 getCurFunction()->setHasBranchProtectedScope(); 6730 } 6731 } 6732 6733 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6734 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6735 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6736 E->getInitializer()->getExprLoc()); 6737 6738 return MaybeBindToTemporary(E); 6739 } 6740 6741 ExprResult 6742 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6743 SourceLocation RBraceLoc) { 6744 // Only produce each kind of designated initialization diagnostic once. 6745 SourceLocation FirstDesignator; 6746 bool DiagnosedArrayDesignator = false; 6747 bool DiagnosedNestedDesignator = false; 6748 bool DiagnosedMixedDesignator = false; 6749 6750 // Check that any designated initializers are syntactically valid in the 6751 // current language mode. 6752 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6753 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6754 if (FirstDesignator.isInvalid()) 6755 FirstDesignator = DIE->getBeginLoc(); 6756 6757 if (!getLangOpts().CPlusPlus) 6758 break; 6759 6760 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6761 DiagnosedNestedDesignator = true; 6762 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6763 << DIE->getDesignatorsSourceRange(); 6764 } 6765 6766 for (auto &Desig : DIE->designators()) { 6767 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6768 DiagnosedArrayDesignator = true; 6769 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6770 << Desig.getSourceRange(); 6771 } 6772 } 6773 6774 if (!DiagnosedMixedDesignator && 6775 !isa<DesignatedInitExpr>(InitArgList[0])) { 6776 DiagnosedMixedDesignator = true; 6777 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6778 << DIE->getSourceRange(); 6779 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6780 << InitArgList[0]->getSourceRange(); 6781 } 6782 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6783 isa<DesignatedInitExpr>(InitArgList[0])) { 6784 DiagnosedMixedDesignator = true; 6785 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6786 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6787 << DIE->getSourceRange(); 6788 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6789 << InitArgList[I]->getSourceRange(); 6790 } 6791 } 6792 6793 if (FirstDesignator.isValid()) { 6794 // Only diagnose designated initiaization as a C++20 extension if we didn't 6795 // already diagnose use of (non-C++20) C99 designator syntax. 6796 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6797 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6798 Diag(FirstDesignator, getLangOpts().CPlusPlus20 6799 ? diag::warn_cxx17_compat_designated_init 6800 : diag::ext_cxx_designated_init); 6801 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6802 Diag(FirstDesignator, diag::ext_designated_init); 6803 } 6804 } 6805 6806 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6807 } 6808 6809 ExprResult 6810 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6811 SourceLocation RBraceLoc) { 6812 // Semantic analysis for initializers is done by ActOnDeclarator() and 6813 // CheckInitializer() - it requires knowledge of the object being initialized. 6814 6815 // Immediately handle non-overload placeholders. Overloads can be 6816 // resolved contextually, but everything else here can't. 6817 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6818 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6819 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6820 6821 // Ignore failures; dropping the entire initializer list because 6822 // of one failure would be terrible for indexing/etc. 6823 if (result.isInvalid()) continue; 6824 6825 InitArgList[I] = result.get(); 6826 } 6827 } 6828 6829 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6830 RBraceLoc); 6831 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6832 return E; 6833 } 6834 6835 /// Do an explicit extend of the given block pointer if we're in ARC. 6836 void Sema::maybeExtendBlockObject(ExprResult &E) { 6837 assert(E.get()->getType()->isBlockPointerType()); 6838 assert(E.get()->isRValue()); 6839 6840 // Only do this in an r-value context. 6841 if (!getLangOpts().ObjCAutoRefCount) return; 6842 6843 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6844 CK_ARCExtendBlockObject, E.get(), 6845 /*base path*/ nullptr, VK_RValue); 6846 Cleanup.setExprNeedsCleanups(true); 6847 } 6848 6849 /// Prepare a conversion of the given expression to an ObjC object 6850 /// pointer type. 6851 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6852 QualType type = E.get()->getType(); 6853 if (type->isObjCObjectPointerType()) { 6854 return CK_BitCast; 6855 } else if (type->isBlockPointerType()) { 6856 maybeExtendBlockObject(E); 6857 return CK_BlockPointerToObjCPointerCast; 6858 } else { 6859 assert(type->isPointerType()); 6860 return CK_CPointerToObjCPointerCast; 6861 } 6862 } 6863 6864 /// Prepares for a scalar cast, performing all the necessary stages 6865 /// except the final cast and returning the kind required. 6866 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6867 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6868 // Also, callers should have filtered out the invalid cases with 6869 // pointers. Everything else should be possible. 6870 6871 QualType SrcTy = Src.get()->getType(); 6872 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6873 return CK_NoOp; 6874 6875 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6876 case Type::STK_MemberPointer: 6877 llvm_unreachable("member pointer type in C"); 6878 6879 case Type::STK_CPointer: 6880 case Type::STK_BlockPointer: 6881 case Type::STK_ObjCObjectPointer: 6882 switch (DestTy->getScalarTypeKind()) { 6883 case Type::STK_CPointer: { 6884 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 6885 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 6886 if (SrcAS != DestAS) 6887 return CK_AddressSpaceConversion; 6888 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 6889 return CK_NoOp; 6890 return CK_BitCast; 6891 } 6892 case Type::STK_BlockPointer: 6893 return (SrcKind == Type::STK_BlockPointer 6894 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 6895 case Type::STK_ObjCObjectPointer: 6896 if (SrcKind == Type::STK_ObjCObjectPointer) 6897 return CK_BitCast; 6898 if (SrcKind == Type::STK_CPointer) 6899 return CK_CPointerToObjCPointerCast; 6900 maybeExtendBlockObject(Src); 6901 return CK_BlockPointerToObjCPointerCast; 6902 case Type::STK_Bool: 6903 return CK_PointerToBoolean; 6904 case Type::STK_Integral: 6905 return CK_PointerToIntegral; 6906 case Type::STK_Floating: 6907 case Type::STK_FloatingComplex: 6908 case Type::STK_IntegralComplex: 6909 case Type::STK_MemberPointer: 6910 case Type::STK_FixedPoint: 6911 llvm_unreachable("illegal cast from pointer"); 6912 } 6913 llvm_unreachable("Should have returned before this"); 6914 6915 case Type::STK_FixedPoint: 6916 switch (DestTy->getScalarTypeKind()) { 6917 case Type::STK_FixedPoint: 6918 return CK_FixedPointCast; 6919 case Type::STK_Bool: 6920 return CK_FixedPointToBoolean; 6921 case Type::STK_Integral: 6922 return CK_FixedPointToIntegral; 6923 case Type::STK_Floating: 6924 case Type::STK_IntegralComplex: 6925 case Type::STK_FloatingComplex: 6926 Diag(Src.get()->getExprLoc(), 6927 diag::err_unimplemented_conversion_with_fixed_point_type) 6928 << DestTy; 6929 return CK_IntegralCast; 6930 case Type::STK_CPointer: 6931 case Type::STK_ObjCObjectPointer: 6932 case Type::STK_BlockPointer: 6933 case Type::STK_MemberPointer: 6934 llvm_unreachable("illegal cast to pointer type"); 6935 } 6936 llvm_unreachable("Should have returned before this"); 6937 6938 case Type::STK_Bool: // casting from bool is like casting from an integer 6939 case Type::STK_Integral: 6940 switch (DestTy->getScalarTypeKind()) { 6941 case Type::STK_CPointer: 6942 case Type::STK_ObjCObjectPointer: 6943 case Type::STK_BlockPointer: 6944 if (Src.get()->isNullPointerConstant(Context, 6945 Expr::NPC_ValueDependentIsNull)) 6946 return CK_NullToPointer; 6947 return CK_IntegralToPointer; 6948 case Type::STK_Bool: 6949 return CK_IntegralToBoolean; 6950 case Type::STK_Integral: 6951 return CK_IntegralCast; 6952 case Type::STK_Floating: 6953 return CK_IntegralToFloating; 6954 case Type::STK_IntegralComplex: 6955 Src = ImpCastExprToType(Src.get(), 6956 DestTy->castAs<ComplexType>()->getElementType(), 6957 CK_IntegralCast); 6958 return CK_IntegralRealToComplex; 6959 case Type::STK_FloatingComplex: 6960 Src = ImpCastExprToType(Src.get(), 6961 DestTy->castAs<ComplexType>()->getElementType(), 6962 CK_IntegralToFloating); 6963 return CK_FloatingRealToComplex; 6964 case Type::STK_MemberPointer: 6965 llvm_unreachable("member pointer type in C"); 6966 case Type::STK_FixedPoint: 6967 return CK_IntegralToFixedPoint; 6968 } 6969 llvm_unreachable("Should have returned before this"); 6970 6971 case Type::STK_Floating: 6972 switch (DestTy->getScalarTypeKind()) { 6973 case Type::STK_Floating: 6974 return CK_FloatingCast; 6975 case Type::STK_Bool: 6976 return CK_FloatingToBoolean; 6977 case Type::STK_Integral: 6978 return CK_FloatingToIntegral; 6979 case Type::STK_FloatingComplex: 6980 Src = ImpCastExprToType(Src.get(), 6981 DestTy->castAs<ComplexType>()->getElementType(), 6982 CK_FloatingCast); 6983 return CK_FloatingRealToComplex; 6984 case Type::STK_IntegralComplex: 6985 Src = ImpCastExprToType(Src.get(), 6986 DestTy->castAs<ComplexType>()->getElementType(), 6987 CK_FloatingToIntegral); 6988 return CK_IntegralRealToComplex; 6989 case Type::STK_CPointer: 6990 case Type::STK_ObjCObjectPointer: 6991 case Type::STK_BlockPointer: 6992 llvm_unreachable("valid float->pointer cast?"); 6993 case Type::STK_MemberPointer: 6994 llvm_unreachable("member pointer type in C"); 6995 case Type::STK_FixedPoint: 6996 Diag(Src.get()->getExprLoc(), 6997 diag::err_unimplemented_conversion_with_fixed_point_type) 6998 << SrcTy; 6999 return CK_IntegralCast; 7000 } 7001 llvm_unreachable("Should have returned before this"); 7002 7003 case Type::STK_FloatingComplex: 7004 switch (DestTy->getScalarTypeKind()) { 7005 case Type::STK_FloatingComplex: 7006 return CK_FloatingComplexCast; 7007 case Type::STK_IntegralComplex: 7008 return CK_FloatingComplexToIntegralComplex; 7009 case Type::STK_Floating: { 7010 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7011 if (Context.hasSameType(ET, DestTy)) 7012 return CK_FloatingComplexToReal; 7013 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7014 return CK_FloatingCast; 7015 } 7016 case Type::STK_Bool: 7017 return CK_FloatingComplexToBoolean; 7018 case Type::STK_Integral: 7019 Src = ImpCastExprToType(Src.get(), 7020 SrcTy->castAs<ComplexType>()->getElementType(), 7021 CK_FloatingComplexToReal); 7022 return CK_FloatingToIntegral; 7023 case Type::STK_CPointer: 7024 case Type::STK_ObjCObjectPointer: 7025 case Type::STK_BlockPointer: 7026 llvm_unreachable("valid complex float->pointer cast?"); 7027 case Type::STK_MemberPointer: 7028 llvm_unreachable("member pointer type in C"); 7029 case Type::STK_FixedPoint: 7030 Diag(Src.get()->getExprLoc(), 7031 diag::err_unimplemented_conversion_with_fixed_point_type) 7032 << SrcTy; 7033 return CK_IntegralCast; 7034 } 7035 llvm_unreachable("Should have returned before this"); 7036 7037 case Type::STK_IntegralComplex: 7038 switch (DestTy->getScalarTypeKind()) { 7039 case Type::STK_FloatingComplex: 7040 return CK_IntegralComplexToFloatingComplex; 7041 case Type::STK_IntegralComplex: 7042 return CK_IntegralComplexCast; 7043 case Type::STK_Integral: { 7044 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7045 if (Context.hasSameType(ET, DestTy)) 7046 return CK_IntegralComplexToReal; 7047 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7048 return CK_IntegralCast; 7049 } 7050 case Type::STK_Bool: 7051 return CK_IntegralComplexToBoolean; 7052 case Type::STK_Floating: 7053 Src = ImpCastExprToType(Src.get(), 7054 SrcTy->castAs<ComplexType>()->getElementType(), 7055 CK_IntegralComplexToReal); 7056 return CK_IntegralToFloating; 7057 case Type::STK_CPointer: 7058 case Type::STK_ObjCObjectPointer: 7059 case Type::STK_BlockPointer: 7060 llvm_unreachable("valid complex int->pointer cast?"); 7061 case Type::STK_MemberPointer: 7062 llvm_unreachable("member pointer type in C"); 7063 case Type::STK_FixedPoint: 7064 Diag(Src.get()->getExprLoc(), 7065 diag::err_unimplemented_conversion_with_fixed_point_type) 7066 << SrcTy; 7067 return CK_IntegralCast; 7068 } 7069 llvm_unreachable("Should have returned before this"); 7070 } 7071 7072 llvm_unreachable("Unhandled scalar cast"); 7073 } 7074 7075 static bool breakDownVectorType(QualType type, uint64_t &len, 7076 QualType &eltType) { 7077 // Vectors are simple. 7078 if (const VectorType *vecType = type->getAs<VectorType>()) { 7079 len = vecType->getNumElements(); 7080 eltType = vecType->getElementType(); 7081 assert(eltType->isScalarType()); 7082 return true; 7083 } 7084 7085 // We allow lax conversion to and from non-vector types, but only if 7086 // they're real types (i.e. non-complex, non-pointer scalar types). 7087 if (!type->isRealType()) return false; 7088 7089 len = 1; 7090 eltType = type; 7091 return true; 7092 } 7093 7094 /// Are the two types lax-compatible vector types? That is, given 7095 /// that one of them is a vector, do they have equal storage sizes, 7096 /// where the storage size is the number of elements times the element 7097 /// size? 7098 /// 7099 /// This will also return false if either of the types is neither a 7100 /// vector nor a real type. 7101 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7102 assert(destTy->isVectorType() || srcTy->isVectorType()); 7103 7104 // Disallow lax conversions between scalars and ExtVectors (these 7105 // conversions are allowed for other vector types because common headers 7106 // depend on them). Most scalar OP ExtVector cases are handled by the 7107 // splat path anyway, which does what we want (convert, not bitcast). 7108 // What this rules out for ExtVectors is crazy things like char4*float. 7109 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7110 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7111 7112 uint64_t srcLen, destLen; 7113 QualType srcEltTy, destEltTy; 7114 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 7115 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 7116 7117 // ASTContext::getTypeSize will return the size rounded up to a 7118 // power of 2, so instead of using that, we need to use the raw 7119 // element size multiplied by the element count. 7120 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 7121 uint64_t destEltSize = Context.getTypeSize(destEltTy); 7122 7123 return (srcLen * srcEltSize == destLen * destEltSize); 7124 } 7125 7126 /// Is this a legal conversion between two types, one of which is 7127 /// known to be a vector type? 7128 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7129 assert(destTy->isVectorType() || srcTy->isVectorType()); 7130 7131 switch (Context.getLangOpts().getLaxVectorConversions()) { 7132 case LangOptions::LaxVectorConversionKind::None: 7133 return false; 7134 7135 case LangOptions::LaxVectorConversionKind::Integer: 7136 if (!srcTy->isIntegralOrEnumerationType()) { 7137 auto *Vec = srcTy->getAs<VectorType>(); 7138 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7139 return false; 7140 } 7141 if (!destTy->isIntegralOrEnumerationType()) { 7142 auto *Vec = destTy->getAs<VectorType>(); 7143 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7144 return false; 7145 } 7146 // OK, integer (vector) -> integer (vector) bitcast. 7147 break; 7148 7149 case LangOptions::LaxVectorConversionKind::All: 7150 break; 7151 } 7152 7153 return areLaxCompatibleVectorTypes(srcTy, destTy); 7154 } 7155 7156 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7157 CastKind &Kind) { 7158 assert(VectorTy->isVectorType() && "Not a vector type!"); 7159 7160 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7161 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7162 return Diag(R.getBegin(), 7163 Ty->isVectorType() ? 7164 diag::err_invalid_conversion_between_vectors : 7165 diag::err_invalid_conversion_between_vector_and_integer) 7166 << VectorTy << Ty << R; 7167 } else 7168 return Diag(R.getBegin(), 7169 diag::err_invalid_conversion_between_vector_and_scalar) 7170 << VectorTy << Ty << R; 7171 7172 Kind = CK_BitCast; 7173 return false; 7174 } 7175 7176 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7177 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7178 7179 if (DestElemTy == SplattedExpr->getType()) 7180 return SplattedExpr; 7181 7182 assert(DestElemTy->isFloatingType() || 7183 DestElemTy->isIntegralOrEnumerationType()); 7184 7185 CastKind CK; 7186 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7187 // OpenCL requires that we convert `true` boolean expressions to -1, but 7188 // only when splatting vectors. 7189 if (DestElemTy->isFloatingType()) { 7190 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7191 // in two steps: boolean to signed integral, then to floating. 7192 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7193 CK_BooleanToSignedIntegral); 7194 SplattedExpr = CastExprRes.get(); 7195 CK = CK_IntegralToFloating; 7196 } else { 7197 CK = CK_BooleanToSignedIntegral; 7198 } 7199 } else { 7200 ExprResult CastExprRes = SplattedExpr; 7201 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7202 if (CastExprRes.isInvalid()) 7203 return ExprError(); 7204 SplattedExpr = CastExprRes.get(); 7205 } 7206 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7207 } 7208 7209 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7210 Expr *CastExpr, CastKind &Kind) { 7211 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7212 7213 QualType SrcTy = CastExpr->getType(); 7214 7215 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7216 // an ExtVectorType. 7217 // In OpenCL, casts between vectors of different types are not allowed. 7218 // (See OpenCL 6.2). 7219 if (SrcTy->isVectorType()) { 7220 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7221 (getLangOpts().OpenCL && 7222 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7223 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7224 << DestTy << SrcTy << R; 7225 return ExprError(); 7226 } 7227 Kind = CK_BitCast; 7228 return CastExpr; 7229 } 7230 7231 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7232 // conversion will take place first from scalar to elt type, and then 7233 // splat from elt type to vector. 7234 if (SrcTy->isPointerType()) 7235 return Diag(R.getBegin(), 7236 diag::err_invalid_conversion_between_vector_and_scalar) 7237 << DestTy << SrcTy << R; 7238 7239 Kind = CK_VectorSplat; 7240 return prepareVectorSplat(DestTy, CastExpr); 7241 } 7242 7243 ExprResult 7244 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7245 Declarator &D, ParsedType &Ty, 7246 SourceLocation RParenLoc, Expr *CastExpr) { 7247 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7248 "ActOnCastExpr(): missing type or expr"); 7249 7250 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7251 if (D.isInvalidType()) 7252 return ExprError(); 7253 7254 if (getLangOpts().CPlusPlus) { 7255 // Check that there are no default arguments (C++ only). 7256 CheckExtraCXXDefaultArguments(D); 7257 } else { 7258 // Make sure any TypoExprs have been dealt with. 7259 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7260 if (!Res.isUsable()) 7261 return ExprError(); 7262 CastExpr = Res.get(); 7263 } 7264 7265 checkUnusedDeclAttributes(D); 7266 7267 QualType castType = castTInfo->getType(); 7268 Ty = CreateParsedType(castType, castTInfo); 7269 7270 bool isVectorLiteral = false; 7271 7272 // Check for an altivec or OpenCL literal, 7273 // i.e. all the elements are integer constants. 7274 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7275 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7276 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7277 && castType->isVectorType() && (PE || PLE)) { 7278 if (PLE && PLE->getNumExprs() == 0) { 7279 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7280 return ExprError(); 7281 } 7282 if (PE || PLE->getNumExprs() == 1) { 7283 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7284 if (!E->getType()->isVectorType()) 7285 isVectorLiteral = true; 7286 } 7287 else 7288 isVectorLiteral = true; 7289 } 7290 7291 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7292 // then handle it as such. 7293 if (isVectorLiteral) 7294 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7295 7296 // If the Expr being casted is a ParenListExpr, handle it specially. 7297 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7298 // sequence of BinOp comma operators. 7299 if (isa<ParenListExpr>(CastExpr)) { 7300 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7301 if (Result.isInvalid()) return ExprError(); 7302 CastExpr = Result.get(); 7303 } 7304 7305 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7306 !getSourceManager().isInSystemMacro(LParenLoc)) 7307 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7308 7309 CheckTollFreeBridgeCast(castType, CastExpr); 7310 7311 CheckObjCBridgeRelatedCast(castType, CastExpr); 7312 7313 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7314 7315 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7316 } 7317 7318 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7319 SourceLocation RParenLoc, Expr *E, 7320 TypeSourceInfo *TInfo) { 7321 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7322 "Expected paren or paren list expression"); 7323 7324 Expr **exprs; 7325 unsigned numExprs; 7326 Expr *subExpr; 7327 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7328 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7329 LiteralLParenLoc = PE->getLParenLoc(); 7330 LiteralRParenLoc = PE->getRParenLoc(); 7331 exprs = PE->getExprs(); 7332 numExprs = PE->getNumExprs(); 7333 } else { // isa<ParenExpr> by assertion at function entrance 7334 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7335 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7336 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7337 exprs = &subExpr; 7338 numExprs = 1; 7339 } 7340 7341 QualType Ty = TInfo->getType(); 7342 assert(Ty->isVectorType() && "Expected vector type"); 7343 7344 SmallVector<Expr *, 8> initExprs; 7345 const VectorType *VTy = Ty->castAs<VectorType>(); 7346 unsigned numElems = VTy->getNumElements(); 7347 7348 // '(...)' form of vector initialization in AltiVec: the number of 7349 // initializers must be one or must match the size of the vector. 7350 // If a single value is specified in the initializer then it will be 7351 // replicated to all the components of the vector 7352 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7353 // The number of initializers must be one or must match the size of the 7354 // vector. If a single value is specified in the initializer then it will 7355 // be replicated to all the components of the vector 7356 if (numExprs == 1) { 7357 QualType ElemTy = VTy->getElementType(); 7358 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7359 if (Literal.isInvalid()) 7360 return ExprError(); 7361 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7362 PrepareScalarCast(Literal, ElemTy)); 7363 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7364 } 7365 else if (numExprs < numElems) { 7366 Diag(E->getExprLoc(), 7367 diag::err_incorrect_number_of_vector_initializers); 7368 return ExprError(); 7369 } 7370 else 7371 initExprs.append(exprs, exprs + numExprs); 7372 } 7373 else { 7374 // For OpenCL, when the number of initializers is a single value, 7375 // it will be replicated to all components of the vector. 7376 if (getLangOpts().OpenCL && 7377 VTy->getVectorKind() == VectorType::GenericVector && 7378 numExprs == 1) { 7379 QualType ElemTy = VTy->getElementType(); 7380 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7381 if (Literal.isInvalid()) 7382 return ExprError(); 7383 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7384 PrepareScalarCast(Literal, ElemTy)); 7385 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7386 } 7387 7388 initExprs.append(exprs, exprs + numExprs); 7389 } 7390 // FIXME: This means that pretty-printing the final AST will produce curly 7391 // braces instead of the original commas. 7392 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7393 initExprs, LiteralRParenLoc); 7394 initE->setType(Ty); 7395 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7396 } 7397 7398 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7399 /// the ParenListExpr into a sequence of comma binary operators. 7400 ExprResult 7401 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7402 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7403 if (!E) 7404 return OrigExpr; 7405 7406 ExprResult Result(E->getExpr(0)); 7407 7408 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7409 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7410 E->getExpr(i)); 7411 7412 if (Result.isInvalid()) return ExprError(); 7413 7414 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7415 } 7416 7417 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7418 SourceLocation R, 7419 MultiExprArg Val) { 7420 return ParenListExpr::Create(Context, L, Val, R); 7421 } 7422 7423 /// Emit a specialized diagnostic when one expression is a null pointer 7424 /// constant and the other is not a pointer. Returns true if a diagnostic is 7425 /// emitted. 7426 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7427 SourceLocation QuestionLoc) { 7428 Expr *NullExpr = LHSExpr; 7429 Expr *NonPointerExpr = RHSExpr; 7430 Expr::NullPointerConstantKind NullKind = 7431 NullExpr->isNullPointerConstant(Context, 7432 Expr::NPC_ValueDependentIsNotNull); 7433 7434 if (NullKind == Expr::NPCK_NotNull) { 7435 NullExpr = RHSExpr; 7436 NonPointerExpr = LHSExpr; 7437 NullKind = 7438 NullExpr->isNullPointerConstant(Context, 7439 Expr::NPC_ValueDependentIsNotNull); 7440 } 7441 7442 if (NullKind == Expr::NPCK_NotNull) 7443 return false; 7444 7445 if (NullKind == Expr::NPCK_ZeroExpression) 7446 return false; 7447 7448 if (NullKind == Expr::NPCK_ZeroLiteral) { 7449 // In this case, check to make sure that we got here from a "NULL" 7450 // string in the source code. 7451 NullExpr = NullExpr->IgnoreParenImpCasts(); 7452 SourceLocation loc = NullExpr->getExprLoc(); 7453 if (!findMacroSpelling(loc, "NULL")) 7454 return false; 7455 } 7456 7457 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7458 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7459 << NonPointerExpr->getType() << DiagType 7460 << NonPointerExpr->getSourceRange(); 7461 return true; 7462 } 7463 7464 /// Return false if the condition expression is valid, true otherwise. 7465 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7466 QualType CondTy = Cond->getType(); 7467 7468 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7469 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7470 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7471 << CondTy << Cond->getSourceRange(); 7472 return true; 7473 } 7474 7475 // C99 6.5.15p2 7476 if (CondTy->isScalarType()) return false; 7477 7478 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7479 << CondTy << Cond->getSourceRange(); 7480 return true; 7481 } 7482 7483 /// Handle when one or both operands are void type. 7484 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7485 ExprResult &RHS) { 7486 Expr *LHSExpr = LHS.get(); 7487 Expr *RHSExpr = RHS.get(); 7488 7489 if (!LHSExpr->getType()->isVoidType()) 7490 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7491 << RHSExpr->getSourceRange(); 7492 if (!RHSExpr->getType()->isVoidType()) 7493 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7494 << LHSExpr->getSourceRange(); 7495 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7496 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7497 return S.Context.VoidTy; 7498 } 7499 7500 /// Return false if the NullExpr can be promoted to PointerTy, 7501 /// true otherwise. 7502 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7503 QualType PointerTy) { 7504 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7505 !NullExpr.get()->isNullPointerConstant(S.Context, 7506 Expr::NPC_ValueDependentIsNull)) 7507 return true; 7508 7509 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7510 return false; 7511 } 7512 7513 /// Checks compatibility between two pointers and return the resulting 7514 /// type. 7515 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7516 ExprResult &RHS, 7517 SourceLocation Loc) { 7518 QualType LHSTy = LHS.get()->getType(); 7519 QualType RHSTy = RHS.get()->getType(); 7520 7521 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7522 // Two identical pointers types are always compatible. 7523 return LHSTy; 7524 } 7525 7526 QualType lhptee, rhptee; 7527 7528 // Get the pointee types. 7529 bool IsBlockPointer = false; 7530 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7531 lhptee = LHSBTy->getPointeeType(); 7532 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7533 IsBlockPointer = true; 7534 } else { 7535 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7536 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7537 } 7538 7539 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7540 // differently qualified versions of compatible types, the result type is 7541 // a pointer to an appropriately qualified version of the composite 7542 // type. 7543 7544 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7545 // clause doesn't make sense for our extensions. E.g. address space 2 should 7546 // be incompatible with address space 3: they may live on different devices or 7547 // anything. 7548 Qualifiers lhQual = lhptee.getQualifiers(); 7549 Qualifiers rhQual = rhptee.getQualifiers(); 7550 7551 LangAS ResultAddrSpace = LangAS::Default; 7552 LangAS LAddrSpace = lhQual.getAddressSpace(); 7553 LangAS RAddrSpace = rhQual.getAddressSpace(); 7554 7555 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7556 // spaces is disallowed. 7557 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7558 ResultAddrSpace = LAddrSpace; 7559 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7560 ResultAddrSpace = RAddrSpace; 7561 else { 7562 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7563 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7564 << RHS.get()->getSourceRange(); 7565 return QualType(); 7566 } 7567 7568 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7569 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7570 lhQual.removeCVRQualifiers(); 7571 rhQual.removeCVRQualifiers(); 7572 7573 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7574 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7575 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7576 // qual types are compatible iff 7577 // * corresponded types are compatible 7578 // * CVR qualifiers are equal 7579 // * address spaces are equal 7580 // Thus for conditional operator we merge CVR and address space unqualified 7581 // pointees and if there is a composite type we return a pointer to it with 7582 // merged qualifiers. 7583 LHSCastKind = 7584 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7585 RHSCastKind = 7586 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7587 lhQual.removeAddressSpace(); 7588 rhQual.removeAddressSpace(); 7589 7590 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7591 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7592 7593 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7594 7595 if (CompositeTy.isNull()) { 7596 // In this situation, we assume void* type. No especially good 7597 // reason, but this is what gcc does, and we do have to pick 7598 // to get a consistent AST. 7599 QualType incompatTy; 7600 incompatTy = S.Context.getPointerType( 7601 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7602 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7603 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7604 7605 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7606 // for casts between types with incompatible address space qualifiers. 7607 // For the following code the compiler produces casts between global and 7608 // local address spaces of the corresponded innermost pointees: 7609 // local int *global *a; 7610 // global int *global *b; 7611 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7612 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7613 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7614 << RHS.get()->getSourceRange(); 7615 7616 return incompatTy; 7617 } 7618 7619 // The pointer types are compatible. 7620 // In case of OpenCL ResultTy should have the address space qualifier 7621 // which is a superset of address spaces of both the 2nd and the 3rd 7622 // operands of the conditional operator. 7623 QualType ResultTy = [&, ResultAddrSpace]() { 7624 if (S.getLangOpts().OpenCL) { 7625 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7626 CompositeQuals.setAddressSpace(ResultAddrSpace); 7627 return S.Context 7628 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7629 .withCVRQualifiers(MergedCVRQual); 7630 } 7631 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7632 }(); 7633 if (IsBlockPointer) 7634 ResultTy = S.Context.getBlockPointerType(ResultTy); 7635 else 7636 ResultTy = S.Context.getPointerType(ResultTy); 7637 7638 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7639 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7640 return ResultTy; 7641 } 7642 7643 /// Return the resulting type when the operands are both block pointers. 7644 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7645 ExprResult &LHS, 7646 ExprResult &RHS, 7647 SourceLocation Loc) { 7648 QualType LHSTy = LHS.get()->getType(); 7649 QualType RHSTy = RHS.get()->getType(); 7650 7651 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7652 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7653 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7654 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7655 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7656 return destType; 7657 } 7658 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7659 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7660 << RHS.get()->getSourceRange(); 7661 return QualType(); 7662 } 7663 7664 // We have 2 block pointer types. 7665 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7666 } 7667 7668 /// Return the resulting type when the operands are both pointers. 7669 static QualType 7670 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7671 ExprResult &RHS, 7672 SourceLocation Loc) { 7673 // get the pointer types 7674 QualType LHSTy = LHS.get()->getType(); 7675 QualType RHSTy = RHS.get()->getType(); 7676 7677 // get the "pointed to" types 7678 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7679 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7680 7681 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7682 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7683 // Figure out necessary qualifiers (C99 6.5.15p6) 7684 QualType destPointee 7685 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7686 QualType destType = S.Context.getPointerType(destPointee); 7687 // Add qualifiers if necessary. 7688 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7689 // Promote to void*. 7690 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7691 return destType; 7692 } 7693 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7694 QualType destPointee 7695 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7696 QualType destType = S.Context.getPointerType(destPointee); 7697 // Add qualifiers if necessary. 7698 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7699 // Promote to void*. 7700 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7701 return destType; 7702 } 7703 7704 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7705 } 7706 7707 /// Return false if the first expression is not an integer and the second 7708 /// expression is not a pointer, true otherwise. 7709 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7710 Expr* PointerExpr, SourceLocation Loc, 7711 bool IsIntFirstExpr) { 7712 if (!PointerExpr->getType()->isPointerType() || 7713 !Int.get()->getType()->isIntegerType()) 7714 return false; 7715 7716 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7717 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7718 7719 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7720 << Expr1->getType() << Expr2->getType() 7721 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7722 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7723 CK_IntegralToPointer); 7724 return true; 7725 } 7726 7727 /// Simple conversion between integer and floating point types. 7728 /// 7729 /// Used when handling the OpenCL conditional operator where the 7730 /// condition is a vector while the other operands are scalar. 7731 /// 7732 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7733 /// types are either integer or floating type. Between the two 7734 /// operands, the type with the higher rank is defined as the "result 7735 /// type". The other operand needs to be promoted to the same type. No 7736 /// other type promotion is allowed. We cannot use 7737 /// UsualArithmeticConversions() for this purpose, since it always 7738 /// promotes promotable types. 7739 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7740 ExprResult &RHS, 7741 SourceLocation QuestionLoc) { 7742 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7743 if (LHS.isInvalid()) 7744 return QualType(); 7745 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7746 if (RHS.isInvalid()) 7747 return QualType(); 7748 7749 // For conversion purposes, we ignore any qualifiers. 7750 // For example, "const float" and "float" are equivalent. 7751 QualType LHSType = 7752 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7753 QualType RHSType = 7754 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7755 7756 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7757 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7758 << LHSType << LHS.get()->getSourceRange(); 7759 return QualType(); 7760 } 7761 7762 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7763 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7764 << RHSType << RHS.get()->getSourceRange(); 7765 return QualType(); 7766 } 7767 7768 // If both types are identical, no conversion is needed. 7769 if (LHSType == RHSType) 7770 return LHSType; 7771 7772 // Now handle "real" floating types (i.e. float, double, long double). 7773 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7774 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7775 /*IsCompAssign = */ false); 7776 7777 // Finally, we have two differing integer types. 7778 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7779 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7780 } 7781 7782 /// Convert scalar operands to a vector that matches the 7783 /// condition in length. 7784 /// 7785 /// Used when handling the OpenCL conditional operator where the 7786 /// condition is a vector while the other operands are scalar. 7787 /// 7788 /// We first compute the "result type" for the scalar operands 7789 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7790 /// into a vector of that type where the length matches the condition 7791 /// vector type. s6.11.6 requires that the element types of the result 7792 /// and the condition must have the same number of bits. 7793 static QualType 7794 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7795 QualType CondTy, SourceLocation QuestionLoc) { 7796 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7797 if (ResTy.isNull()) return QualType(); 7798 7799 const VectorType *CV = CondTy->getAs<VectorType>(); 7800 assert(CV); 7801 7802 // Determine the vector result type 7803 unsigned NumElements = CV->getNumElements(); 7804 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7805 7806 // Ensure that all types have the same number of bits 7807 if (S.Context.getTypeSize(CV->getElementType()) 7808 != S.Context.getTypeSize(ResTy)) { 7809 // Since VectorTy is created internally, it does not pretty print 7810 // with an OpenCL name. Instead, we just print a description. 7811 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7812 SmallString<64> Str; 7813 llvm::raw_svector_ostream OS(Str); 7814 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7815 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7816 << CondTy << OS.str(); 7817 return QualType(); 7818 } 7819 7820 // Convert operands to the vector result type 7821 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7822 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7823 7824 return VectorTy; 7825 } 7826 7827 /// Return false if this is a valid OpenCL condition vector 7828 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7829 SourceLocation QuestionLoc) { 7830 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7831 // integral type. 7832 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7833 assert(CondTy); 7834 QualType EleTy = CondTy->getElementType(); 7835 if (EleTy->isIntegerType()) return false; 7836 7837 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7838 << Cond->getType() << Cond->getSourceRange(); 7839 return true; 7840 } 7841 7842 /// Return false if the vector condition type and the vector 7843 /// result type are compatible. 7844 /// 7845 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7846 /// number of elements, and their element types have the same number 7847 /// of bits. 7848 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7849 SourceLocation QuestionLoc) { 7850 const VectorType *CV = CondTy->getAs<VectorType>(); 7851 const VectorType *RV = VecResTy->getAs<VectorType>(); 7852 assert(CV && RV); 7853 7854 if (CV->getNumElements() != RV->getNumElements()) { 7855 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7856 << CondTy << VecResTy; 7857 return true; 7858 } 7859 7860 QualType CVE = CV->getElementType(); 7861 QualType RVE = RV->getElementType(); 7862 7863 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7864 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7865 << CondTy << VecResTy; 7866 return true; 7867 } 7868 7869 return false; 7870 } 7871 7872 /// Return the resulting type for the conditional operator in 7873 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7874 /// s6.3.i) when the condition is a vector type. 7875 static QualType 7876 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7877 ExprResult &LHS, ExprResult &RHS, 7878 SourceLocation QuestionLoc) { 7879 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 7880 if (Cond.isInvalid()) 7881 return QualType(); 7882 QualType CondTy = Cond.get()->getType(); 7883 7884 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 7885 return QualType(); 7886 7887 // If either operand is a vector then find the vector type of the 7888 // result as specified in OpenCL v1.1 s6.3.i. 7889 if (LHS.get()->getType()->isVectorType() || 7890 RHS.get()->getType()->isVectorType()) { 7891 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 7892 /*isCompAssign*/false, 7893 /*AllowBothBool*/true, 7894 /*AllowBoolConversions*/false); 7895 if (VecResTy.isNull()) return QualType(); 7896 // The result type must match the condition type as specified in 7897 // OpenCL v1.1 s6.11.6. 7898 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 7899 return QualType(); 7900 return VecResTy; 7901 } 7902 7903 // Both operands are scalar. 7904 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 7905 } 7906 7907 /// Return true if the Expr is block type 7908 static bool checkBlockType(Sema &S, const Expr *E) { 7909 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7910 QualType Ty = CE->getCallee()->getType(); 7911 if (Ty->isBlockPointerType()) { 7912 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 7913 return true; 7914 } 7915 } 7916 return false; 7917 } 7918 7919 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 7920 /// In that case, LHS = cond. 7921 /// C99 6.5.15 7922 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 7923 ExprResult &RHS, ExprValueKind &VK, 7924 ExprObjectKind &OK, 7925 SourceLocation QuestionLoc) { 7926 7927 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 7928 if (!LHSResult.isUsable()) return QualType(); 7929 LHS = LHSResult; 7930 7931 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 7932 if (!RHSResult.isUsable()) return QualType(); 7933 RHS = RHSResult; 7934 7935 // C++ is sufficiently different to merit its own checker. 7936 if (getLangOpts().CPlusPlus) 7937 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 7938 7939 VK = VK_RValue; 7940 OK = OK_Ordinary; 7941 7942 // The OpenCL operator with a vector condition is sufficiently 7943 // different to merit its own checker. 7944 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 7945 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 7946 7947 // First, check the condition. 7948 Cond = UsualUnaryConversions(Cond.get()); 7949 if (Cond.isInvalid()) 7950 return QualType(); 7951 if (checkCondition(*this, Cond.get(), QuestionLoc)) 7952 return QualType(); 7953 7954 // Now check the two expressions. 7955 if (LHS.get()->getType()->isVectorType() || 7956 RHS.get()->getType()->isVectorType()) 7957 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 7958 /*AllowBothBool*/true, 7959 /*AllowBoolConversions*/false); 7960 7961 QualType ResTy = 7962 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 7963 if (LHS.isInvalid() || RHS.isInvalid()) 7964 return QualType(); 7965 7966 QualType LHSTy = LHS.get()->getType(); 7967 QualType RHSTy = RHS.get()->getType(); 7968 7969 // Diagnose attempts to convert between __float128 and long double where 7970 // such conversions currently can't be handled. 7971 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 7972 Diag(QuestionLoc, 7973 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 7974 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7975 return QualType(); 7976 } 7977 7978 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 7979 // selection operator (?:). 7980 if (getLangOpts().OpenCL && 7981 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 7982 return QualType(); 7983 } 7984 7985 // If both operands have arithmetic type, do the usual arithmetic conversions 7986 // to find a common type: C99 6.5.15p3,5. 7987 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 7988 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7989 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7990 7991 return ResTy; 7992 } 7993 7994 // If both operands are the same structure or union type, the result is that 7995 // type. 7996 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 7997 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 7998 if (LHSRT->getDecl() == RHSRT->getDecl()) 7999 // "If both the operands have structure or union type, the result has 8000 // that type." This implies that CV qualifiers are dropped. 8001 return LHSTy.getUnqualifiedType(); 8002 // FIXME: Type of conditional expression must be complete in C mode. 8003 } 8004 8005 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8006 // The following || allows only one side to be void (a GCC-ism). 8007 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8008 return checkConditionalVoidType(*this, LHS, RHS); 8009 } 8010 8011 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8012 // the type of the other operand." 8013 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8014 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8015 8016 // All objective-c pointer type analysis is done here. 8017 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8018 QuestionLoc); 8019 if (LHS.isInvalid() || RHS.isInvalid()) 8020 return QualType(); 8021 if (!compositeType.isNull()) 8022 return compositeType; 8023 8024 8025 // Handle block pointer types. 8026 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8027 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8028 QuestionLoc); 8029 8030 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8031 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8032 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8033 QuestionLoc); 8034 8035 // GCC compatibility: soften pointer/integer mismatch. Note that 8036 // null pointers have been filtered out by this point. 8037 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8038 /*IsIntFirstExpr=*/true)) 8039 return RHSTy; 8040 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8041 /*IsIntFirstExpr=*/false)) 8042 return LHSTy; 8043 8044 // Allow ?: operations in which both operands have the same 8045 // built-in sizeless type. 8046 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) 8047 return LHSTy; 8048 8049 // Emit a better diagnostic if one of the expressions is a null pointer 8050 // constant and the other is not a pointer type. In this case, the user most 8051 // likely forgot to take the address of the other expression. 8052 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8053 return QualType(); 8054 8055 // Otherwise, the operands are not compatible. 8056 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8057 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8058 << RHS.get()->getSourceRange(); 8059 return QualType(); 8060 } 8061 8062 /// FindCompositeObjCPointerType - Helper method to find composite type of 8063 /// two objective-c pointer types of the two input expressions. 8064 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8065 SourceLocation QuestionLoc) { 8066 QualType LHSTy = LHS.get()->getType(); 8067 QualType RHSTy = RHS.get()->getType(); 8068 8069 // Handle things like Class and struct objc_class*. Here we case the result 8070 // to the pseudo-builtin, because that will be implicitly cast back to the 8071 // redefinition type if an attempt is made to access its fields. 8072 if (LHSTy->isObjCClassType() && 8073 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8074 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8075 return LHSTy; 8076 } 8077 if (RHSTy->isObjCClassType() && 8078 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8079 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8080 return RHSTy; 8081 } 8082 // And the same for struct objc_object* / id 8083 if (LHSTy->isObjCIdType() && 8084 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8085 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8086 return LHSTy; 8087 } 8088 if (RHSTy->isObjCIdType() && 8089 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8090 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8091 return RHSTy; 8092 } 8093 // And the same for struct objc_selector* / SEL 8094 if (Context.isObjCSelType(LHSTy) && 8095 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8096 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8097 return LHSTy; 8098 } 8099 if (Context.isObjCSelType(RHSTy) && 8100 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8101 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8102 return RHSTy; 8103 } 8104 // Check constraints for Objective-C object pointers types. 8105 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8106 8107 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8108 // Two identical object pointer types are always compatible. 8109 return LHSTy; 8110 } 8111 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8112 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8113 QualType compositeType = LHSTy; 8114 8115 // If both operands are interfaces and either operand can be 8116 // assigned to the other, use that type as the composite 8117 // type. This allows 8118 // xxx ? (A*) a : (B*) b 8119 // where B is a subclass of A. 8120 // 8121 // Additionally, as for assignment, if either type is 'id' 8122 // allow silent coercion. Finally, if the types are 8123 // incompatible then make sure to use 'id' as the composite 8124 // type so the result is acceptable for sending messages to. 8125 8126 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8127 // It could return the composite type. 8128 if (!(compositeType = 8129 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8130 // Nothing more to do. 8131 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8132 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8133 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8134 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8135 } else if ((LHSOPT->isObjCQualifiedIdType() || 8136 RHSOPT->isObjCQualifiedIdType()) && 8137 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8138 true)) { 8139 // Need to handle "id<xx>" explicitly. 8140 // GCC allows qualified id and any Objective-C type to devolve to 8141 // id. Currently localizing to here until clear this should be 8142 // part of ObjCQualifiedIdTypesAreCompatible. 8143 compositeType = Context.getObjCIdType(); 8144 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8145 compositeType = Context.getObjCIdType(); 8146 } else { 8147 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8148 << LHSTy << RHSTy 8149 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8150 QualType incompatTy = Context.getObjCIdType(); 8151 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8152 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8153 return incompatTy; 8154 } 8155 // The object pointer types are compatible. 8156 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8157 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8158 return compositeType; 8159 } 8160 // Check Objective-C object pointer types and 'void *' 8161 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8162 if (getLangOpts().ObjCAutoRefCount) { 8163 // ARC forbids the implicit conversion of object pointers to 'void *', 8164 // so these types are not compatible. 8165 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8166 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8167 LHS = RHS = true; 8168 return QualType(); 8169 } 8170 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8171 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8172 QualType destPointee 8173 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8174 QualType destType = Context.getPointerType(destPointee); 8175 // Add qualifiers if necessary. 8176 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8177 // Promote to void*. 8178 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8179 return destType; 8180 } 8181 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8182 if (getLangOpts().ObjCAutoRefCount) { 8183 // ARC forbids the implicit conversion of object pointers to 'void *', 8184 // so these types are not compatible. 8185 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8186 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8187 LHS = RHS = true; 8188 return QualType(); 8189 } 8190 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8191 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8192 QualType destPointee 8193 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8194 QualType destType = Context.getPointerType(destPointee); 8195 // Add qualifiers if necessary. 8196 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8197 // Promote to void*. 8198 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8199 return destType; 8200 } 8201 return QualType(); 8202 } 8203 8204 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8205 /// ParenRange in parentheses. 8206 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8207 const PartialDiagnostic &Note, 8208 SourceRange ParenRange) { 8209 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8210 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8211 EndLoc.isValid()) { 8212 Self.Diag(Loc, Note) 8213 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8214 << FixItHint::CreateInsertion(EndLoc, ")"); 8215 } else { 8216 // We can't display the parentheses, so just show the bare note. 8217 Self.Diag(Loc, Note) << ParenRange; 8218 } 8219 } 8220 8221 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8222 return BinaryOperator::isAdditiveOp(Opc) || 8223 BinaryOperator::isMultiplicativeOp(Opc) || 8224 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8225 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8226 // not any of the logical operators. Bitwise-xor is commonly used as a 8227 // logical-xor because there is no logical-xor operator. The logical 8228 // operators, including uses of xor, have a high false positive rate for 8229 // precedence warnings. 8230 } 8231 8232 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8233 /// expression, either using a built-in or overloaded operator, 8234 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8235 /// expression. 8236 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8237 Expr **RHSExprs) { 8238 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8239 E = E->IgnoreImpCasts(); 8240 E = E->IgnoreConversionOperator(); 8241 E = E->IgnoreImpCasts(); 8242 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8243 E = MTE->getSubExpr(); 8244 E = E->IgnoreImpCasts(); 8245 } 8246 8247 // Built-in binary operator. 8248 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8249 if (IsArithmeticOp(OP->getOpcode())) { 8250 *Opcode = OP->getOpcode(); 8251 *RHSExprs = OP->getRHS(); 8252 return true; 8253 } 8254 } 8255 8256 // Overloaded operator. 8257 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8258 if (Call->getNumArgs() != 2) 8259 return false; 8260 8261 // Make sure this is really a binary operator that is safe to pass into 8262 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8263 OverloadedOperatorKind OO = Call->getOperator(); 8264 if (OO < OO_Plus || OO > OO_Arrow || 8265 OO == OO_PlusPlus || OO == OO_MinusMinus) 8266 return false; 8267 8268 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8269 if (IsArithmeticOp(OpKind)) { 8270 *Opcode = OpKind; 8271 *RHSExprs = Call->getArg(1); 8272 return true; 8273 } 8274 } 8275 8276 return false; 8277 } 8278 8279 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8280 /// or is a logical expression such as (x==y) which has int type, but is 8281 /// commonly interpreted as boolean. 8282 static bool ExprLooksBoolean(Expr *E) { 8283 E = E->IgnoreParenImpCasts(); 8284 8285 if (E->getType()->isBooleanType()) 8286 return true; 8287 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8288 return OP->isComparisonOp() || OP->isLogicalOp(); 8289 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8290 return OP->getOpcode() == UO_LNot; 8291 if (E->getType()->isPointerType()) 8292 return true; 8293 // FIXME: What about overloaded operator calls returning "unspecified boolean 8294 // type"s (commonly pointer-to-members)? 8295 8296 return false; 8297 } 8298 8299 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8300 /// and binary operator are mixed in a way that suggests the programmer assumed 8301 /// the conditional operator has higher precedence, for example: 8302 /// "int x = a + someBinaryCondition ? 1 : 2". 8303 static void DiagnoseConditionalPrecedence(Sema &Self, 8304 SourceLocation OpLoc, 8305 Expr *Condition, 8306 Expr *LHSExpr, 8307 Expr *RHSExpr) { 8308 BinaryOperatorKind CondOpcode; 8309 Expr *CondRHS; 8310 8311 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8312 return; 8313 if (!ExprLooksBoolean(CondRHS)) 8314 return; 8315 8316 // The condition is an arithmetic binary expression, with a right- 8317 // hand side that looks boolean, so warn. 8318 8319 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8320 ? diag::warn_precedence_bitwise_conditional 8321 : diag::warn_precedence_conditional; 8322 8323 Self.Diag(OpLoc, DiagID) 8324 << Condition->getSourceRange() 8325 << BinaryOperator::getOpcodeStr(CondOpcode); 8326 8327 SuggestParentheses( 8328 Self, OpLoc, 8329 Self.PDiag(diag::note_precedence_silence) 8330 << BinaryOperator::getOpcodeStr(CondOpcode), 8331 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8332 8333 SuggestParentheses(Self, OpLoc, 8334 Self.PDiag(diag::note_precedence_conditional_first), 8335 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8336 } 8337 8338 /// Compute the nullability of a conditional expression. 8339 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8340 QualType LHSTy, QualType RHSTy, 8341 ASTContext &Ctx) { 8342 if (!ResTy->isAnyPointerType()) 8343 return ResTy; 8344 8345 auto GetNullability = [&Ctx](QualType Ty) { 8346 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8347 if (Kind) 8348 return *Kind; 8349 return NullabilityKind::Unspecified; 8350 }; 8351 8352 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8353 NullabilityKind MergedKind; 8354 8355 // Compute nullability of a binary conditional expression. 8356 if (IsBin) { 8357 if (LHSKind == NullabilityKind::NonNull) 8358 MergedKind = NullabilityKind::NonNull; 8359 else 8360 MergedKind = RHSKind; 8361 // Compute nullability of a normal conditional expression. 8362 } else { 8363 if (LHSKind == NullabilityKind::Nullable || 8364 RHSKind == NullabilityKind::Nullable) 8365 MergedKind = NullabilityKind::Nullable; 8366 else if (LHSKind == NullabilityKind::NonNull) 8367 MergedKind = RHSKind; 8368 else if (RHSKind == NullabilityKind::NonNull) 8369 MergedKind = LHSKind; 8370 else 8371 MergedKind = NullabilityKind::Unspecified; 8372 } 8373 8374 // Return if ResTy already has the correct nullability. 8375 if (GetNullability(ResTy) == MergedKind) 8376 return ResTy; 8377 8378 // Strip all nullability from ResTy. 8379 while (ResTy->getNullability(Ctx)) 8380 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8381 8382 // Create a new AttributedType with the new nullability kind. 8383 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8384 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8385 } 8386 8387 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8388 /// in the case of a the GNU conditional expr extension. 8389 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8390 SourceLocation ColonLoc, 8391 Expr *CondExpr, Expr *LHSExpr, 8392 Expr *RHSExpr) { 8393 if (!getLangOpts().CPlusPlus) { 8394 // C cannot handle TypoExpr nodes in the condition because it 8395 // doesn't handle dependent types properly, so make sure any TypoExprs have 8396 // been dealt with before checking the operands. 8397 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8398 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8399 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8400 8401 if (!CondResult.isUsable()) 8402 return ExprError(); 8403 8404 if (LHSExpr) { 8405 if (!LHSResult.isUsable()) 8406 return ExprError(); 8407 } 8408 8409 if (!RHSResult.isUsable()) 8410 return ExprError(); 8411 8412 CondExpr = CondResult.get(); 8413 LHSExpr = LHSResult.get(); 8414 RHSExpr = RHSResult.get(); 8415 } 8416 8417 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8418 // was the condition. 8419 OpaqueValueExpr *opaqueValue = nullptr; 8420 Expr *commonExpr = nullptr; 8421 if (!LHSExpr) { 8422 commonExpr = CondExpr; 8423 // Lower out placeholder types first. This is important so that we don't 8424 // try to capture a placeholder. This happens in few cases in C++; such 8425 // as Objective-C++'s dictionary subscripting syntax. 8426 if (commonExpr->hasPlaceholderType()) { 8427 ExprResult result = CheckPlaceholderExpr(commonExpr); 8428 if (!result.isUsable()) return ExprError(); 8429 commonExpr = result.get(); 8430 } 8431 // We usually want to apply unary conversions *before* saving, except 8432 // in the special case of a C++ l-value conditional. 8433 if (!(getLangOpts().CPlusPlus 8434 && !commonExpr->isTypeDependent() 8435 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8436 && commonExpr->isGLValue() 8437 && commonExpr->isOrdinaryOrBitFieldObject() 8438 && RHSExpr->isOrdinaryOrBitFieldObject() 8439 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8440 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8441 if (commonRes.isInvalid()) 8442 return ExprError(); 8443 commonExpr = commonRes.get(); 8444 } 8445 8446 // If the common expression is a class or array prvalue, materialize it 8447 // so that we can safely refer to it multiple times. 8448 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 8449 commonExpr->getType()->isArrayType())) { 8450 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8451 if (MatExpr.isInvalid()) 8452 return ExprError(); 8453 commonExpr = MatExpr.get(); 8454 } 8455 8456 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8457 commonExpr->getType(), 8458 commonExpr->getValueKind(), 8459 commonExpr->getObjectKind(), 8460 commonExpr); 8461 LHSExpr = CondExpr = opaqueValue; 8462 } 8463 8464 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8465 ExprValueKind VK = VK_RValue; 8466 ExprObjectKind OK = OK_Ordinary; 8467 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8468 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8469 VK, OK, QuestionLoc); 8470 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8471 RHS.isInvalid()) 8472 return ExprError(); 8473 8474 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8475 RHS.get()); 8476 8477 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8478 8479 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8480 Context); 8481 8482 if (!commonExpr) 8483 return new (Context) 8484 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8485 RHS.get(), result, VK, OK); 8486 8487 return new (Context) BinaryConditionalOperator( 8488 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8489 ColonLoc, result, VK, OK); 8490 } 8491 8492 // Check if we have a conversion between incompatible cmse function pointer 8493 // types, that is, a conversion between a function pointer with the 8494 // cmse_nonsecure_call attribute and one without. 8495 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8496 QualType ToType) { 8497 if (const auto *ToFn = 8498 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8499 if (const auto *FromFn = 8500 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8501 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8502 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8503 8504 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8505 } 8506 } 8507 return false; 8508 } 8509 8510 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8511 // being closely modeled after the C99 spec:-). The odd characteristic of this 8512 // routine is it effectively iqnores the qualifiers on the top level pointee. 8513 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8514 // FIXME: add a couple examples in this comment. 8515 static Sema::AssignConvertType 8516 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8517 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8518 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8519 8520 // get the "pointed to" type (ignoring qualifiers at the top level) 8521 const Type *lhptee, *rhptee; 8522 Qualifiers lhq, rhq; 8523 std::tie(lhptee, lhq) = 8524 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8525 std::tie(rhptee, rhq) = 8526 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8527 8528 Sema::AssignConvertType ConvTy = Sema::Compatible; 8529 8530 // C99 6.5.16.1p1: This following citation is common to constraints 8531 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8532 // qualifiers of the type *pointed to* by the right; 8533 8534 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8535 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8536 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8537 // Ignore lifetime for further calculation. 8538 lhq.removeObjCLifetime(); 8539 rhq.removeObjCLifetime(); 8540 } 8541 8542 if (!lhq.compatiblyIncludes(rhq)) { 8543 // Treat address-space mismatches as fatal. 8544 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8545 return Sema::IncompatiblePointerDiscardsQualifiers; 8546 8547 // It's okay to add or remove GC or lifetime qualifiers when converting to 8548 // and from void*. 8549 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8550 .compatiblyIncludes( 8551 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8552 && (lhptee->isVoidType() || rhptee->isVoidType())) 8553 ; // keep old 8554 8555 // Treat lifetime mismatches as fatal. 8556 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8557 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8558 8559 // For GCC/MS compatibility, other qualifier mismatches are treated 8560 // as still compatible in C. 8561 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8562 } 8563 8564 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8565 // incomplete type and the other is a pointer to a qualified or unqualified 8566 // version of void... 8567 if (lhptee->isVoidType()) { 8568 if (rhptee->isIncompleteOrObjectType()) 8569 return ConvTy; 8570 8571 // As an extension, we allow cast to/from void* to function pointer. 8572 assert(rhptee->isFunctionType()); 8573 return Sema::FunctionVoidPointer; 8574 } 8575 8576 if (rhptee->isVoidType()) { 8577 if (lhptee->isIncompleteOrObjectType()) 8578 return ConvTy; 8579 8580 // As an extension, we allow cast to/from void* to function pointer. 8581 assert(lhptee->isFunctionType()); 8582 return Sema::FunctionVoidPointer; 8583 } 8584 8585 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8586 // unqualified versions of compatible types, ... 8587 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8588 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8589 // Check if the pointee types are compatible ignoring the sign. 8590 // We explicitly check for char so that we catch "char" vs 8591 // "unsigned char" on systems where "char" is unsigned. 8592 if (lhptee->isCharType()) 8593 ltrans = S.Context.UnsignedCharTy; 8594 else if (lhptee->hasSignedIntegerRepresentation()) 8595 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8596 8597 if (rhptee->isCharType()) 8598 rtrans = S.Context.UnsignedCharTy; 8599 else if (rhptee->hasSignedIntegerRepresentation()) 8600 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8601 8602 if (ltrans == rtrans) { 8603 // Types are compatible ignoring the sign. Qualifier incompatibility 8604 // takes priority over sign incompatibility because the sign 8605 // warning can be disabled. 8606 if (ConvTy != Sema::Compatible) 8607 return ConvTy; 8608 8609 return Sema::IncompatiblePointerSign; 8610 } 8611 8612 // If we are a multi-level pointer, it's possible that our issue is simply 8613 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8614 // the eventual target type is the same and the pointers have the same 8615 // level of indirection, this must be the issue. 8616 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8617 do { 8618 std::tie(lhptee, lhq) = 8619 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8620 std::tie(rhptee, rhq) = 8621 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8622 8623 // Inconsistent address spaces at this point is invalid, even if the 8624 // address spaces would be compatible. 8625 // FIXME: This doesn't catch address space mismatches for pointers of 8626 // different nesting levels, like: 8627 // __local int *** a; 8628 // int ** b = a; 8629 // It's not clear how to actually determine when such pointers are 8630 // invalidly incompatible. 8631 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8632 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8633 8634 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8635 8636 if (lhptee == rhptee) 8637 return Sema::IncompatibleNestedPointerQualifiers; 8638 } 8639 8640 // General pointer incompatibility takes priority over qualifiers. 8641 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8642 return Sema::IncompatibleFunctionPointer; 8643 return Sema::IncompatiblePointer; 8644 } 8645 if (!S.getLangOpts().CPlusPlus && 8646 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8647 return Sema::IncompatibleFunctionPointer; 8648 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 8649 return Sema::IncompatibleFunctionPointer; 8650 return ConvTy; 8651 } 8652 8653 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8654 /// block pointer types are compatible or whether a block and normal pointer 8655 /// are compatible. It is more restrict than comparing two function pointer 8656 // types. 8657 static Sema::AssignConvertType 8658 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8659 QualType RHSType) { 8660 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8661 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8662 8663 QualType lhptee, rhptee; 8664 8665 // get the "pointed to" type (ignoring qualifiers at the top level) 8666 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8667 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8668 8669 // In C++, the types have to match exactly. 8670 if (S.getLangOpts().CPlusPlus) 8671 return Sema::IncompatibleBlockPointer; 8672 8673 Sema::AssignConvertType ConvTy = Sema::Compatible; 8674 8675 // For blocks we enforce that qualifiers are identical. 8676 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8677 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8678 if (S.getLangOpts().OpenCL) { 8679 LQuals.removeAddressSpace(); 8680 RQuals.removeAddressSpace(); 8681 } 8682 if (LQuals != RQuals) 8683 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8684 8685 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8686 // assignment. 8687 // The current behavior is similar to C++ lambdas. A block might be 8688 // assigned to a variable iff its return type and parameters are compatible 8689 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8690 // an assignment. Presumably it should behave in way that a function pointer 8691 // assignment does in C, so for each parameter and return type: 8692 // * CVR and address space of LHS should be a superset of CVR and address 8693 // space of RHS. 8694 // * unqualified types should be compatible. 8695 if (S.getLangOpts().OpenCL) { 8696 if (!S.Context.typesAreBlockPointerCompatible( 8697 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8698 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8699 return Sema::IncompatibleBlockPointer; 8700 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8701 return Sema::IncompatibleBlockPointer; 8702 8703 return ConvTy; 8704 } 8705 8706 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8707 /// for assignment compatibility. 8708 static Sema::AssignConvertType 8709 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8710 QualType RHSType) { 8711 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8712 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8713 8714 if (LHSType->isObjCBuiltinType()) { 8715 // Class is not compatible with ObjC object pointers. 8716 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8717 !RHSType->isObjCQualifiedClassType()) 8718 return Sema::IncompatiblePointer; 8719 return Sema::Compatible; 8720 } 8721 if (RHSType->isObjCBuiltinType()) { 8722 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8723 !LHSType->isObjCQualifiedClassType()) 8724 return Sema::IncompatiblePointer; 8725 return Sema::Compatible; 8726 } 8727 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8728 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8729 8730 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8731 // make an exception for id<P> 8732 !LHSType->isObjCQualifiedIdType()) 8733 return Sema::CompatiblePointerDiscardsQualifiers; 8734 8735 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8736 return Sema::Compatible; 8737 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8738 return Sema::IncompatibleObjCQualifiedId; 8739 return Sema::IncompatiblePointer; 8740 } 8741 8742 Sema::AssignConvertType 8743 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8744 QualType LHSType, QualType RHSType) { 8745 // Fake up an opaque expression. We don't actually care about what 8746 // cast operations are required, so if CheckAssignmentConstraints 8747 // adds casts to this they'll be wasted, but fortunately that doesn't 8748 // usually happen on valid code. 8749 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8750 ExprResult RHSPtr = &RHSExpr; 8751 CastKind K; 8752 8753 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8754 } 8755 8756 /// This helper function returns true if QT is a vector type that has element 8757 /// type ElementType. 8758 static bool isVector(QualType QT, QualType ElementType) { 8759 if (const VectorType *VT = QT->getAs<VectorType>()) 8760 return VT->getElementType().getCanonicalType() == ElementType; 8761 return false; 8762 } 8763 8764 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8765 /// has code to accommodate several GCC extensions when type checking 8766 /// pointers. Here are some objectionable examples that GCC considers warnings: 8767 /// 8768 /// int a, *pint; 8769 /// short *pshort; 8770 /// struct foo *pfoo; 8771 /// 8772 /// pint = pshort; // warning: assignment from incompatible pointer type 8773 /// a = pint; // warning: assignment makes integer from pointer without a cast 8774 /// pint = a; // warning: assignment makes pointer from integer without a cast 8775 /// pint = pfoo; // warning: assignment from incompatible pointer type 8776 /// 8777 /// As a result, the code for dealing with pointers is more complex than the 8778 /// C99 spec dictates. 8779 /// 8780 /// Sets 'Kind' for any result kind except Incompatible. 8781 Sema::AssignConvertType 8782 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8783 CastKind &Kind, bool ConvertRHS) { 8784 QualType RHSType = RHS.get()->getType(); 8785 QualType OrigLHSType = LHSType; 8786 8787 // Get canonical types. We're not formatting these types, just comparing 8788 // them. 8789 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8790 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8791 8792 // Common case: no conversion required. 8793 if (LHSType == RHSType) { 8794 Kind = CK_NoOp; 8795 return Compatible; 8796 } 8797 8798 // If we have an atomic type, try a non-atomic assignment, then just add an 8799 // atomic qualification step. 8800 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8801 Sema::AssignConvertType result = 8802 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8803 if (result != Compatible) 8804 return result; 8805 if (Kind != CK_NoOp && ConvertRHS) 8806 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8807 Kind = CK_NonAtomicToAtomic; 8808 return Compatible; 8809 } 8810 8811 // If the left-hand side is a reference type, then we are in a 8812 // (rare!) case where we've allowed the use of references in C, 8813 // e.g., as a parameter type in a built-in function. In this case, 8814 // just make sure that the type referenced is compatible with the 8815 // right-hand side type. The caller is responsible for adjusting 8816 // LHSType so that the resulting expression does not have reference 8817 // type. 8818 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8819 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8820 Kind = CK_LValueBitCast; 8821 return Compatible; 8822 } 8823 return Incompatible; 8824 } 8825 8826 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8827 // to the same ExtVector type. 8828 if (LHSType->isExtVectorType()) { 8829 if (RHSType->isExtVectorType()) 8830 return Incompatible; 8831 if (RHSType->isArithmeticType()) { 8832 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8833 if (ConvertRHS) 8834 RHS = prepareVectorSplat(LHSType, RHS.get()); 8835 Kind = CK_VectorSplat; 8836 return Compatible; 8837 } 8838 } 8839 8840 // Conversions to or from vector type. 8841 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8842 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8843 // Allow assignments of an AltiVec vector type to an equivalent GCC 8844 // vector type and vice versa 8845 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8846 Kind = CK_BitCast; 8847 return Compatible; 8848 } 8849 8850 // If we are allowing lax vector conversions, and LHS and RHS are both 8851 // vectors, the total size only needs to be the same. This is a bitcast; 8852 // no bits are changed but the result type is different. 8853 if (isLaxVectorConversion(RHSType, LHSType)) { 8854 Kind = CK_BitCast; 8855 return IncompatibleVectors; 8856 } 8857 } 8858 8859 // When the RHS comes from another lax conversion (e.g. binops between 8860 // scalars and vectors) the result is canonicalized as a vector. When the 8861 // LHS is also a vector, the lax is allowed by the condition above. Handle 8862 // the case where LHS is a scalar. 8863 if (LHSType->isScalarType()) { 8864 const VectorType *VecType = RHSType->getAs<VectorType>(); 8865 if (VecType && VecType->getNumElements() == 1 && 8866 isLaxVectorConversion(RHSType, LHSType)) { 8867 ExprResult *VecExpr = &RHS; 8868 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 8869 Kind = CK_BitCast; 8870 return Compatible; 8871 } 8872 } 8873 8874 return Incompatible; 8875 } 8876 8877 // Diagnose attempts to convert between __float128 and long double where 8878 // such conversions currently can't be handled. 8879 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 8880 return Incompatible; 8881 8882 // Disallow assigning a _Complex to a real type in C++ mode since it simply 8883 // discards the imaginary part. 8884 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 8885 !LHSType->getAs<ComplexType>()) 8886 return Incompatible; 8887 8888 // Arithmetic conversions. 8889 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 8890 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 8891 if (ConvertRHS) 8892 Kind = PrepareScalarCast(RHS, LHSType); 8893 return Compatible; 8894 } 8895 8896 // Conversions to normal pointers. 8897 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 8898 // U* -> T* 8899 if (isa<PointerType>(RHSType)) { 8900 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8901 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 8902 if (AddrSpaceL != AddrSpaceR) 8903 Kind = CK_AddressSpaceConversion; 8904 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 8905 Kind = CK_NoOp; 8906 else 8907 Kind = CK_BitCast; 8908 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 8909 } 8910 8911 // int -> T* 8912 if (RHSType->isIntegerType()) { 8913 Kind = CK_IntegralToPointer; // FIXME: null? 8914 return IntToPointer; 8915 } 8916 8917 // C pointers are not compatible with ObjC object pointers, 8918 // with two exceptions: 8919 if (isa<ObjCObjectPointerType>(RHSType)) { 8920 // - conversions to void* 8921 if (LHSPointer->getPointeeType()->isVoidType()) { 8922 Kind = CK_BitCast; 8923 return Compatible; 8924 } 8925 8926 // - conversions from 'Class' to the redefinition type 8927 if (RHSType->isObjCClassType() && 8928 Context.hasSameType(LHSType, 8929 Context.getObjCClassRedefinitionType())) { 8930 Kind = CK_BitCast; 8931 return Compatible; 8932 } 8933 8934 Kind = CK_BitCast; 8935 return IncompatiblePointer; 8936 } 8937 8938 // U^ -> void* 8939 if (RHSType->getAs<BlockPointerType>()) { 8940 if (LHSPointer->getPointeeType()->isVoidType()) { 8941 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8942 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8943 ->getPointeeType() 8944 .getAddressSpace(); 8945 Kind = 8946 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8947 return Compatible; 8948 } 8949 } 8950 8951 return Incompatible; 8952 } 8953 8954 // Conversions to block pointers. 8955 if (isa<BlockPointerType>(LHSType)) { 8956 // U^ -> T^ 8957 if (RHSType->isBlockPointerType()) { 8958 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 8959 ->getPointeeType() 8960 .getAddressSpace(); 8961 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8962 ->getPointeeType() 8963 .getAddressSpace(); 8964 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8965 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 8966 } 8967 8968 // int or null -> T^ 8969 if (RHSType->isIntegerType()) { 8970 Kind = CK_IntegralToPointer; // FIXME: null 8971 return IntToBlockPointer; 8972 } 8973 8974 // id -> T^ 8975 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 8976 Kind = CK_AnyPointerToBlockPointerCast; 8977 return Compatible; 8978 } 8979 8980 // void* -> T^ 8981 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 8982 if (RHSPT->getPointeeType()->isVoidType()) { 8983 Kind = CK_AnyPointerToBlockPointerCast; 8984 return Compatible; 8985 } 8986 8987 return Incompatible; 8988 } 8989 8990 // Conversions to Objective-C pointers. 8991 if (isa<ObjCObjectPointerType>(LHSType)) { 8992 // A* -> B* 8993 if (RHSType->isObjCObjectPointerType()) { 8994 Kind = CK_BitCast; 8995 Sema::AssignConvertType result = 8996 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 8997 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8998 result == Compatible && 8999 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9000 result = IncompatibleObjCWeakRef; 9001 return result; 9002 } 9003 9004 // int or null -> A* 9005 if (RHSType->isIntegerType()) { 9006 Kind = CK_IntegralToPointer; // FIXME: null 9007 return IntToPointer; 9008 } 9009 9010 // In general, C pointers are not compatible with ObjC object pointers, 9011 // with two exceptions: 9012 if (isa<PointerType>(RHSType)) { 9013 Kind = CK_CPointerToObjCPointerCast; 9014 9015 // - conversions from 'void*' 9016 if (RHSType->isVoidPointerType()) { 9017 return Compatible; 9018 } 9019 9020 // - conversions to 'Class' from its redefinition type 9021 if (LHSType->isObjCClassType() && 9022 Context.hasSameType(RHSType, 9023 Context.getObjCClassRedefinitionType())) { 9024 return Compatible; 9025 } 9026 9027 return IncompatiblePointer; 9028 } 9029 9030 // Only under strict condition T^ is compatible with an Objective-C pointer. 9031 if (RHSType->isBlockPointerType() && 9032 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9033 if (ConvertRHS) 9034 maybeExtendBlockObject(RHS); 9035 Kind = CK_BlockPointerToObjCPointerCast; 9036 return Compatible; 9037 } 9038 9039 return Incompatible; 9040 } 9041 9042 // Conversions from pointers that are not covered by the above. 9043 if (isa<PointerType>(RHSType)) { 9044 // T* -> _Bool 9045 if (LHSType == Context.BoolTy) { 9046 Kind = CK_PointerToBoolean; 9047 return Compatible; 9048 } 9049 9050 // T* -> int 9051 if (LHSType->isIntegerType()) { 9052 Kind = CK_PointerToIntegral; 9053 return PointerToInt; 9054 } 9055 9056 return Incompatible; 9057 } 9058 9059 // Conversions from Objective-C pointers that are not covered by the above. 9060 if (isa<ObjCObjectPointerType>(RHSType)) { 9061 // T* -> _Bool 9062 if (LHSType == Context.BoolTy) { 9063 Kind = CK_PointerToBoolean; 9064 return Compatible; 9065 } 9066 9067 // T* -> int 9068 if (LHSType->isIntegerType()) { 9069 Kind = CK_PointerToIntegral; 9070 return PointerToInt; 9071 } 9072 9073 return Incompatible; 9074 } 9075 9076 // struct A -> struct B 9077 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9078 if (Context.typesAreCompatible(LHSType, RHSType)) { 9079 Kind = CK_NoOp; 9080 return Compatible; 9081 } 9082 } 9083 9084 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9085 Kind = CK_IntToOCLSampler; 9086 return Compatible; 9087 } 9088 9089 return Incompatible; 9090 } 9091 9092 /// Constructs a transparent union from an expression that is 9093 /// used to initialize the transparent union. 9094 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9095 ExprResult &EResult, QualType UnionType, 9096 FieldDecl *Field) { 9097 // Build an initializer list that designates the appropriate member 9098 // of the transparent union. 9099 Expr *E = EResult.get(); 9100 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9101 E, SourceLocation()); 9102 Initializer->setType(UnionType); 9103 Initializer->setInitializedFieldInUnion(Field); 9104 9105 // Build a compound literal constructing a value of the transparent 9106 // union type from this initializer list. 9107 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9108 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9109 VK_RValue, Initializer, false); 9110 } 9111 9112 Sema::AssignConvertType 9113 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9114 ExprResult &RHS) { 9115 QualType RHSType = RHS.get()->getType(); 9116 9117 // If the ArgType is a Union type, we want to handle a potential 9118 // transparent_union GCC extension. 9119 const RecordType *UT = ArgType->getAsUnionType(); 9120 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9121 return Incompatible; 9122 9123 // The field to initialize within the transparent union. 9124 RecordDecl *UD = UT->getDecl(); 9125 FieldDecl *InitField = nullptr; 9126 // It's compatible if the expression matches any of the fields. 9127 for (auto *it : UD->fields()) { 9128 if (it->getType()->isPointerType()) { 9129 // If the transparent union contains a pointer type, we allow: 9130 // 1) void pointer 9131 // 2) null pointer constant 9132 if (RHSType->isPointerType()) 9133 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9134 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9135 InitField = it; 9136 break; 9137 } 9138 9139 if (RHS.get()->isNullPointerConstant(Context, 9140 Expr::NPC_ValueDependentIsNull)) { 9141 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9142 CK_NullToPointer); 9143 InitField = it; 9144 break; 9145 } 9146 } 9147 9148 CastKind Kind; 9149 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9150 == Compatible) { 9151 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9152 InitField = it; 9153 break; 9154 } 9155 } 9156 9157 if (!InitField) 9158 return Incompatible; 9159 9160 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9161 return Compatible; 9162 } 9163 9164 Sema::AssignConvertType 9165 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9166 bool Diagnose, 9167 bool DiagnoseCFAudited, 9168 bool ConvertRHS) { 9169 // We need to be able to tell the caller whether we diagnosed a problem, if 9170 // they ask us to issue diagnostics. 9171 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9172 9173 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9174 // we can't avoid *all* modifications at the moment, so we need some somewhere 9175 // to put the updated value. 9176 ExprResult LocalRHS = CallerRHS; 9177 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9178 9179 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9180 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9181 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9182 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9183 Diag(RHS.get()->getExprLoc(), 9184 diag::warn_noderef_to_dereferenceable_pointer) 9185 << RHS.get()->getSourceRange(); 9186 } 9187 } 9188 } 9189 9190 if (getLangOpts().CPlusPlus) { 9191 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9192 // C++ 5.17p3: If the left operand is not of class type, the 9193 // expression is implicitly converted (C++ 4) to the 9194 // cv-unqualified type of the left operand. 9195 QualType RHSType = RHS.get()->getType(); 9196 if (Diagnose) { 9197 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9198 AA_Assigning); 9199 } else { 9200 ImplicitConversionSequence ICS = 9201 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9202 /*SuppressUserConversions=*/false, 9203 AllowedExplicit::None, 9204 /*InOverloadResolution=*/false, 9205 /*CStyle=*/false, 9206 /*AllowObjCWritebackConversion=*/false); 9207 if (ICS.isFailure()) 9208 return Incompatible; 9209 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9210 ICS, AA_Assigning); 9211 } 9212 if (RHS.isInvalid()) 9213 return Incompatible; 9214 Sema::AssignConvertType result = Compatible; 9215 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9216 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9217 result = IncompatibleObjCWeakRef; 9218 return result; 9219 } 9220 9221 // FIXME: Currently, we fall through and treat C++ classes like C 9222 // structures. 9223 // FIXME: We also fall through for atomics; not sure what should 9224 // happen there, though. 9225 } else if (RHS.get()->getType() == Context.OverloadTy) { 9226 // As a set of extensions to C, we support overloading on functions. These 9227 // functions need to be resolved here. 9228 DeclAccessPair DAP; 9229 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9230 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9231 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9232 else 9233 return Incompatible; 9234 } 9235 9236 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9237 // a null pointer constant. 9238 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9239 LHSType->isBlockPointerType()) && 9240 RHS.get()->isNullPointerConstant(Context, 9241 Expr::NPC_ValueDependentIsNull)) { 9242 if (Diagnose || ConvertRHS) { 9243 CastKind Kind; 9244 CXXCastPath Path; 9245 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9246 /*IgnoreBaseAccess=*/false, Diagnose); 9247 if (ConvertRHS) 9248 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 9249 } 9250 return Compatible; 9251 } 9252 9253 // OpenCL queue_t type assignment. 9254 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9255 Context, Expr::NPC_ValueDependentIsNull)) { 9256 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9257 return Compatible; 9258 } 9259 9260 // This check seems unnatural, however it is necessary to ensure the proper 9261 // conversion of functions/arrays. If the conversion were done for all 9262 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9263 // expressions that suppress this implicit conversion (&, sizeof). 9264 // 9265 // Suppress this for references: C++ 8.5.3p5. 9266 if (!LHSType->isReferenceType()) { 9267 // FIXME: We potentially allocate here even if ConvertRHS is false. 9268 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9269 if (RHS.isInvalid()) 9270 return Incompatible; 9271 } 9272 CastKind Kind; 9273 Sema::AssignConvertType result = 9274 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9275 9276 // C99 6.5.16.1p2: The value of the right operand is converted to the 9277 // type of the assignment expression. 9278 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9279 // so that we can use references in built-in functions even in C. 9280 // The getNonReferenceType() call makes sure that the resulting expression 9281 // does not have reference type. 9282 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9283 QualType Ty = LHSType.getNonLValueExprType(Context); 9284 Expr *E = RHS.get(); 9285 9286 // Check for various Objective-C errors. If we are not reporting 9287 // diagnostics and just checking for errors, e.g., during overload 9288 // resolution, return Incompatible to indicate the failure. 9289 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9290 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9291 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9292 if (!Diagnose) 9293 return Incompatible; 9294 } 9295 if (getLangOpts().ObjC && 9296 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9297 E->getType(), E, Diagnose) || 9298 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9299 if (!Diagnose) 9300 return Incompatible; 9301 // Replace the expression with a corrected version and continue so we 9302 // can find further errors. 9303 RHS = E; 9304 return Compatible; 9305 } 9306 9307 if (ConvertRHS) 9308 RHS = ImpCastExprToType(E, Ty, Kind); 9309 } 9310 9311 return result; 9312 } 9313 9314 namespace { 9315 /// The original operand to an operator, prior to the application of the usual 9316 /// arithmetic conversions and converting the arguments of a builtin operator 9317 /// candidate. 9318 struct OriginalOperand { 9319 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9320 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9321 Op = MTE->getSubExpr(); 9322 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9323 Op = BTE->getSubExpr(); 9324 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9325 Orig = ICE->getSubExprAsWritten(); 9326 Conversion = ICE->getConversionFunction(); 9327 } 9328 } 9329 9330 QualType getType() const { return Orig->getType(); } 9331 9332 Expr *Orig; 9333 NamedDecl *Conversion; 9334 }; 9335 } 9336 9337 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9338 ExprResult &RHS) { 9339 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9340 9341 Diag(Loc, diag::err_typecheck_invalid_operands) 9342 << OrigLHS.getType() << OrigRHS.getType() 9343 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9344 9345 // If a user-defined conversion was applied to either of the operands prior 9346 // to applying the built-in operator rules, tell the user about it. 9347 if (OrigLHS.Conversion) { 9348 Diag(OrigLHS.Conversion->getLocation(), 9349 diag::note_typecheck_invalid_operands_converted) 9350 << 0 << LHS.get()->getType(); 9351 } 9352 if (OrigRHS.Conversion) { 9353 Diag(OrigRHS.Conversion->getLocation(), 9354 diag::note_typecheck_invalid_operands_converted) 9355 << 1 << RHS.get()->getType(); 9356 } 9357 9358 return QualType(); 9359 } 9360 9361 // Diagnose cases where a scalar was implicitly converted to a vector and 9362 // diagnose the underlying types. Otherwise, diagnose the error 9363 // as invalid vector logical operands for non-C++ cases. 9364 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9365 ExprResult &RHS) { 9366 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9367 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9368 9369 bool LHSNatVec = LHSType->isVectorType(); 9370 bool RHSNatVec = RHSType->isVectorType(); 9371 9372 if (!(LHSNatVec && RHSNatVec)) { 9373 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9374 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9375 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9376 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9377 << Vector->getSourceRange(); 9378 return QualType(); 9379 } 9380 9381 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9382 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9383 << RHS.get()->getSourceRange(); 9384 9385 return QualType(); 9386 } 9387 9388 /// Try to convert a value of non-vector type to a vector type by converting 9389 /// the type to the element type of the vector and then performing a splat. 9390 /// If the language is OpenCL, we only use conversions that promote scalar 9391 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9392 /// for float->int. 9393 /// 9394 /// OpenCL V2.0 6.2.6.p2: 9395 /// An error shall occur if any scalar operand type has greater rank 9396 /// than the type of the vector element. 9397 /// 9398 /// \param scalar - if non-null, actually perform the conversions 9399 /// \return true if the operation fails (but without diagnosing the failure) 9400 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9401 QualType scalarTy, 9402 QualType vectorEltTy, 9403 QualType vectorTy, 9404 unsigned &DiagID) { 9405 // The conversion to apply to the scalar before splatting it, 9406 // if necessary. 9407 CastKind scalarCast = CK_NoOp; 9408 9409 if (vectorEltTy->isIntegralType(S.Context)) { 9410 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9411 (scalarTy->isIntegerType() && 9412 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9413 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9414 return true; 9415 } 9416 if (!scalarTy->isIntegralType(S.Context)) 9417 return true; 9418 scalarCast = CK_IntegralCast; 9419 } else if (vectorEltTy->isRealFloatingType()) { 9420 if (scalarTy->isRealFloatingType()) { 9421 if (S.getLangOpts().OpenCL && 9422 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9423 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9424 return true; 9425 } 9426 scalarCast = CK_FloatingCast; 9427 } 9428 else if (scalarTy->isIntegralType(S.Context)) 9429 scalarCast = CK_IntegralToFloating; 9430 else 9431 return true; 9432 } else { 9433 return true; 9434 } 9435 9436 // Adjust scalar if desired. 9437 if (scalar) { 9438 if (scalarCast != CK_NoOp) 9439 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9440 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9441 } 9442 return false; 9443 } 9444 9445 /// Convert vector E to a vector with the same number of elements but different 9446 /// element type. 9447 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9448 const auto *VecTy = E->getType()->getAs<VectorType>(); 9449 assert(VecTy && "Expression E must be a vector"); 9450 QualType NewVecTy = S.Context.getVectorType(ElementType, 9451 VecTy->getNumElements(), 9452 VecTy->getVectorKind()); 9453 9454 // Look through the implicit cast. Return the subexpression if its type is 9455 // NewVecTy. 9456 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9457 if (ICE->getSubExpr()->getType() == NewVecTy) 9458 return ICE->getSubExpr(); 9459 9460 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9461 return S.ImpCastExprToType(E, NewVecTy, Cast); 9462 } 9463 9464 /// Test if a (constant) integer Int can be casted to another integer type 9465 /// IntTy without losing precision. 9466 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9467 QualType OtherIntTy) { 9468 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9469 9470 // Reject cases where the value of the Int is unknown as that would 9471 // possibly cause truncation, but accept cases where the scalar can be 9472 // demoted without loss of precision. 9473 Expr::EvalResult EVResult; 9474 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9475 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9476 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9477 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9478 9479 if (CstInt) { 9480 // If the scalar is constant and is of a higher order and has more active 9481 // bits that the vector element type, reject it. 9482 llvm::APSInt Result = EVResult.Val.getInt(); 9483 unsigned NumBits = IntSigned 9484 ? (Result.isNegative() ? Result.getMinSignedBits() 9485 : Result.getActiveBits()) 9486 : Result.getActiveBits(); 9487 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9488 return true; 9489 9490 // If the signedness of the scalar type and the vector element type 9491 // differs and the number of bits is greater than that of the vector 9492 // element reject it. 9493 return (IntSigned != OtherIntSigned && 9494 NumBits > S.Context.getIntWidth(OtherIntTy)); 9495 } 9496 9497 // Reject cases where the value of the scalar is not constant and it's 9498 // order is greater than that of the vector element type. 9499 return (Order < 0); 9500 } 9501 9502 /// Test if a (constant) integer Int can be casted to floating point type 9503 /// FloatTy without losing precision. 9504 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9505 QualType FloatTy) { 9506 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9507 9508 // Determine if the integer constant can be expressed as a floating point 9509 // number of the appropriate type. 9510 Expr::EvalResult EVResult; 9511 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9512 9513 uint64_t Bits = 0; 9514 if (CstInt) { 9515 // Reject constants that would be truncated if they were converted to 9516 // the floating point type. Test by simple to/from conversion. 9517 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9518 // could be avoided if there was a convertFromAPInt method 9519 // which could signal back if implicit truncation occurred. 9520 llvm::APSInt Result = EVResult.Val.getInt(); 9521 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9522 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9523 llvm::APFloat::rmTowardZero); 9524 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9525 !IntTy->hasSignedIntegerRepresentation()); 9526 bool Ignored = false; 9527 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9528 &Ignored); 9529 if (Result != ConvertBack) 9530 return true; 9531 } else { 9532 // Reject types that cannot be fully encoded into the mantissa of 9533 // the float. 9534 Bits = S.Context.getTypeSize(IntTy); 9535 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9536 S.Context.getFloatTypeSemantics(FloatTy)); 9537 if (Bits > FloatPrec) 9538 return true; 9539 } 9540 9541 return false; 9542 } 9543 9544 /// Attempt to convert and splat Scalar into a vector whose types matches 9545 /// Vector following GCC conversion rules. The rule is that implicit 9546 /// conversion can occur when Scalar can be casted to match Vector's element 9547 /// type without causing truncation of Scalar. 9548 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9549 ExprResult *Vector) { 9550 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9551 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9552 const VectorType *VT = VectorTy->getAs<VectorType>(); 9553 9554 assert(!isa<ExtVectorType>(VT) && 9555 "ExtVectorTypes should not be handled here!"); 9556 9557 QualType VectorEltTy = VT->getElementType(); 9558 9559 // Reject cases where the vector element type or the scalar element type are 9560 // not integral or floating point types. 9561 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9562 return true; 9563 9564 // The conversion to apply to the scalar before splatting it, 9565 // if necessary. 9566 CastKind ScalarCast = CK_NoOp; 9567 9568 // Accept cases where the vector elements are integers and the scalar is 9569 // an integer. 9570 // FIXME: Notionally if the scalar was a floating point value with a precise 9571 // integral representation, we could cast it to an appropriate integer 9572 // type and then perform the rest of the checks here. GCC will perform 9573 // this conversion in some cases as determined by the input language. 9574 // We should accept it on a language independent basis. 9575 if (VectorEltTy->isIntegralType(S.Context) && 9576 ScalarTy->isIntegralType(S.Context) && 9577 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9578 9579 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9580 return true; 9581 9582 ScalarCast = CK_IntegralCast; 9583 } else if (VectorEltTy->isIntegralType(S.Context) && 9584 ScalarTy->isRealFloatingType()) { 9585 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9586 ScalarCast = CK_FloatingToIntegral; 9587 else 9588 return true; 9589 } else if (VectorEltTy->isRealFloatingType()) { 9590 if (ScalarTy->isRealFloatingType()) { 9591 9592 // Reject cases where the scalar type is not a constant and has a higher 9593 // Order than the vector element type. 9594 llvm::APFloat Result(0.0); 9595 9596 // Determine whether this is a constant scalar. In the event that the 9597 // value is dependent (and thus cannot be evaluated by the constant 9598 // evaluator), skip the evaluation. This will then diagnose once the 9599 // expression is instantiated. 9600 bool CstScalar = Scalar->get()->isValueDependent() || 9601 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9602 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9603 if (!CstScalar && Order < 0) 9604 return true; 9605 9606 // If the scalar cannot be safely casted to the vector element type, 9607 // reject it. 9608 if (CstScalar) { 9609 bool Truncated = false; 9610 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9611 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9612 if (Truncated) 9613 return true; 9614 } 9615 9616 ScalarCast = CK_FloatingCast; 9617 } else if (ScalarTy->isIntegralType(S.Context)) { 9618 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9619 return true; 9620 9621 ScalarCast = CK_IntegralToFloating; 9622 } else 9623 return true; 9624 } 9625 9626 // Adjust scalar if desired. 9627 if (Scalar) { 9628 if (ScalarCast != CK_NoOp) 9629 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9630 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9631 } 9632 return false; 9633 } 9634 9635 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9636 SourceLocation Loc, bool IsCompAssign, 9637 bool AllowBothBool, 9638 bool AllowBoolConversions) { 9639 if (!IsCompAssign) { 9640 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9641 if (LHS.isInvalid()) 9642 return QualType(); 9643 } 9644 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9645 if (RHS.isInvalid()) 9646 return QualType(); 9647 9648 // For conversion purposes, we ignore any qualifiers. 9649 // For example, "const float" and "float" are equivalent. 9650 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9651 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9652 9653 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9654 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9655 assert(LHSVecType || RHSVecType); 9656 9657 // AltiVec-style "vector bool op vector bool" combinations are allowed 9658 // for some operators but not others. 9659 if (!AllowBothBool && 9660 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9661 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9662 return InvalidOperands(Loc, LHS, RHS); 9663 9664 // If the vector types are identical, return. 9665 if (Context.hasSameType(LHSType, RHSType)) 9666 return LHSType; 9667 9668 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9669 if (LHSVecType && RHSVecType && 9670 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9671 if (isa<ExtVectorType>(LHSVecType)) { 9672 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9673 return LHSType; 9674 } 9675 9676 if (!IsCompAssign) 9677 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9678 return RHSType; 9679 } 9680 9681 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9682 // can be mixed, with the result being the non-bool type. The non-bool 9683 // operand must have integer element type. 9684 if (AllowBoolConversions && LHSVecType && RHSVecType && 9685 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9686 (Context.getTypeSize(LHSVecType->getElementType()) == 9687 Context.getTypeSize(RHSVecType->getElementType()))) { 9688 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9689 LHSVecType->getElementType()->isIntegerType() && 9690 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9691 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9692 return LHSType; 9693 } 9694 if (!IsCompAssign && 9695 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9696 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9697 RHSVecType->getElementType()->isIntegerType()) { 9698 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9699 return RHSType; 9700 } 9701 } 9702 9703 // If there's a vector type and a scalar, try to convert the scalar to 9704 // the vector element type and splat. 9705 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9706 if (!RHSVecType) { 9707 if (isa<ExtVectorType>(LHSVecType)) { 9708 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9709 LHSVecType->getElementType(), LHSType, 9710 DiagID)) 9711 return LHSType; 9712 } else { 9713 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9714 return LHSType; 9715 } 9716 } 9717 if (!LHSVecType) { 9718 if (isa<ExtVectorType>(RHSVecType)) { 9719 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9720 LHSType, RHSVecType->getElementType(), 9721 RHSType, DiagID)) 9722 return RHSType; 9723 } else { 9724 if (LHS.get()->getValueKind() == VK_LValue || 9725 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9726 return RHSType; 9727 } 9728 } 9729 9730 // FIXME: The code below also handles conversion between vectors and 9731 // non-scalars, we should break this down into fine grained specific checks 9732 // and emit proper diagnostics. 9733 QualType VecType = LHSVecType ? LHSType : RHSType; 9734 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9735 QualType OtherType = LHSVecType ? RHSType : LHSType; 9736 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9737 if (isLaxVectorConversion(OtherType, VecType)) { 9738 // If we're allowing lax vector conversions, only the total (data) size 9739 // needs to be the same. For non compound assignment, if one of the types is 9740 // scalar, the result is always the vector type. 9741 if (!IsCompAssign) { 9742 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9743 return VecType; 9744 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9745 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9746 // type. Note that this is already done by non-compound assignments in 9747 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9748 // <1 x T> -> T. The result is also a vector type. 9749 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9750 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9751 ExprResult *RHSExpr = &RHS; 9752 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9753 return VecType; 9754 } 9755 } 9756 9757 // Okay, the expression is invalid. 9758 9759 // If there's a non-vector, non-real operand, diagnose that. 9760 if ((!RHSVecType && !RHSType->isRealType()) || 9761 (!LHSVecType && !LHSType->isRealType())) { 9762 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9763 << LHSType << RHSType 9764 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9765 return QualType(); 9766 } 9767 9768 // OpenCL V1.1 6.2.6.p1: 9769 // If the operands are of more than one vector type, then an error shall 9770 // occur. Implicit conversions between vector types are not permitted, per 9771 // section 6.2.1. 9772 if (getLangOpts().OpenCL && 9773 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9774 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9775 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9776 << RHSType; 9777 return QualType(); 9778 } 9779 9780 9781 // If there is a vector type that is not a ExtVector and a scalar, we reach 9782 // this point if scalar could not be converted to the vector's element type 9783 // without truncation. 9784 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9785 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9786 QualType Scalar = LHSVecType ? RHSType : LHSType; 9787 QualType Vector = LHSVecType ? LHSType : RHSType; 9788 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9789 Diag(Loc, 9790 diag::err_typecheck_vector_not_convertable_implict_truncation) 9791 << ScalarOrVector << Scalar << Vector; 9792 9793 return QualType(); 9794 } 9795 9796 // Otherwise, use the generic diagnostic. 9797 Diag(Loc, DiagID) 9798 << LHSType << RHSType 9799 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9800 return QualType(); 9801 } 9802 9803 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9804 // expression. These are mainly cases where the null pointer is used as an 9805 // integer instead of a pointer. 9806 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9807 SourceLocation Loc, bool IsCompare) { 9808 // The canonical way to check for a GNU null is with isNullPointerConstant, 9809 // but we use a bit of a hack here for speed; this is a relatively 9810 // hot path, and isNullPointerConstant is slow. 9811 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9812 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9813 9814 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9815 9816 // Avoid analyzing cases where the result will either be invalid (and 9817 // diagnosed as such) or entirely valid and not something to warn about. 9818 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9819 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9820 return; 9821 9822 // Comparison operations would not make sense with a null pointer no matter 9823 // what the other expression is. 9824 if (!IsCompare) { 9825 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9826 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9827 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9828 return; 9829 } 9830 9831 // The rest of the operations only make sense with a null pointer 9832 // if the other expression is a pointer. 9833 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 9834 NonNullType->canDecayToPointerType()) 9835 return; 9836 9837 S.Diag(Loc, diag::warn_null_in_comparison_operation) 9838 << LHSNull /* LHS is NULL */ << NonNullType 9839 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9840 } 9841 9842 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 9843 SourceLocation Loc) { 9844 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 9845 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 9846 if (!LUE || !RUE) 9847 return; 9848 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 9849 RUE->getKind() != UETT_SizeOf) 9850 return; 9851 9852 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 9853 QualType LHSTy = LHSArg->getType(); 9854 QualType RHSTy; 9855 9856 if (RUE->isArgumentType()) 9857 RHSTy = RUE->getArgumentType(); 9858 else 9859 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 9860 9861 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 9862 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 9863 return; 9864 9865 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 9866 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9867 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9868 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 9869 << LHSArgDecl; 9870 } 9871 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 9872 QualType ArrayElemTy = ArrayTy->getElementType(); 9873 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 9874 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 9875 ArrayElemTy->isCharType() || 9876 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 9877 return; 9878 S.Diag(Loc, diag::warn_division_sizeof_array) 9879 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 9880 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9881 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9882 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 9883 << LHSArgDecl; 9884 } 9885 9886 S.Diag(Loc, diag::note_precedence_silence) << RHS; 9887 } 9888 } 9889 9890 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 9891 ExprResult &RHS, 9892 SourceLocation Loc, bool IsDiv) { 9893 // Check for division/remainder by zero. 9894 Expr::EvalResult RHSValue; 9895 if (!RHS.get()->isValueDependent() && 9896 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 9897 RHSValue.Val.getInt() == 0) 9898 S.DiagRuntimeBehavior(Loc, RHS.get(), 9899 S.PDiag(diag::warn_remainder_division_by_zero) 9900 << IsDiv << RHS.get()->getSourceRange()); 9901 } 9902 9903 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 9904 SourceLocation Loc, 9905 bool IsCompAssign, bool IsDiv) { 9906 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9907 9908 if (LHS.get()->getType()->isVectorType() || 9909 RHS.get()->getType()->isVectorType()) 9910 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9911 /*AllowBothBool*/getLangOpts().AltiVec, 9912 /*AllowBoolConversions*/false); 9913 9914 QualType compType = UsualArithmeticConversions( 9915 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 9916 if (LHS.isInvalid() || RHS.isInvalid()) 9917 return QualType(); 9918 9919 9920 if (compType.isNull() || !compType->isArithmeticType()) 9921 return InvalidOperands(Loc, LHS, RHS); 9922 if (IsDiv) { 9923 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 9924 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 9925 } 9926 return compType; 9927 } 9928 9929 QualType Sema::CheckRemainderOperands( 9930 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9931 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9932 9933 if (LHS.get()->getType()->isVectorType() || 9934 RHS.get()->getType()->isVectorType()) { 9935 if (LHS.get()->getType()->hasIntegerRepresentation() && 9936 RHS.get()->getType()->hasIntegerRepresentation()) 9937 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9938 /*AllowBothBool*/getLangOpts().AltiVec, 9939 /*AllowBoolConversions*/false); 9940 return InvalidOperands(Loc, LHS, RHS); 9941 } 9942 9943 QualType compType = UsualArithmeticConversions( 9944 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 9945 if (LHS.isInvalid() || RHS.isInvalid()) 9946 return QualType(); 9947 9948 if (compType.isNull() || !compType->isIntegerType()) 9949 return InvalidOperands(Loc, LHS, RHS); 9950 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 9951 return compType; 9952 } 9953 9954 /// Diagnose invalid arithmetic on two void pointers. 9955 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 9956 Expr *LHSExpr, Expr *RHSExpr) { 9957 S.Diag(Loc, S.getLangOpts().CPlusPlus 9958 ? diag::err_typecheck_pointer_arith_void_type 9959 : diag::ext_gnu_void_ptr) 9960 << 1 /* two pointers */ << LHSExpr->getSourceRange() 9961 << RHSExpr->getSourceRange(); 9962 } 9963 9964 /// Diagnose invalid arithmetic on a void pointer. 9965 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 9966 Expr *Pointer) { 9967 S.Diag(Loc, S.getLangOpts().CPlusPlus 9968 ? diag::err_typecheck_pointer_arith_void_type 9969 : diag::ext_gnu_void_ptr) 9970 << 0 /* one pointer */ << Pointer->getSourceRange(); 9971 } 9972 9973 /// Diagnose invalid arithmetic on a null pointer. 9974 /// 9975 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 9976 /// idiom, which we recognize as a GNU extension. 9977 /// 9978 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 9979 Expr *Pointer, bool IsGNUIdiom) { 9980 if (IsGNUIdiom) 9981 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 9982 << Pointer->getSourceRange(); 9983 else 9984 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 9985 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 9986 } 9987 9988 /// Diagnose invalid arithmetic on two function pointers. 9989 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 9990 Expr *LHS, Expr *RHS) { 9991 assert(LHS->getType()->isAnyPointerType()); 9992 assert(RHS->getType()->isAnyPointerType()); 9993 S.Diag(Loc, S.getLangOpts().CPlusPlus 9994 ? diag::err_typecheck_pointer_arith_function_type 9995 : diag::ext_gnu_ptr_func_arith) 9996 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 9997 // We only show the second type if it differs from the first. 9998 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 9999 RHS->getType()) 10000 << RHS->getType()->getPointeeType() 10001 << LHS->getSourceRange() << RHS->getSourceRange(); 10002 } 10003 10004 /// Diagnose invalid arithmetic on a function pointer. 10005 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10006 Expr *Pointer) { 10007 assert(Pointer->getType()->isAnyPointerType()); 10008 S.Diag(Loc, S.getLangOpts().CPlusPlus 10009 ? diag::err_typecheck_pointer_arith_function_type 10010 : diag::ext_gnu_ptr_func_arith) 10011 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10012 << 0 /* one pointer, so only one type */ 10013 << Pointer->getSourceRange(); 10014 } 10015 10016 /// Emit error if Operand is incomplete pointer type 10017 /// 10018 /// \returns True if pointer has incomplete type 10019 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10020 Expr *Operand) { 10021 QualType ResType = Operand->getType(); 10022 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10023 ResType = ResAtomicType->getValueType(); 10024 10025 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10026 QualType PointeeTy = ResType->getPointeeType(); 10027 return S.RequireCompleteSizedType( 10028 Loc, PointeeTy, 10029 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10030 Operand->getSourceRange()); 10031 } 10032 10033 /// Check the validity of an arithmetic pointer operand. 10034 /// 10035 /// If the operand has pointer type, this code will check for pointer types 10036 /// which are invalid in arithmetic operations. These will be diagnosed 10037 /// appropriately, including whether or not the use is supported as an 10038 /// extension. 10039 /// 10040 /// \returns True when the operand is valid to use (even if as an extension). 10041 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10042 Expr *Operand) { 10043 QualType ResType = Operand->getType(); 10044 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10045 ResType = ResAtomicType->getValueType(); 10046 10047 if (!ResType->isAnyPointerType()) return true; 10048 10049 QualType PointeeTy = ResType->getPointeeType(); 10050 if (PointeeTy->isVoidType()) { 10051 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10052 return !S.getLangOpts().CPlusPlus; 10053 } 10054 if (PointeeTy->isFunctionType()) { 10055 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10056 return !S.getLangOpts().CPlusPlus; 10057 } 10058 10059 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10060 10061 return true; 10062 } 10063 10064 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10065 /// operands. 10066 /// 10067 /// This routine will diagnose any invalid arithmetic on pointer operands much 10068 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10069 /// for emitting a single diagnostic even for operations where both LHS and RHS 10070 /// are (potentially problematic) pointers. 10071 /// 10072 /// \returns True when the operand is valid to use (even if as an extension). 10073 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10074 Expr *LHSExpr, Expr *RHSExpr) { 10075 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10076 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10077 if (!isLHSPointer && !isRHSPointer) return true; 10078 10079 QualType LHSPointeeTy, RHSPointeeTy; 10080 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10081 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10082 10083 // if both are pointers check if operation is valid wrt address spaces 10084 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 10085 const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>(); 10086 const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>(); 10087 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 10088 S.Diag(Loc, 10089 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10090 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10091 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10092 return false; 10093 } 10094 } 10095 10096 // Check for arithmetic on pointers to incomplete types. 10097 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10098 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10099 if (isLHSVoidPtr || isRHSVoidPtr) { 10100 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10101 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10102 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10103 10104 return !S.getLangOpts().CPlusPlus; 10105 } 10106 10107 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10108 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10109 if (isLHSFuncPtr || isRHSFuncPtr) { 10110 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10111 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10112 RHSExpr); 10113 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10114 10115 return !S.getLangOpts().CPlusPlus; 10116 } 10117 10118 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10119 return false; 10120 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10121 return false; 10122 10123 return true; 10124 } 10125 10126 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10127 /// literal. 10128 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10129 Expr *LHSExpr, Expr *RHSExpr) { 10130 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10131 Expr* IndexExpr = RHSExpr; 10132 if (!StrExpr) { 10133 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10134 IndexExpr = LHSExpr; 10135 } 10136 10137 bool IsStringPlusInt = StrExpr && 10138 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10139 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10140 return; 10141 10142 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10143 Self.Diag(OpLoc, diag::warn_string_plus_int) 10144 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10145 10146 // Only print a fixit for "str" + int, not for int + "str". 10147 if (IndexExpr == RHSExpr) { 10148 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10149 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10150 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10151 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10152 << FixItHint::CreateInsertion(EndLoc, "]"); 10153 } else 10154 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10155 } 10156 10157 /// Emit a warning when adding a char literal to a string. 10158 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10159 Expr *LHSExpr, Expr *RHSExpr) { 10160 const Expr *StringRefExpr = LHSExpr; 10161 const CharacterLiteral *CharExpr = 10162 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10163 10164 if (!CharExpr) { 10165 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10166 StringRefExpr = RHSExpr; 10167 } 10168 10169 if (!CharExpr || !StringRefExpr) 10170 return; 10171 10172 const QualType StringType = StringRefExpr->getType(); 10173 10174 // Return if not a PointerType. 10175 if (!StringType->isAnyPointerType()) 10176 return; 10177 10178 // Return if not a CharacterType. 10179 if (!StringType->getPointeeType()->isAnyCharacterType()) 10180 return; 10181 10182 ASTContext &Ctx = Self.getASTContext(); 10183 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10184 10185 const QualType CharType = CharExpr->getType(); 10186 if (!CharType->isAnyCharacterType() && 10187 CharType->isIntegerType() && 10188 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10189 Self.Diag(OpLoc, diag::warn_string_plus_char) 10190 << DiagRange << Ctx.CharTy; 10191 } else { 10192 Self.Diag(OpLoc, diag::warn_string_plus_char) 10193 << DiagRange << CharExpr->getType(); 10194 } 10195 10196 // Only print a fixit for str + char, not for char + str. 10197 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10198 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10199 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10200 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10201 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10202 << FixItHint::CreateInsertion(EndLoc, "]"); 10203 } else { 10204 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10205 } 10206 } 10207 10208 /// Emit error when two pointers are incompatible. 10209 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10210 Expr *LHSExpr, Expr *RHSExpr) { 10211 assert(LHSExpr->getType()->isAnyPointerType()); 10212 assert(RHSExpr->getType()->isAnyPointerType()); 10213 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10214 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10215 << RHSExpr->getSourceRange(); 10216 } 10217 10218 // C99 6.5.6 10219 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10220 SourceLocation Loc, BinaryOperatorKind Opc, 10221 QualType* CompLHSTy) { 10222 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10223 10224 if (LHS.get()->getType()->isVectorType() || 10225 RHS.get()->getType()->isVectorType()) { 10226 QualType compType = CheckVectorOperands( 10227 LHS, RHS, Loc, CompLHSTy, 10228 /*AllowBothBool*/getLangOpts().AltiVec, 10229 /*AllowBoolConversions*/getLangOpts().ZVector); 10230 if (CompLHSTy) *CompLHSTy = compType; 10231 return compType; 10232 } 10233 10234 QualType compType = UsualArithmeticConversions( 10235 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10236 if (LHS.isInvalid() || RHS.isInvalid()) 10237 return QualType(); 10238 10239 // Diagnose "string literal" '+' int and string '+' "char literal". 10240 if (Opc == BO_Add) { 10241 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10242 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10243 } 10244 10245 // handle the common case first (both operands are arithmetic). 10246 if (!compType.isNull() && compType->isArithmeticType()) { 10247 if (CompLHSTy) *CompLHSTy = compType; 10248 return compType; 10249 } 10250 10251 // Type-checking. Ultimately the pointer's going to be in PExp; 10252 // note that we bias towards the LHS being the pointer. 10253 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10254 10255 bool isObjCPointer; 10256 if (PExp->getType()->isPointerType()) { 10257 isObjCPointer = false; 10258 } else if (PExp->getType()->isObjCObjectPointerType()) { 10259 isObjCPointer = true; 10260 } else { 10261 std::swap(PExp, IExp); 10262 if (PExp->getType()->isPointerType()) { 10263 isObjCPointer = false; 10264 } else if (PExp->getType()->isObjCObjectPointerType()) { 10265 isObjCPointer = true; 10266 } else { 10267 return InvalidOperands(Loc, LHS, RHS); 10268 } 10269 } 10270 assert(PExp->getType()->isAnyPointerType()); 10271 10272 if (!IExp->getType()->isIntegerType()) 10273 return InvalidOperands(Loc, LHS, RHS); 10274 10275 // Adding to a null pointer results in undefined behavior. 10276 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10277 Context, Expr::NPC_ValueDependentIsNotNull)) { 10278 // In C++ adding zero to a null pointer is defined. 10279 Expr::EvalResult KnownVal; 10280 if (!getLangOpts().CPlusPlus || 10281 (!IExp->isValueDependent() && 10282 (!IExp->EvaluateAsInt(KnownVal, Context) || 10283 KnownVal.Val.getInt() != 0))) { 10284 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10285 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10286 Context, BO_Add, PExp, IExp); 10287 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10288 } 10289 } 10290 10291 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10292 return QualType(); 10293 10294 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10295 return QualType(); 10296 10297 // Check array bounds for pointer arithemtic 10298 CheckArrayAccess(PExp, IExp); 10299 10300 if (CompLHSTy) { 10301 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10302 if (LHSTy.isNull()) { 10303 LHSTy = LHS.get()->getType(); 10304 if (LHSTy->isPromotableIntegerType()) 10305 LHSTy = Context.getPromotedIntegerType(LHSTy); 10306 } 10307 *CompLHSTy = LHSTy; 10308 } 10309 10310 return PExp->getType(); 10311 } 10312 10313 // C99 6.5.6 10314 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10315 SourceLocation Loc, 10316 QualType* CompLHSTy) { 10317 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10318 10319 if (LHS.get()->getType()->isVectorType() || 10320 RHS.get()->getType()->isVectorType()) { 10321 QualType compType = CheckVectorOperands( 10322 LHS, RHS, Loc, CompLHSTy, 10323 /*AllowBothBool*/getLangOpts().AltiVec, 10324 /*AllowBoolConversions*/getLangOpts().ZVector); 10325 if (CompLHSTy) *CompLHSTy = compType; 10326 return compType; 10327 } 10328 10329 QualType compType = UsualArithmeticConversions( 10330 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10331 if (LHS.isInvalid() || RHS.isInvalid()) 10332 return QualType(); 10333 10334 // Enforce type constraints: C99 6.5.6p3. 10335 10336 // Handle the common case first (both operands are arithmetic). 10337 if (!compType.isNull() && compType->isArithmeticType()) { 10338 if (CompLHSTy) *CompLHSTy = compType; 10339 return compType; 10340 } 10341 10342 // Either ptr - int or ptr - ptr. 10343 if (LHS.get()->getType()->isAnyPointerType()) { 10344 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10345 10346 // Diagnose bad cases where we step over interface counts. 10347 if (LHS.get()->getType()->isObjCObjectPointerType() && 10348 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10349 return QualType(); 10350 10351 // The result type of a pointer-int computation is the pointer type. 10352 if (RHS.get()->getType()->isIntegerType()) { 10353 // Subtracting from a null pointer should produce a warning. 10354 // The last argument to the diagnose call says this doesn't match the 10355 // GNU int-to-pointer idiom. 10356 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10357 Expr::NPC_ValueDependentIsNotNull)) { 10358 // In C++ adding zero to a null pointer is defined. 10359 Expr::EvalResult KnownVal; 10360 if (!getLangOpts().CPlusPlus || 10361 (!RHS.get()->isValueDependent() && 10362 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10363 KnownVal.Val.getInt() != 0))) { 10364 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10365 } 10366 } 10367 10368 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10369 return QualType(); 10370 10371 // Check array bounds for pointer arithemtic 10372 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10373 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10374 10375 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10376 return LHS.get()->getType(); 10377 } 10378 10379 // Handle pointer-pointer subtractions. 10380 if (const PointerType *RHSPTy 10381 = RHS.get()->getType()->getAs<PointerType>()) { 10382 QualType rpointee = RHSPTy->getPointeeType(); 10383 10384 if (getLangOpts().CPlusPlus) { 10385 // Pointee types must be the same: C++ [expr.add] 10386 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10387 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10388 } 10389 } else { 10390 // Pointee types must be compatible C99 6.5.6p3 10391 if (!Context.typesAreCompatible( 10392 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10393 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10394 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10395 return QualType(); 10396 } 10397 } 10398 10399 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10400 LHS.get(), RHS.get())) 10401 return QualType(); 10402 10403 // FIXME: Add warnings for nullptr - ptr. 10404 10405 // The pointee type may have zero size. As an extension, a structure or 10406 // union may have zero size or an array may have zero length. In this 10407 // case subtraction does not make sense. 10408 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10409 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10410 if (ElementSize.isZero()) { 10411 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10412 << rpointee.getUnqualifiedType() 10413 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10414 } 10415 } 10416 10417 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10418 return Context.getPointerDiffType(); 10419 } 10420 } 10421 10422 return InvalidOperands(Loc, LHS, RHS); 10423 } 10424 10425 static bool isScopedEnumerationType(QualType T) { 10426 if (const EnumType *ET = T->getAs<EnumType>()) 10427 return ET->getDecl()->isScoped(); 10428 return false; 10429 } 10430 10431 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10432 SourceLocation Loc, BinaryOperatorKind Opc, 10433 QualType LHSType) { 10434 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10435 // so skip remaining warnings as we don't want to modify values within Sema. 10436 if (S.getLangOpts().OpenCL) 10437 return; 10438 10439 // Check right/shifter operand 10440 Expr::EvalResult RHSResult; 10441 if (RHS.get()->isValueDependent() || 10442 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10443 return; 10444 llvm::APSInt Right = RHSResult.Val.getInt(); 10445 10446 if (Right.isNegative()) { 10447 S.DiagRuntimeBehavior(Loc, RHS.get(), 10448 S.PDiag(diag::warn_shift_negative) 10449 << RHS.get()->getSourceRange()); 10450 return; 10451 } 10452 10453 QualType LHSExprType = LHS.get()->getType(); 10454 uint64_t LeftSize = LHSExprType->isExtIntType() 10455 ? S.Context.getIntWidth(LHSExprType) 10456 : S.Context.getTypeSize(LHSExprType); 10457 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10458 if (Right.uge(LeftBits)) { 10459 S.DiagRuntimeBehavior(Loc, RHS.get(), 10460 S.PDiag(diag::warn_shift_gt_typewidth) 10461 << RHS.get()->getSourceRange()); 10462 return; 10463 } 10464 10465 if (Opc != BO_Shl) 10466 return; 10467 10468 // When left shifting an ICE which is signed, we can check for overflow which 10469 // according to C++ standards prior to C++2a has undefined behavior 10470 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10471 // more than the maximum value representable in the result type, so never 10472 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10473 // expression is still probably a bug.) 10474 Expr::EvalResult LHSResult; 10475 if (LHS.get()->isValueDependent() || 10476 LHSType->hasUnsignedIntegerRepresentation() || 10477 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10478 return; 10479 llvm::APSInt Left = LHSResult.Val.getInt(); 10480 10481 // If LHS does not have a signed type and non-negative value 10482 // then, the behavior is undefined before C++2a. Warn about it. 10483 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10484 !S.getLangOpts().CPlusPlus20) { 10485 S.DiagRuntimeBehavior(Loc, LHS.get(), 10486 S.PDiag(diag::warn_shift_lhs_negative) 10487 << LHS.get()->getSourceRange()); 10488 return; 10489 } 10490 10491 llvm::APInt ResultBits = 10492 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10493 if (LeftBits.uge(ResultBits)) 10494 return; 10495 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10496 Result = Result.shl(Right); 10497 10498 // Print the bit representation of the signed integer as an unsigned 10499 // hexadecimal number. 10500 SmallString<40> HexResult; 10501 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10502 10503 // If we are only missing a sign bit, this is less likely to result in actual 10504 // bugs -- if the result is cast back to an unsigned type, it will have the 10505 // expected value. Thus we place this behind a different warning that can be 10506 // turned off separately if needed. 10507 if (LeftBits == ResultBits - 1) { 10508 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10509 << HexResult << LHSType 10510 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10511 return; 10512 } 10513 10514 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10515 << HexResult.str() << Result.getMinSignedBits() << LHSType 10516 << Left.getBitWidth() << LHS.get()->getSourceRange() 10517 << RHS.get()->getSourceRange(); 10518 } 10519 10520 /// Return the resulting type when a vector is shifted 10521 /// by a scalar or vector shift amount. 10522 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10523 SourceLocation Loc, bool IsCompAssign) { 10524 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10525 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10526 !LHS.get()->getType()->isVectorType()) { 10527 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10528 << RHS.get()->getType() << LHS.get()->getType() 10529 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10530 return QualType(); 10531 } 10532 10533 if (!IsCompAssign) { 10534 LHS = S.UsualUnaryConversions(LHS.get()); 10535 if (LHS.isInvalid()) return QualType(); 10536 } 10537 10538 RHS = S.UsualUnaryConversions(RHS.get()); 10539 if (RHS.isInvalid()) return QualType(); 10540 10541 QualType LHSType = LHS.get()->getType(); 10542 // Note that LHS might be a scalar because the routine calls not only in 10543 // OpenCL case. 10544 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10545 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10546 10547 // Note that RHS might not be a vector. 10548 QualType RHSType = RHS.get()->getType(); 10549 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10550 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10551 10552 // The operands need to be integers. 10553 if (!LHSEleType->isIntegerType()) { 10554 S.Diag(Loc, diag::err_typecheck_expect_int) 10555 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10556 return QualType(); 10557 } 10558 10559 if (!RHSEleType->isIntegerType()) { 10560 S.Diag(Loc, diag::err_typecheck_expect_int) 10561 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10562 return QualType(); 10563 } 10564 10565 if (!LHSVecTy) { 10566 assert(RHSVecTy); 10567 if (IsCompAssign) 10568 return RHSType; 10569 if (LHSEleType != RHSEleType) { 10570 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10571 LHSEleType = RHSEleType; 10572 } 10573 QualType VecTy = 10574 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10575 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10576 LHSType = VecTy; 10577 } else if (RHSVecTy) { 10578 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10579 // are applied component-wise. So if RHS is a vector, then ensure 10580 // that the number of elements is the same as LHS... 10581 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10582 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10583 << LHS.get()->getType() << RHS.get()->getType() 10584 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10585 return QualType(); 10586 } 10587 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10588 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10589 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10590 if (LHSBT != RHSBT && 10591 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10592 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10593 << LHS.get()->getType() << RHS.get()->getType() 10594 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10595 } 10596 } 10597 } else { 10598 // ...else expand RHS to match the number of elements in LHS. 10599 QualType VecTy = 10600 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10601 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10602 } 10603 10604 return LHSType; 10605 } 10606 10607 // C99 6.5.7 10608 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10609 SourceLocation Loc, BinaryOperatorKind Opc, 10610 bool IsCompAssign) { 10611 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10612 10613 // Vector shifts promote their scalar inputs to vector type. 10614 if (LHS.get()->getType()->isVectorType() || 10615 RHS.get()->getType()->isVectorType()) { 10616 if (LangOpts.ZVector) { 10617 // The shift operators for the z vector extensions work basically 10618 // like general shifts, except that neither the LHS nor the RHS is 10619 // allowed to be a "vector bool". 10620 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 10621 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 10622 return InvalidOperands(Loc, LHS, RHS); 10623 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10624 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10625 return InvalidOperands(Loc, LHS, RHS); 10626 } 10627 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10628 } 10629 10630 // Shifts don't perform usual arithmetic conversions, they just do integer 10631 // promotions on each operand. C99 6.5.7p3 10632 10633 // For the LHS, do usual unary conversions, but then reset them away 10634 // if this is a compound assignment. 10635 ExprResult OldLHS = LHS; 10636 LHS = UsualUnaryConversions(LHS.get()); 10637 if (LHS.isInvalid()) 10638 return QualType(); 10639 QualType LHSType = LHS.get()->getType(); 10640 if (IsCompAssign) LHS = OldLHS; 10641 10642 // The RHS is simpler. 10643 RHS = UsualUnaryConversions(RHS.get()); 10644 if (RHS.isInvalid()) 10645 return QualType(); 10646 QualType RHSType = RHS.get()->getType(); 10647 10648 // C99 6.5.7p2: Each of the operands shall have integer type. 10649 if (!LHSType->hasIntegerRepresentation() || 10650 !RHSType->hasIntegerRepresentation()) 10651 return InvalidOperands(Loc, LHS, RHS); 10652 10653 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10654 // hasIntegerRepresentation() above instead of this. 10655 if (isScopedEnumerationType(LHSType) || 10656 isScopedEnumerationType(RHSType)) { 10657 return InvalidOperands(Loc, LHS, RHS); 10658 } 10659 // Sanity-check shift operands 10660 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10661 10662 // "The type of the result is that of the promoted left operand." 10663 return LHSType; 10664 } 10665 10666 /// Diagnose bad pointer comparisons. 10667 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10668 ExprResult &LHS, ExprResult &RHS, 10669 bool IsError) { 10670 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10671 : diag::ext_typecheck_comparison_of_distinct_pointers) 10672 << LHS.get()->getType() << RHS.get()->getType() 10673 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10674 } 10675 10676 /// Returns false if the pointers are converted to a composite type, 10677 /// true otherwise. 10678 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10679 ExprResult &LHS, ExprResult &RHS) { 10680 // C++ [expr.rel]p2: 10681 // [...] Pointer conversions (4.10) and qualification 10682 // conversions (4.4) are performed on pointer operands (or on 10683 // a pointer operand and a null pointer constant) to bring 10684 // them to their composite pointer type. [...] 10685 // 10686 // C++ [expr.eq]p1 uses the same notion for (in)equality 10687 // comparisons of pointers. 10688 10689 QualType LHSType = LHS.get()->getType(); 10690 QualType RHSType = RHS.get()->getType(); 10691 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10692 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10693 10694 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10695 if (T.isNull()) { 10696 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10697 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10698 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10699 else 10700 S.InvalidOperands(Loc, LHS, RHS); 10701 return true; 10702 } 10703 10704 return false; 10705 } 10706 10707 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10708 ExprResult &LHS, 10709 ExprResult &RHS, 10710 bool IsError) { 10711 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10712 : diag::ext_typecheck_comparison_of_fptr_to_void) 10713 << LHS.get()->getType() << RHS.get()->getType() 10714 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10715 } 10716 10717 static bool isObjCObjectLiteral(ExprResult &E) { 10718 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10719 case Stmt::ObjCArrayLiteralClass: 10720 case Stmt::ObjCDictionaryLiteralClass: 10721 case Stmt::ObjCStringLiteralClass: 10722 case Stmt::ObjCBoxedExprClass: 10723 return true; 10724 default: 10725 // Note that ObjCBoolLiteral is NOT an object literal! 10726 return false; 10727 } 10728 } 10729 10730 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10731 const ObjCObjectPointerType *Type = 10732 LHS->getType()->getAs<ObjCObjectPointerType>(); 10733 10734 // If this is not actually an Objective-C object, bail out. 10735 if (!Type) 10736 return false; 10737 10738 // Get the LHS object's interface type. 10739 QualType InterfaceType = Type->getPointeeType(); 10740 10741 // If the RHS isn't an Objective-C object, bail out. 10742 if (!RHS->getType()->isObjCObjectPointerType()) 10743 return false; 10744 10745 // Try to find the -isEqual: method. 10746 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10747 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10748 InterfaceType, 10749 /*IsInstance=*/true); 10750 if (!Method) { 10751 if (Type->isObjCIdType()) { 10752 // For 'id', just check the global pool. 10753 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10754 /*receiverId=*/true); 10755 } else { 10756 // Check protocols. 10757 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10758 /*IsInstance=*/true); 10759 } 10760 } 10761 10762 if (!Method) 10763 return false; 10764 10765 QualType T = Method->parameters()[0]->getType(); 10766 if (!T->isObjCObjectPointerType()) 10767 return false; 10768 10769 QualType R = Method->getReturnType(); 10770 if (!R->isScalarType()) 10771 return false; 10772 10773 return true; 10774 } 10775 10776 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10777 FromE = FromE->IgnoreParenImpCasts(); 10778 switch (FromE->getStmtClass()) { 10779 default: 10780 break; 10781 case Stmt::ObjCStringLiteralClass: 10782 // "string literal" 10783 return LK_String; 10784 case Stmt::ObjCArrayLiteralClass: 10785 // "array literal" 10786 return LK_Array; 10787 case Stmt::ObjCDictionaryLiteralClass: 10788 // "dictionary literal" 10789 return LK_Dictionary; 10790 case Stmt::BlockExprClass: 10791 return LK_Block; 10792 case Stmt::ObjCBoxedExprClass: { 10793 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10794 switch (Inner->getStmtClass()) { 10795 case Stmt::IntegerLiteralClass: 10796 case Stmt::FloatingLiteralClass: 10797 case Stmt::CharacterLiteralClass: 10798 case Stmt::ObjCBoolLiteralExprClass: 10799 case Stmt::CXXBoolLiteralExprClass: 10800 // "numeric literal" 10801 return LK_Numeric; 10802 case Stmt::ImplicitCastExprClass: { 10803 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10804 // Boolean literals can be represented by implicit casts. 10805 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10806 return LK_Numeric; 10807 break; 10808 } 10809 default: 10810 break; 10811 } 10812 return LK_Boxed; 10813 } 10814 } 10815 return LK_None; 10816 } 10817 10818 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 10819 ExprResult &LHS, ExprResult &RHS, 10820 BinaryOperator::Opcode Opc){ 10821 Expr *Literal; 10822 Expr *Other; 10823 if (isObjCObjectLiteral(LHS)) { 10824 Literal = LHS.get(); 10825 Other = RHS.get(); 10826 } else { 10827 Literal = RHS.get(); 10828 Other = LHS.get(); 10829 } 10830 10831 // Don't warn on comparisons against nil. 10832 Other = Other->IgnoreParenCasts(); 10833 if (Other->isNullPointerConstant(S.getASTContext(), 10834 Expr::NPC_ValueDependentIsNotNull)) 10835 return; 10836 10837 // This should be kept in sync with warn_objc_literal_comparison. 10838 // LK_String should always be after the other literals, since it has its own 10839 // warning flag. 10840 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 10841 assert(LiteralKind != Sema::LK_Block); 10842 if (LiteralKind == Sema::LK_None) { 10843 llvm_unreachable("Unknown Objective-C object literal kind"); 10844 } 10845 10846 if (LiteralKind == Sema::LK_String) 10847 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 10848 << Literal->getSourceRange(); 10849 else 10850 S.Diag(Loc, diag::warn_objc_literal_comparison) 10851 << LiteralKind << Literal->getSourceRange(); 10852 10853 if (BinaryOperator::isEqualityOp(Opc) && 10854 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 10855 SourceLocation Start = LHS.get()->getBeginLoc(); 10856 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 10857 CharSourceRange OpRange = 10858 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 10859 10860 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 10861 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 10862 << FixItHint::CreateReplacement(OpRange, " isEqual:") 10863 << FixItHint::CreateInsertion(End, "]"); 10864 } 10865 } 10866 10867 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 10868 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 10869 ExprResult &RHS, SourceLocation Loc, 10870 BinaryOperatorKind Opc) { 10871 // Check that left hand side is !something. 10872 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 10873 if (!UO || UO->getOpcode() != UO_LNot) return; 10874 10875 // Only check if the right hand side is non-bool arithmetic type. 10876 if (RHS.get()->isKnownToHaveBooleanValue()) return; 10877 10878 // Make sure that the something in !something is not bool. 10879 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 10880 if (SubExpr->isKnownToHaveBooleanValue()) return; 10881 10882 // Emit warning. 10883 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 10884 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 10885 << Loc << IsBitwiseOp; 10886 10887 // First note suggest !(x < y) 10888 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 10889 SourceLocation FirstClose = RHS.get()->getEndLoc(); 10890 FirstClose = S.getLocForEndOfToken(FirstClose); 10891 if (FirstClose.isInvalid()) 10892 FirstOpen = SourceLocation(); 10893 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 10894 << IsBitwiseOp 10895 << FixItHint::CreateInsertion(FirstOpen, "(") 10896 << FixItHint::CreateInsertion(FirstClose, ")"); 10897 10898 // Second note suggests (!x) < y 10899 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 10900 SourceLocation SecondClose = LHS.get()->getEndLoc(); 10901 SecondClose = S.getLocForEndOfToken(SecondClose); 10902 if (SecondClose.isInvalid()) 10903 SecondOpen = SourceLocation(); 10904 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 10905 << FixItHint::CreateInsertion(SecondOpen, "(") 10906 << FixItHint::CreateInsertion(SecondClose, ")"); 10907 } 10908 10909 // Returns true if E refers to a non-weak array. 10910 static bool checkForArray(const Expr *E) { 10911 const ValueDecl *D = nullptr; 10912 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 10913 D = DR->getDecl(); 10914 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 10915 if (Mem->isImplicitAccess()) 10916 D = Mem->getMemberDecl(); 10917 } 10918 if (!D) 10919 return false; 10920 return D->getType()->isArrayType() && !D->isWeak(); 10921 } 10922 10923 /// Diagnose some forms of syntactically-obvious tautological comparison. 10924 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 10925 Expr *LHS, Expr *RHS, 10926 BinaryOperatorKind Opc) { 10927 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 10928 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 10929 10930 QualType LHSType = LHS->getType(); 10931 QualType RHSType = RHS->getType(); 10932 if (LHSType->hasFloatingRepresentation() || 10933 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 10934 S.inTemplateInstantiation()) 10935 return; 10936 10937 // Comparisons between two array types are ill-formed for operator<=>, so 10938 // we shouldn't emit any additional warnings about it. 10939 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 10940 return; 10941 10942 // For non-floating point types, check for self-comparisons of the form 10943 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10944 // often indicate logic errors in the program. 10945 // 10946 // NOTE: Don't warn about comparison expressions resulting from macro 10947 // expansion. Also don't warn about comparisons which are only self 10948 // comparisons within a template instantiation. The warnings should catch 10949 // obvious cases in the definition of the template anyways. The idea is to 10950 // warn when the typed comparison operator will always evaluate to the same 10951 // result. 10952 10953 // Used for indexing into %select in warn_comparison_always 10954 enum { 10955 AlwaysConstant, 10956 AlwaysTrue, 10957 AlwaysFalse, 10958 AlwaysEqual, // std::strong_ordering::equal from operator<=> 10959 }; 10960 10961 // C++2a [depr.array.comp]: 10962 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 10963 // operands of array type are deprecated. 10964 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 10965 RHSStripped->getType()->isArrayType()) { 10966 S.Diag(Loc, diag::warn_depr_array_comparison) 10967 << LHS->getSourceRange() << RHS->getSourceRange() 10968 << LHSStripped->getType() << RHSStripped->getType(); 10969 // Carry on to produce the tautological comparison warning, if this 10970 // expression is potentially-evaluated, we can resolve the array to a 10971 // non-weak declaration, and so on. 10972 } 10973 10974 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 10975 if (Expr::isSameComparisonOperand(LHS, RHS)) { 10976 unsigned Result; 10977 switch (Opc) { 10978 case BO_EQ: 10979 case BO_LE: 10980 case BO_GE: 10981 Result = AlwaysTrue; 10982 break; 10983 case BO_NE: 10984 case BO_LT: 10985 case BO_GT: 10986 Result = AlwaysFalse; 10987 break; 10988 case BO_Cmp: 10989 Result = AlwaysEqual; 10990 break; 10991 default: 10992 Result = AlwaysConstant; 10993 break; 10994 } 10995 S.DiagRuntimeBehavior(Loc, nullptr, 10996 S.PDiag(diag::warn_comparison_always) 10997 << 0 /*self-comparison*/ 10998 << Result); 10999 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11000 // What is it always going to evaluate to? 11001 unsigned Result; 11002 switch (Opc) { 11003 case BO_EQ: // e.g. array1 == array2 11004 Result = AlwaysFalse; 11005 break; 11006 case BO_NE: // e.g. array1 != array2 11007 Result = AlwaysTrue; 11008 break; 11009 default: // e.g. array1 <= array2 11010 // The best we can say is 'a constant' 11011 Result = AlwaysConstant; 11012 break; 11013 } 11014 S.DiagRuntimeBehavior(Loc, nullptr, 11015 S.PDiag(diag::warn_comparison_always) 11016 << 1 /*array comparison*/ 11017 << Result); 11018 } 11019 } 11020 11021 if (isa<CastExpr>(LHSStripped)) 11022 LHSStripped = LHSStripped->IgnoreParenCasts(); 11023 if (isa<CastExpr>(RHSStripped)) 11024 RHSStripped = RHSStripped->IgnoreParenCasts(); 11025 11026 // Warn about comparisons against a string constant (unless the other 11027 // operand is null); the user probably wants string comparison function. 11028 Expr *LiteralString = nullptr; 11029 Expr *LiteralStringStripped = nullptr; 11030 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11031 !RHSStripped->isNullPointerConstant(S.Context, 11032 Expr::NPC_ValueDependentIsNull)) { 11033 LiteralString = LHS; 11034 LiteralStringStripped = LHSStripped; 11035 } else if ((isa<StringLiteral>(RHSStripped) || 11036 isa<ObjCEncodeExpr>(RHSStripped)) && 11037 !LHSStripped->isNullPointerConstant(S.Context, 11038 Expr::NPC_ValueDependentIsNull)) { 11039 LiteralString = RHS; 11040 LiteralStringStripped = RHSStripped; 11041 } 11042 11043 if (LiteralString) { 11044 S.DiagRuntimeBehavior(Loc, nullptr, 11045 S.PDiag(diag::warn_stringcompare) 11046 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11047 << LiteralString->getSourceRange()); 11048 } 11049 } 11050 11051 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11052 switch (CK) { 11053 default: { 11054 #ifndef NDEBUG 11055 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11056 << "\n"; 11057 #endif 11058 llvm_unreachable("unhandled cast kind"); 11059 } 11060 case CK_UserDefinedConversion: 11061 return ICK_Identity; 11062 case CK_LValueToRValue: 11063 return ICK_Lvalue_To_Rvalue; 11064 case CK_ArrayToPointerDecay: 11065 return ICK_Array_To_Pointer; 11066 case CK_FunctionToPointerDecay: 11067 return ICK_Function_To_Pointer; 11068 case CK_IntegralCast: 11069 return ICK_Integral_Conversion; 11070 case CK_FloatingCast: 11071 return ICK_Floating_Conversion; 11072 case CK_IntegralToFloating: 11073 case CK_FloatingToIntegral: 11074 return ICK_Floating_Integral; 11075 case CK_IntegralComplexCast: 11076 case CK_FloatingComplexCast: 11077 case CK_FloatingComplexToIntegralComplex: 11078 case CK_IntegralComplexToFloatingComplex: 11079 return ICK_Complex_Conversion; 11080 case CK_FloatingComplexToReal: 11081 case CK_FloatingRealToComplex: 11082 case CK_IntegralComplexToReal: 11083 case CK_IntegralRealToComplex: 11084 return ICK_Complex_Real; 11085 } 11086 } 11087 11088 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11089 QualType FromType, 11090 SourceLocation Loc) { 11091 // Check for a narrowing implicit conversion. 11092 StandardConversionSequence SCS; 11093 SCS.setAsIdentityConversion(); 11094 SCS.setToType(0, FromType); 11095 SCS.setToType(1, ToType); 11096 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11097 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11098 11099 APValue PreNarrowingValue; 11100 QualType PreNarrowingType; 11101 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11102 PreNarrowingType, 11103 /*IgnoreFloatToIntegralConversion*/ true)) { 11104 case NK_Dependent_Narrowing: 11105 // Implicit conversion to a narrower type, but the expression is 11106 // value-dependent so we can't tell whether it's actually narrowing. 11107 case NK_Not_Narrowing: 11108 return false; 11109 11110 case NK_Constant_Narrowing: 11111 // Implicit conversion to a narrower type, and the value is not a constant 11112 // expression. 11113 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11114 << /*Constant*/ 1 11115 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11116 return true; 11117 11118 case NK_Variable_Narrowing: 11119 // Implicit conversion to a narrower type, and the value is not a constant 11120 // expression. 11121 case NK_Type_Narrowing: 11122 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11123 << /*Constant*/ 0 << FromType << ToType; 11124 // TODO: It's not a constant expression, but what if the user intended it 11125 // to be? Can we produce notes to help them figure out why it isn't? 11126 return true; 11127 } 11128 llvm_unreachable("unhandled case in switch"); 11129 } 11130 11131 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11132 ExprResult &LHS, 11133 ExprResult &RHS, 11134 SourceLocation Loc) { 11135 QualType LHSType = LHS.get()->getType(); 11136 QualType RHSType = RHS.get()->getType(); 11137 // Dig out the original argument type and expression before implicit casts 11138 // were applied. These are the types/expressions we need to check the 11139 // [expr.spaceship] requirements against. 11140 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11141 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11142 QualType LHSStrippedType = LHSStripped.get()->getType(); 11143 QualType RHSStrippedType = RHSStripped.get()->getType(); 11144 11145 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11146 // other is not, the program is ill-formed. 11147 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11148 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11149 return QualType(); 11150 } 11151 11152 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11153 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11154 RHSStrippedType->isEnumeralType(); 11155 if (NumEnumArgs == 1) { 11156 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11157 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11158 if (OtherTy->hasFloatingRepresentation()) { 11159 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11160 return QualType(); 11161 } 11162 } 11163 if (NumEnumArgs == 2) { 11164 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11165 // type E, the operator yields the result of converting the operands 11166 // to the underlying type of E and applying <=> to the converted operands. 11167 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11168 S.InvalidOperands(Loc, LHS, RHS); 11169 return QualType(); 11170 } 11171 QualType IntType = 11172 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11173 assert(IntType->isArithmeticType()); 11174 11175 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11176 // promote the boolean type, and all other promotable integer types, to 11177 // avoid this. 11178 if (IntType->isPromotableIntegerType()) 11179 IntType = S.Context.getPromotedIntegerType(IntType); 11180 11181 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11182 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11183 LHSType = RHSType = IntType; 11184 } 11185 11186 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11187 // usual arithmetic conversions are applied to the operands. 11188 QualType Type = 11189 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11190 if (LHS.isInvalid() || RHS.isInvalid()) 11191 return QualType(); 11192 if (Type.isNull()) 11193 return S.InvalidOperands(Loc, LHS, RHS); 11194 11195 Optional<ComparisonCategoryType> CCT = 11196 getComparisonCategoryForBuiltinCmp(Type); 11197 if (!CCT) 11198 return S.InvalidOperands(Loc, LHS, RHS); 11199 11200 bool HasNarrowing = checkThreeWayNarrowingConversion( 11201 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11202 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11203 RHS.get()->getBeginLoc()); 11204 if (HasNarrowing) 11205 return QualType(); 11206 11207 assert(!Type.isNull() && "composite type for <=> has not been set"); 11208 11209 return S.CheckComparisonCategoryType( 11210 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11211 } 11212 11213 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11214 ExprResult &RHS, 11215 SourceLocation Loc, 11216 BinaryOperatorKind Opc) { 11217 if (Opc == BO_Cmp) 11218 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11219 11220 // C99 6.5.8p3 / C99 6.5.9p4 11221 QualType Type = 11222 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11223 if (LHS.isInvalid() || RHS.isInvalid()) 11224 return QualType(); 11225 if (Type.isNull()) 11226 return S.InvalidOperands(Loc, LHS, RHS); 11227 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11228 11229 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11230 return S.InvalidOperands(Loc, LHS, RHS); 11231 11232 // Check for comparisons of floating point operands using != and ==. 11233 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11234 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11235 11236 // The result of comparisons is 'bool' in C++, 'int' in C. 11237 return S.Context.getLogicalOperationType(); 11238 } 11239 11240 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11241 if (!NullE.get()->getType()->isAnyPointerType()) 11242 return; 11243 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11244 if (!E.get()->getType()->isAnyPointerType() && 11245 E.get()->isNullPointerConstant(Context, 11246 Expr::NPC_ValueDependentIsNotNull) == 11247 Expr::NPCK_ZeroExpression) { 11248 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11249 if (CL->getValue() == 0) 11250 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11251 << NullValue 11252 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11253 NullValue ? "NULL" : "(void *)0"); 11254 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11255 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11256 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11257 if (T == Context.CharTy) 11258 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11259 << NullValue 11260 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11261 NullValue ? "NULL" : "(void *)0"); 11262 } 11263 } 11264 } 11265 11266 // C99 6.5.8, C++ [expr.rel] 11267 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11268 SourceLocation Loc, 11269 BinaryOperatorKind Opc) { 11270 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11271 bool IsThreeWay = Opc == BO_Cmp; 11272 bool IsOrdered = IsRelational || IsThreeWay; 11273 auto IsAnyPointerType = [](ExprResult E) { 11274 QualType Ty = E.get()->getType(); 11275 return Ty->isPointerType() || Ty->isMemberPointerType(); 11276 }; 11277 11278 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11279 // type, array-to-pointer, ..., conversions are performed on both operands to 11280 // bring them to their composite type. 11281 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11282 // any type-related checks. 11283 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11284 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11285 if (LHS.isInvalid()) 11286 return QualType(); 11287 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11288 if (RHS.isInvalid()) 11289 return QualType(); 11290 } else { 11291 LHS = DefaultLvalueConversion(LHS.get()); 11292 if (LHS.isInvalid()) 11293 return QualType(); 11294 RHS = DefaultLvalueConversion(RHS.get()); 11295 if (RHS.isInvalid()) 11296 return QualType(); 11297 } 11298 11299 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11300 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11301 CheckPtrComparisonWithNullChar(LHS, RHS); 11302 CheckPtrComparisonWithNullChar(RHS, LHS); 11303 } 11304 11305 // Handle vector comparisons separately. 11306 if (LHS.get()->getType()->isVectorType() || 11307 RHS.get()->getType()->isVectorType()) 11308 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11309 11310 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11311 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11312 11313 QualType LHSType = LHS.get()->getType(); 11314 QualType RHSType = RHS.get()->getType(); 11315 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11316 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11317 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11318 11319 const Expr::NullPointerConstantKind LHSNullKind = 11320 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11321 const Expr::NullPointerConstantKind RHSNullKind = 11322 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11323 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11324 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11325 11326 auto computeResultTy = [&]() { 11327 if (Opc != BO_Cmp) 11328 return Context.getLogicalOperationType(); 11329 assert(getLangOpts().CPlusPlus); 11330 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11331 11332 QualType CompositeTy = LHS.get()->getType(); 11333 assert(!CompositeTy->isReferenceType()); 11334 11335 Optional<ComparisonCategoryType> CCT = 11336 getComparisonCategoryForBuiltinCmp(CompositeTy); 11337 if (!CCT) 11338 return InvalidOperands(Loc, LHS, RHS); 11339 11340 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11341 // P0946R0: Comparisons between a null pointer constant and an object 11342 // pointer result in std::strong_equality, which is ill-formed under 11343 // P1959R0. 11344 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11345 << (LHSIsNull ? LHS.get()->getSourceRange() 11346 : RHS.get()->getSourceRange()); 11347 return QualType(); 11348 } 11349 11350 return CheckComparisonCategoryType( 11351 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11352 }; 11353 11354 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11355 bool IsEquality = Opc == BO_EQ; 11356 if (RHSIsNull) 11357 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11358 RHS.get()->getSourceRange()); 11359 else 11360 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11361 LHS.get()->getSourceRange()); 11362 } 11363 11364 if ((LHSType->isIntegerType() && !LHSIsNull) || 11365 (RHSType->isIntegerType() && !RHSIsNull)) { 11366 // Skip normal pointer conversion checks in this case; we have better 11367 // diagnostics for this below. 11368 } else if (getLangOpts().CPlusPlus) { 11369 // Equality comparison of a function pointer to a void pointer is invalid, 11370 // but we allow it as an extension. 11371 // FIXME: If we really want to allow this, should it be part of composite 11372 // pointer type computation so it works in conditionals too? 11373 if (!IsOrdered && 11374 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11375 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11376 // This is a gcc extension compatibility comparison. 11377 // In a SFINAE context, we treat this as a hard error to maintain 11378 // conformance with the C++ standard. 11379 diagnoseFunctionPointerToVoidComparison( 11380 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11381 11382 if (isSFINAEContext()) 11383 return QualType(); 11384 11385 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11386 return computeResultTy(); 11387 } 11388 11389 // C++ [expr.eq]p2: 11390 // If at least one operand is a pointer [...] bring them to their 11391 // composite pointer type. 11392 // C++ [expr.spaceship]p6 11393 // If at least one of the operands is of pointer type, [...] bring them 11394 // to their composite pointer type. 11395 // C++ [expr.rel]p2: 11396 // If both operands are pointers, [...] bring them to their composite 11397 // pointer type. 11398 // For <=>, the only valid non-pointer types are arrays and functions, and 11399 // we already decayed those, so this is really the same as the relational 11400 // comparison rule. 11401 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11402 (IsOrdered ? 2 : 1) && 11403 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11404 RHSType->isObjCObjectPointerType()))) { 11405 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11406 return QualType(); 11407 return computeResultTy(); 11408 } 11409 } else if (LHSType->isPointerType() && 11410 RHSType->isPointerType()) { // C99 6.5.8p2 11411 // All of the following pointer-related warnings are GCC extensions, except 11412 // when handling null pointer constants. 11413 QualType LCanPointeeTy = 11414 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11415 QualType RCanPointeeTy = 11416 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11417 11418 // C99 6.5.9p2 and C99 6.5.8p2 11419 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11420 RCanPointeeTy.getUnqualifiedType())) { 11421 // Valid unless a relational comparison of function pointers 11422 if (IsRelational && LCanPointeeTy->isFunctionType()) { 11423 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 11424 << LHSType << RHSType << LHS.get()->getSourceRange() 11425 << RHS.get()->getSourceRange(); 11426 } 11427 } else if (!IsRelational && 11428 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11429 // Valid unless comparison between non-null pointer and function pointer 11430 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11431 && !LHSIsNull && !RHSIsNull) 11432 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11433 /*isError*/false); 11434 } else { 11435 // Invalid 11436 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11437 } 11438 if (LCanPointeeTy != RCanPointeeTy) { 11439 // Treat NULL constant as a special case in OpenCL. 11440 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11441 const PointerType *LHSPtr = LHSType->castAs<PointerType>(); 11442 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) { 11443 Diag(Loc, 11444 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11445 << LHSType << RHSType << 0 /* comparison */ 11446 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11447 } 11448 } 11449 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11450 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11451 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11452 : CK_BitCast; 11453 if (LHSIsNull && !RHSIsNull) 11454 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11455 else 11456 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11457 } 11458 return computeResultTy(); 11459 } 11460 11461 if (getLangOpts().CPlusPlus) { 11462 // C++ [expr.eq]p4: 11463 // Two operands of type std::nullptr_t or one operand of type 11464 // std::nullptr_t and the other a null pointer constant compare equal. 11465 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11466 if (LHSType->isNullPtrType()) { 11467 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11468 return computeResultTy(); 11469 } 11470 if (RHSType->isNullPtrType()) { 11471 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11472 return computeResultTy(); 11473 } 11474 } 11475 11476 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11477 // These aren't covered by the composite pointer type rules. 11478 if (!IsOrdered && RHSType->isNullPtrType() && 11479 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11480 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11481 return computeResultTy(); 11482 } 11483 if (!IsOrdered && LHSType->isNullPtrType() && 11484 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11485 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11486 return computeResultTy(); 11487 } 11488 11489 if (IsRelational && 11490 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11491 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11492 // HACK: Relational comparison of nullptr_t against a pointer type is 11493 // invalid per DR583, but we allow it within std::less<> and friends, 11494 // since otherwise common uses of it break. 11495 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11496 // friends to have std::nullptr_t overload candidates. 11497 DeclContext *DC = CurContext; 11498 if (isa<FunctionDecl>(DC)) 11499 DC = DC->getParent(); 11500 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11501 if (CTSD->isInStdNamespace() && 11502 llvm::StringSwitch<bool>(CTSD->getName()) 11503 .Cases("less", "less_equal", "greater", "greater_equal", true) 11504 .Default(false)) { 11505 if (RHSType->isNullPtrType()) 11506 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11507 else 11508 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11509 return computeResultTy(); 11510 } 11511 } 11512 } 11513 11514 // C++ [expr.eq]p2: 11515 // If at least one operand is a pointer to member, [...] bring them to 11516 // their composite pointer type. 11517 if (!IsOrdered && 11518 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11519 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11520 return QualType(); 11521 else 11522 return computeResultTy(); 11523 } 11524 } 11525 11526 // Handle block pointer types. 11527 if (!IsOrdered && LHSType->isBlockPointerType() && 11528 RHSType->isBlockPointerType()) { 11529 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11530 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11531 11532 if (!LHSIsNull && !RHSIsNull && 11533 !Context.typesAreCompatible(lpointee, rpointee)) { 11534 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11535 << LHSType << RHSType << LHS.get()->getSourceRange() 11536 << RHS.get()->getSourceRange(); 11537 } 11538 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11539 return computeResultTy(); 11540 } 11541 11542 // Allow block pointers to be compared with null pointer constants. 11543 if (!IsOrdered 11544 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11545 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11546 if (!LHSIsNull && !RHSIsNull) { 11547 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11548 ->getPointeeType()->isVoidType()) 11549 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11550 ->getPointeeType()->isVoidType()))) 11551 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11552 << LHSType << RHSType << LHS.get()->getSourceRange() 11553 << RHS.get()->getSourceRange(); 11554 } 11555 if (LHSIsNull && !RHSIsNull) 11556 LHS = ImpCastExprToType(LHS.get(), RHSType, 11557 RHSType->isPointerType() ? CK_BitCast 11558 : CK_AnyPointerToBlockPointerCast); 11559 else 11560 RHS = ImpCastExprToType(RHS.get(), LHSType, 11561 LHSType->isPointerType() ? CK_BitCast 11562 : CK_AnyPointerToBlockPointerCast); 11563 return computeResultTy(); 11564 } 11565 11566 if (LHSType->isObjCObjectPointerType() || 11567 RHSType->isObjCObjectPointerType()) { 11568 const PointerType *LPT = LHSType->getAs<PointerType>(); 11569 const PointerType *RPT = RHSType->getAs<PointerType>(); 11570 if (LPT || RPT) { 11571 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11572 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11573 11574 if (!LPtrToVoid && !RPtrToVoid && 11575 !Context.typesAreCompatible(LHSType, RHSType)) { 11576 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11577 /*isError*/false); 11578 } 11579 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11580 // the RHS, but we have test coverage for this behavior. 11581 // FIXME: Consider using convertPointersToCompositeType in C++. 11582 if (LHSIsNull && !RHSIsNull) { 11583 Expr *E = LHS.get(); 11584 if (getLangOpts().ObjCAutoRefCount) 11585 CheckObjCConversion(SourceRange(), RHSType, E, 11586 CCK_ImplicitConversion); 11587 LHS = ImpCastExprToType(E, RHSType, 11588 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11589 } 11590 else { 11591 Expr *E = RHS.get(); 11592 if (getLangOpts().ObjCAutoRefCount) 11593 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11594 /*Diagnose=*/true, 11595 /*DiagnoseCFAudited=*/false, Opc); 11596 RHS = ImpCastExprToType(E, LHSType, 11597 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11598 } 11599 return computeResultTy(); 11600 } 11601 if (LHSType->isObjCObjectPointerType() && 11602 RHSType->isObjCObjectPointerType()) { 11603 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11604 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11605 /*isError*/false); 11606 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11607 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11608 11609 if (LHSIsNull && !RHSIsNull) 11610 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11611 else 11612 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11613 return computeResultTy(); 11614 } 11615 11616 if (!IsOrdered && LHSType->isBlockPointerType() && 11617 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11618 LHS = ImpCastExprToType(LHS.get(), RHSType, 11619 CK_BlockPointerToObjCPointerCast); 11620 return computeResultTy(); 11621 } else if (!IsOrdered && 11622 LHSType->isBlockCompatibleObjCPointerType(Context) && 11623 RHSType->isBlockPointerType()) { 11624 RHS = ImpCastExprToType(RHS.get(), LHSType, 11625 CK_BlockPointerToObjCPointerCast); 11626 return computeResultTy(); 11627 } 11628 } 11629 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11630 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11631 unsigned DiagID = 0; 11632 bool isError = false; 11633 if (LangOpts.DebuggerSupport) { 11634 // Under a debugger, allow the comparison of pointers to integers, 11635 // since users tend to want to compare addresses. 11636 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11637 (RHSIsNull && RHSType->isIntegerType())) { 11638 if (IsOrdered) { 11639 isError = getLangOpts().CPlusPlus; 11640 DiagID = 11641 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11642 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11643 } 11644 } else if (getLangOpts().CPlusPlus) { 11645 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11646 isError = true; 11647 } else if (IsOrdered) 11648 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11649 else 11650 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11651 11652 if (DiagID) { 11653 Diag(Loc, DiagID) 11654 << LHSType << RHSType << LHS.get()->getSourceRange() 11655 << RHS.get()->getSourceRange(); 11656 if (isError) 11657 return QualType(); 11658 } 11659 11660 if (LHSType->isIntegerType()) 11661 LHS = ImpCastExprToType(LHS.get(), RHSType, 11662 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11663 else 11664 RHS = ImpCastExprToType(RHS.get(), LHSType, 11665 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11666 return computeResultTy(); 11667 } 11668 11669 // Handle block pointers. 11670 if (!IsOrdered && RHSIsNull 11671 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11672 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11673 return computeResultTy(); 11674 } 11675 if (!IsOrdered && LHSIsNull 11676 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11677 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11678 return computeResultTy(); 11679 } 11680 11681 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11682 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11683 return computeResultTy(); 11684 } 11685 11686 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11687 return computeResultTy(); 11688 } 11689 11690 if (LHSIsNull && RHSType->isQueueT()) { 11691 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11692 return computeResultTy(); 11693 } 11694 11695 if (LHSType->isQueueT() && RHSIsNull) { 11696 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11697 return computeResultTy(); 11698 } 11699 } 11700 11701 return InvalidOperands(Loc, LHS, RHS); 11702 } 11703 11704 // Return a signed ext_vector_type that is of identical size and number of 11705 // elements. For floating point vectors, return an integer type of identical 11706 // size and number of elements. In the non ext_vector_type case, search from 11707 // the largest type to the smallest type to avoid cases where long long == long, 11708 // where long gets picked over long long. 11709 QualType Sema::GetSignedVectorType(QualType V) { 11710 const VectorType *VTy = V->castAs<VectorType>(); 11711 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11712 11713 if (isa<ExtVectorType>(VTy)) { 11714 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11715 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11716 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11717 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11718 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11719 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11720 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11721 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11722 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11723 "Unhandled vector element size in vector compare"); 11724 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11725 } 11726 11727 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11728 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11729 VectorType::GenericVector); 11730 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11731 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11732 VectorType::GenericVector); 11733 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11734 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11735 VectorType::GenericVector); 11736 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11737 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11738 VectorType::GenericVector); 11739 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11740 "Unhandled vector element size in vector compare"); 11741 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11742 VectorType::GenericVector); 11743 } 11744 11745 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11746 /// operates on extended vector types. Instead of producing an IntTy result, 11747 /// like a scalar comparison, a vector comparison produces a vector of integer 11748 /// types. 11749 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11750 SourceLocation Loc, 11751 BinaryOperatorKind Opc) { 11752 if (Opc == BO_Cmp) { 11753 Diag(Loc, diag::err_three_way_vector_comparison); 11754 return QualType(); 11755 } 11756 11757 // Check to make sure we're operating on vectors of the same type and width, 11758 // Allowing one side to be a scalar of element type. 11759 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11760 /*AllowBothBool*/true, 11761 /*AllowBoolConversions*/getLangOpts().ZVector); 11762 if (vType.isNull()) 11763 return vType; 11764 11765 QualType LHSType = LHS.get()->getType(); 11766 11767 // If AltiVec, the comparison results in a numeric type, i.e. 11768 // bool for C++, int for C 11769 if (getLangOpts().AltiVec && 11770 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11771 return Context.getLogicalOperationType(); 11772 11773 // For non-floating point types, check for self-comparisons of the form 11774 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11775 // often indicate logic errors in the program. 11776 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11777 11778 // Check for comparisons of floating point operands using != and ==. 11779 if (BinaryOperator::isEqualityOp(Opc) && 11780 LHSType->hasFloatingRepresentation()) { 11781 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11782 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11783 } 11784 11785 // Return a signed type for the vector. 11786 return GetSignedVectorType(vType); 11787 } 11788 11789 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11790 const ExprResult &XorRHS, 11791 const SourceLocation Loc) { 11792 // Do not diagnose macros. 11793 if (Loc.isMacroID()) 11794 return; 11795 11796 bool Negative = false; 11797 bool ExplicitPlus = false; 11798 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11799 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11800 11801 if (!LHSInt) 11802 return; 11803 if (!RHSInt) { 11804 // Check negative literals. 11805 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 11806 UnaryOperatorKind Opc = UO->getOpcode(); 11807 if (Opc != UO_Minus && Opc != UO_Plus) 11808 return; 11809 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11810 if (!RHSInt) 11811 return; 11812 Negative = (Opc == UO_Minus); 11813 ExplicitPlus = !Negative; 11814 } else { 11815 return; 11816 } 11817 } 11818 11819 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 11820 llvm::APInt RightSideValue = RHSInt->getValue(); 11821 if (LeftSideValue != 2 && LeftSideValue != 10) 11822 return; 11823 11824 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 11825 return; 11826 11827 CharSourceRange ExprRange = CharSourceRange::getCharRange( 11828 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 11829 llvm::StringRef ExprStr = 11830 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 11831 11832 CharSourceRange XorRange = 11833 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11834 llvm::StringRef XorStr = 11835 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 11836 // Do not diagnose if xor keyword/macro is used. 11837 if (XorStr == "xor") 11838 return; 11839 11840 std::string LHSStr = std::string(Lexer::getSourceText( 11841 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 11842 S.getSourceManager(), S.getLangOpts())); 11843 std::string RHSStr = std::string(Lexer::getSourceText( 11844 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 11845 S.getSourceManager(), S.getLangOpts())); 11846 11847 if (Negative) { 11848 RightSideValue = -RightSideValue; 11849 RHSStr = "-" + RHSStr; 11850 } else if (ExplicitPlus) { 11851 RHSStr = "+" + RHSStr; 11852 } 11853 11854 StringRef LHSStrRef = LHSStr; 11855 StringRef RHSStrRef = RHSStr; 11856 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 11857 // literals. 11858 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 11859 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 11860 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 11861 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 11862 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 11863 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 11864 LHSStrRef.find('\'') != StringRef::npos || 11865 RHSStrRef.find('\'') != StringRef::npos) 11866 return; 11867 11868 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 11869 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 11870 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 11871 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 11872 std::string SuggestedExpr = "1 << " + RHSStr; 11873 bool Overflow = false; 11874 llvm::APInt One = (LeftSideValue - 1); 11875 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 11876 if (Overflow) { 11877 if (RightSideIntValue < 64) 11878 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11879 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 11880 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 11881 else if (RightSideIntValue == 64) 11882 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 11883 else 11884 return; 11885 } else { 11886 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 11887 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 11888 << PowValue.toString(10, true) 11889 << FixItHint::CreateReplacement( 11890 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 11891 } 11892 11893 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 11894 } else if (LeftSideValue == 10) { 11895 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 11896 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11897 << ExprStr << XorValue.toString(10, true) << SuggestedValue 11898 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 11899 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 11900 } 11901 } 11902 11903 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11904 SourceLocation Loc) { 11905 // Ensure that either both operands are of the same vector type, or 11906 // one operand is of a vector type and the other is of its element type. 11907 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 11908 /*AllowBothBool*/true, 11909 /*AllowBoolConversions*/false); 11910 if (vType.isNull()) 11911 return InvalidOperands(Loc, LHS, RHS); 11912 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 11913 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 11914 return InvalidOperands(Loc, LHS, RHS); 11915 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 11916 // usage of the logical operators && and || with vectors in C. This 11917 // check could be notionally dropped. 11918 if (!getLangOpts().CPlusPlus && 11919 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 11920 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 11921 11922 return GetSignedVectorType(LHS.get()->getType()); 11923 } 11924 11925 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 11926 SourceLocation Loc, 11927 BinaryOperatorKind Opc) { 11928 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11929 11930 bool IsCompAssign = 11931 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 11932 11933 if (LHS.get()->getType()->isVectorType() || 11934 RHS.get()->getType()->isVectorType()) { 11935 if (LHS.get()->getType()->hasIntegerRepresentation() && 11936 RHS.get()->getType()->hasIntegerRepresentation()) 11937 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 11938 /*AllowBothBool*/true, 11939 /*AllowBoolConversions*/getLangOpts().ZVector); 11940 return InvalidOperands(Loc, LHS, RHS); 11941 } 11942 11943 if (Opc == BO_And) 11944 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11945 11946 if (LHS.get()->getType()->hasFloatingRepresentation() || 11947 RHS.get()->getType()->hasFloatingRepresentation()) 11948 return InvalidOperands(Loc, LHS, RHS); 11949 11950 ExprResult LHSResult = LHS, RHSResult = RHS; 11951 QualType compType = UsualArithmeticConversions( 11952 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 11953 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 11954 return QualType(); 11955 LHS = LHSResult.get(); 11956 RHS = RHSResult.get(); 11957 11958 if (Opc == BO_Xor) 11959 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 11960 11961 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 11962 return compType; 11963 return InvalidOperands(Loc, LHS, RHS); 11964 } 11965 11966 // C99 6.5.[13,14] 11967 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11968 SourceLocation Loc, 11969 BinaryOperatorKind Opc) { 11970 // Check vector operands differently. 11971 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 11972 return CheckVectorLogicalOperands(LHS, RHS, Loc); 11973 11974 bool EnumConstantInBoolContext = false; 11975 for (const ExprResult &HS : {LHS, RHS}) { 11976 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 11977 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 11978 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 11979 EnumConstantInBoolContext = true; 11980 } 11981 } 11982 11983 if (EnumConstantInBoolContext) 11984 Diag(Loc, diag::warn_enum_constant_in_bool_context); 11985 11986 // Diagnose cases where the user write a logical and/or but probably meant a 11987 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 11988 // is a constant. 11989 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 11990 !LHS.get()->getType()->isBooleanType() && 11991 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 11992 // Don't warn in macros or template instantiations. 11993 !Loc.isMacroID() && !inTemplateInstantiation()) { 11994 // If the RHS can be constant folded, and if it constant folds to something 11995 // that isn't 0 or 1 (which indicate a potential logical operation that 11996 // happened to fold to true/false) then warn. 11997 // Parens on the RHS are ignored. 11998 Expr::EvalResult EVResult; 11999 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12000 llvm::APSInt Result = EVResult.Val.getInt(); 12001 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12002 !RHS.get()->getExprLoc().isMacroID()) || 12003 (Result != 0 && Result != 1)) { 12004 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12005 << RHS.get()->getSourceRange() 12006 << (Opc == BO_LAnd ? "&&" : "||"); 12007 // Suggest replacing the logical operator with the bitwise version 12008 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12009 << (Opc == BO_LAnd ? "&" : "|") 12010 << FixItHint::CreateReplacement(SourceRange( 12011 Loc, getLocForEndOfToken(Loc)), 12012 Opc == BO_LAnd ? "&" : "|"); 12013 if (Opc == BO_LAnd) 12014 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12015 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12016 << FixItHint::CreateRemoval( 12017 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12018 RHS.get()->getEndLoc())); 12019 } 12020 } 12021 } 12022 12023 if (!Context.getLangOpts().CPlusPlus) { 12024 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12025 // not operate on the built-in scalar and vector float types. 12026 if (Context.getLangOpts().OpenCL && 12027 Context.getLangOpts().OpenCLVersion < 120) { 12028 if (LHS.get()->getType()->isFloatingType() || 12029 RHS.get()->getType()->isFloatingType()) 12030 return InvalidOperands(Loc, LHS, RHS); 12031 } 12032 12033 LHS = UsualUnaryConversions(LHS.get()); 12034 if (LHS.isInvalid()) 12035 return QualType(); 12036 12037 RHS = UsualUnaryConversions(RHS.get()); 12038 if (RHS.isInvalid()) 12039 return QualType(); 12040 12041 if (!LHS.get()->getType()->isScalarType() || 12042 !RHS.get()->getType()->isScalarType()) 12043 return InvalidOperands(Loc, LHS, RHS); 12044 12045 return Context.IntTy; 12046 } 12047 12048 // The following is safe because we only use this method for 12049 // non-overloadable operands. 12050 12051 // C++ [expr.log.and]p1 12052 // C++ [expr.log.or]p1 12053 // The operands are both contextually converted to type bool. 12054 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12055 if (LHSRes.isInvalid()) 12056 return InvalidOperands(Loc, LHS, RHS); 12057 LHS = LHSRes; 12058 12059 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12060 if (RHSRes.isInvalid()) 12061 return InvalidOperands(Loc, LHS, RHS); 12062 RHS = RHSRes; 12063 12064 // C++ [expr.log.and]p2 12065 // C++ [expr.log.or]p2 12066 // The result is a bool. 12067 return Context.BoolTy; 12068 } 12069 12070 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12071 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12072 if (!ME) return false; 12073 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12074 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12075 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12076 if (!Base) return false; 12077 return Base->getMethodDecl() != nullptr; 12078 } 12079 12080 /// Is the given expression (which must be 'const') a reference to a 12081 /// variable which was originally non-const, but which has become 12082 /// 'const' due to being captured within a block? 12083 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12084 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12085 assert(E->isLValue() && E->getType().isConstQualified()); 12086 E = E->IgnoreParens(); 12087 12088 // Must be a reference to a declaration from an enclosing scope. 12089 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12090 if (!DRE) return NCCK_None; 12091 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12092 12093 // The declaration must be a variable which is not declared 'const'. 12094 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12095 if (!var) return NCCK_None; 12096 if (var->getType().isConstQualified()) return NCCK_None; 12097 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12098 12099 // Decide whether the first capture was for a block or a lambda. 12100 DeclContext *DC = S.CurContext, *Prev = nullptr; 12101 // Decide whether the first capture was for a block or a lambda. 12102 while (DC) { 12103 // For init-capture, it is possible that the variable belongs to the 12104 // template pattern of the current context. 12105 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12106 if (var->isInitCapture() && 12107 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12108 break; 12109 if (DC == var->getDeclContext()) 12110 break; 12111 Prev = DC; 12112 DC = DC->getParent(); 12113 } 12114 // Unless we have an init-capture, we've gone one step too far. 12115 if (!var->isInitCapture()) 12116 DC = Prev; 12117 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12118 } 12119 12120 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12121 Ty = Ty.getNonReferenceType(); 12122 if (IsDereference && Ty->isPointerType()) 12123 Ty = Ty->getPointeeType(); 12124 return !Ty.isConstQualified(); 12125 } 12126 12127 // Update err_typecheck_assign_const and note_typecheck_assign_const 12128 // when this enum is changed. 12129 enum { 12130 ConstFunction, 12131 ConstVariable, 12132 ConstMember, 12133 ConstMethod, 12134 NestedConstMember, 12135 ConstUnknown, // Keep as last element 12136 }; 12137 12138 /// Emit the "read-only variable not assignable" error and print notes to give 12139 /// more information about why the variable is not assignable, such as pointing 12140 /// to the declaration of a const variable, showing that a method is const, or 12141 /// that the function is returning a const reference. 12142 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12143 SourceLocation Loc) { 12144 SourceRange ExprRange = E->getSourceRange(); 12145 12146 // Only emit one error on the first const found. All other consts will emit 12147 // a note to the error. 12148 bool DiagnosticEmitted = false; 12149 12150 // Track if the current expression is the result of a dereference, and if the 12151 // next checked expression is the result of a dereference. 12152 bool IsDereference = false; 12153 bool NextIsDereference = false; 12154 12155 // Loop to process MemberExpr chains. 12156 while (true) { 12157 IsDereference = NextIsDereference; 12158 12159 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12160 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12161 NextIsDereference = ME->isArrow(); 12162 const ValueDecl *VD = ME->getMemberDecl(); 12163 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12164 // Mutable fields can be modified even if the class is const. 12165 if (Field->isMutable()) { 12166 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12167 break; 12168 } 12169 12170 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12171 if (!DiagnosticEmitted) { 12172 S.Diag(Loc, diag::err_typecheck_assign_const) 12173 << ExprRange << ConstMember << false /*static*/ << Field 12174 << Field->getType(); 12175 DiagnosticEmitted = true; 12176 } 12177 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12178 << ConstMember << false /*static*/ << Field << Field->getType() 12179 << Field->getSourceRange(); 12180 } 12181 E = ME->getBase(); 12182 continue; 12183 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12184 if (VDecl->getType().isConstQualified()) { 12185 if (!DiagnosticEmitted) { 12186 S.Diag(Loc, diag::err_typecheck_assign_const) 12187 << ExprRange << ConstMember << true /*static*/ << VDecl 12188 << VDecl->getType(); 12189 DiagnosticEmitted = true; 12190 } 12191 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12192 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12193 << VDecl->getSourceRange(); 12194 } 12195 // Static fields do not inherit constness from parents. 12196 break; 12197 } 12198 break; // End MemberExpr 12199 } else if (const ArraySubscriptExpr *ASE = 12200 dyn_cast<ArraySubscriptExpr>(E)) { 12201 E = ASE->getBase()->IgnoreParenImpCasts(); 12202 continue; 12203 } else if (const ExtVectorElementExpr *EVE = 12204 dyn_cast<ExtVectorElementExpr>(E)) { 12205 E = EVE->getBase()->IgnoreParenImpCasts(); 12206 continue; 12207 } 12208 break; 12209 } 12210 12211 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12212 // Function calls 12213 const FunctionDecl *FD = CE->getDirectCallee(); 12214 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12215 if (!DiagnosticEmitted) { 12216 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12217 << ConstFunction << FD; 12218 DiagnosticEmitted = true; 12219 } 12220 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12221 diag::note_typecheck_assign_const) 12222 << ConstFunction << FD << FD->getReturnType() 12223 << FD->getReturnTypeSourceRange(); 12224 } 12225 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12226 // Point to variable declaration. 12227 if (const ValueDecl *VD = DRE->getDecl()) { 12228 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12229 if (!DiagnosticEmitted) { 12230 S.Diag(Loc, diag::err_typecheck_assign_const) 12231 << ExprRange << ConstVariable << VD << VD->getType(); 12232 DiagnosticEmitted = true; 12233 } 12234 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12235 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12236 } 12237 } 12238 } else if (isa<CXXThisExpr>(E)) { 12239 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12240 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12241 if (MD->isConst()) { 12242 if (!DiagnosticEmitted) { 12243 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12244 << ConstMethod << MD; 12245 DiagnosticEmitted = true; 12246 } 12247 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12248 << ConstMethod << MD << MD->getSourceRange(); 12249 } 12250 } 12251 } 12252 } 12253 12254 if (DiagnosticEmitted) 12255 return; 12256 12257 // Can't determine a more specific message, so display the generic error. 12258 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12259 } 12260 12261 enum OriginalExprKind { 12262 OEK_Variable, 12263 OEK_Member, 12264 OEK_LValue 12265 }; 12266 12267 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12268 const RecordType *Ty, 12269 SourceLocation Loc, SourceRange Range, 12270 OriginalExprKind OEK, 12271 bool &DiagnosticEmitted) { 12272 std::vector<const RecordType *> RecordTypeList; 12273 RecordTypeList.push_back(Ty); 12274 unsigned NextToCheckIndex = 0; 12275 // We walk the record hierarchy breadth-first to ensure that we print 12276 // diagnostics in field nesting order. 12277 while (RecordTypeList.size() > NextToCheckIndex) { 12278 bool IsNested = NextToCheckIndex > 0; 12279 for (const FieldDecl *Field : 12280 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12281 // First, check every field for constness. 12282 QualType FieldTy = Field->getType(); 12283 if (FieldTy.isConstQualified()) { 12284 if (!DiagnosticEmitted) { 12285 S.Diag(Loc, diag::err_typecheck_assign_const) 12286 << Range << NestedConstMember << OEK << VD 12287 << IsNested << Field; 12288 DiagnosticEmitted = true; 12289 } 12290 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12291 << NestedConstMember << IsNested << Field 12292 << FieldTy << Field->getSourceRange(); 12293 } 12294 12295 // Then we append it to the list to check next in order. 12296 FieldTy = FieldTy.getCanonicalType(); 12297 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12298 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12299 RecordTypeList.push_back(FieldRecTy); 12300 } 12301 } 12302 ++NextToCheckIndex; 12303 } 12304 } 12305 12306 /// Emit an error for the case where a record we are trying to assign to has a 12307 /// const-qualified field somewhere in its hierarchy. 12308 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12309 SourceLocation Loc) { 12310 QualType Ty = E->getType(); 12311 assert(Ty->isRecordType() && "lvalue was not record?"); 12312 SourceRange Range = E->getSourceRange(); 12313 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12314 bool DiagEmitted = false; 12315 12316 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12317 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12318 Range, OEK_Member, DiagEmitted); 12319 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12320 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12321 Range, OEK_Variable, DiagEmitted); 12322 else 12323 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12324 Range, OEK_LValue, DiagEmitted); 12325 if (!DiagEmitted) 12326 DiagnoseConstAssignment(S, E, Loc); 12327 } 12328 12329 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12330 /// emit an error and return true. If so, return false. 12331 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12332 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12333 12334 S.CheckShadowingDeclModification(E, Loc); 12335 12336 SourceLocation OrigLoc = Loc; 12337 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12338 &Loc); 12339 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12340 IsLV = Expr::MLV_InvalidMessageExpression; 12341 if (IsLV == Expr::MLV_Valid) 12342 return false; 12343 12344 unsigned DiagID = 0; 12345 bool NeedType = false; 12346 switch (IsLV) { // C99 6.5.16p2 12347 case Expr::MLV_ConstQualified: 12348 // Use a specialized diagnostic when we're assigning to an object 12349 // from an enclosing function or block. 12350 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12351 if (NCCK == NCCK_Block) 12352 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12353 else 12354 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12355 break; 12356 } 12357 12358 // In ARC, use some specialized diagnostics for occasions where we 12359 // infer 'const'. These are always pseudo-strong variables. 12360 if (S.getLangOpts().ObjCAutoRefCount) { 12361 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12362 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12363 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12364 12365 // Use the normal diagnostic if it's pseudo-__strong but the 12366 // user actually wrote 'const'. 12367 if (var->isARCPseudoStrong() && 12368 (!var->getTypeSourceInfo() || 12369 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12370 // There are three pseudo-strong cases: 12371 // - self 12372 ObjCMethodDecl *method = S.getCurMethodDecl(); 12373 if (method && var == method->getSelfDecl()) { 12374 DiagID = method->isClassMethod() 12375 ? diag::err_typecheck_arc_assign_self_class_method 12376 : diag::err_typecheck_arc_assign_self; 12377 12378 // - Objective-C externally_retained attribute. 12379 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12380 isa<ParmVarDecl>(var)) { 12381 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12382 12383 // - fast enumeration variables 12384 } else { 12385 DiagID = diag::err_typecheck_arr_assign_enumeration; 12386 } 12387 12388 SourceRange Assign; 12389 if (Loc != OrigLoc) 12390 Assign = SourceRange(OrigLoc, OrigLoc); 12391 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12392 // We need to preserve the AST regardless, so migration tool 12393 // can do its job. 12394 return false; 12395 } 12396 } 12397 } 12398 12399 // If none of the special cases above are triggered, then this is a 12400 // simple const assignment. 12401 if (DiagID == 0) { 12402 DiagnoseConstAssignment(S, E, Loc); 12403 return true; 12404 } 12405 12406 break; 12407 case Expr::MLV_ConstAddrSpace: 12408 DiagnoseConstAssignment(S, E, Loc); 12409 return true; 12410 case Expr::MLV_ConstQualifiedField: 12411 DiagnoseRecursiveConstFields(S, E, Loc); 12412 return true; 12413 case Expr::MLV_ArrayType: 12414 case Expr::MLV_ArrayTemporary: 12415 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12416 NeedType = true; 12417 break; 12418 case Expr::MLV_NotObjectType: 12419 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12420 NeedType = true; 12421 break; 12422 case Expr::MLV_LValueCast: 12423 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12424 break; 12425 case Expr::MLV_Valid: 12426 llvm_unreachable("did not take early return for MLV_Valid"); 12427 case Expr::MLV_InvalidExpression: 12428 case Expr::MLV_MemberFunction: 12429 case Expr::MLV_ClassTemporary: 12430 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12431 break; 12432 case Expr::MLV_IncompleteType: 12433 case Expr::MLV_IncompleteVoidType: 12434 return S.RequireCompleteType(Loc, E->getType(), 12435 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12436 case Expr::MLV_DuplicateVectorComponents: 12437 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12438 break; 12439 case Expr::MLV_NoSetterProperty: 12440 llvm_unreachable("readonly properties should be processed differently"); 12441 case Expr::MLV_InvalidMessageExpression: 12442 DiagID = diag::err_readonly_message_assignment; 12443 break; 12444 case Expr::MLV_SubObjCPropertySetting: 12445 DiagID = diag::err_no_subobject_property_setting; 12446 break; 12447 } 12448 12449 SourceRange Assign; 12450 if (Loc != OrigLoc) 12451 Assign = SourceRange(OrigLoc, OrigLoc); 12452 if (NeedType) 12453 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 12454 else 12455 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12456 return true; 12457 } 12458 12459 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 12460 SourceLocation Loc, 12461 Sema &Sema) { 12462 if (Sema.inTemplateInstantiation()) 12463 return; 12464 if (Sema.isUnevaluatedContext()) 12465 return; 12466 if (Loc.isInvalid() || Loc.isMacroID()) 12467 return; 12468 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 12469 return; 12470 12471 // C / C++ fields 12472 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 12473 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 12474 if (ML && MR) { 12475 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 12476 return; 12477 const ValueDecl *LHSDecl = 12478 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 12479 const ValueDecl *RHSDecl = 12480 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 12481 if (LHSDecl != RHSDecl) 12482 return; 12483 if (LHSDecl->getType().isVolatileQualified()) 12484 return; 12485 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12486 if (RefTy->getPointeeType().isVolatileQualified()) 12487 return; 12488 12489 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 12490 } 12491 12492 // Objective-C instance variables 12493 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 12494 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 12495 if (OL && OR && OL->getDecl() == OR->getDecl()) { 12496 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 12497 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 12498 if (RL && RR && RL->getDecl() == RR->getDecl()) 12499 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 12500 } 12501 } 12502 12503 // C99 6.5.16.1 12504 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 12505 SourceLocation Loc, 12506 QualType CompoundType) { 12507 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 12508 12509 // Verify that LHS is a modifiable lvalue, and emit error if not. 12510 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12511 return QualType(); 12512 12513 QualType LHSType = LHSExpr->getType(); 12514 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12515 CompoundType; 12516 // OpenCL v1.2 s6.1.1.1 p2: 12517 // The half data type can only be used to declare a pointer to a buffer that 12518 // contains half values 12519 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 12520 LHSType->isHalfType()) { 12521 Diag(Loc, diag::err_opencl_half_load_store) << 1 12522 << LHSType.getUnqualifiedType(); 12523 return QualType(); 12524 } 12525 12526 AssignConvertType ConvTy; 12527 if (CompoundType.isNull()) { 12528 Expr *RHSCheck = RHS.get(); 12529 12530 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 12531 12532 QualType LHSTy(LHSType); 12533 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 12534 if (RHS.isInvalid()) 12535 return QualType(); 12536 // Special case of NSObject attributes on c-style pointer types. 12537 if (ConvTy == IncompatiblePointer && 12538 ((Context.isObjCNSObjectType(LHSType) && 12539 RHSType->isObjCObjectPointerType()) || 12540 (Context.isObjCNSObjectType(RHSType) && 12541 LHSType->isObjCObjectPointerType()))) 12542 ConvTy = Compatible; 12543 12544 if (ConvTy == Compatible && 12545 LHSType->isObjCObjectType()) 12546 Diag(Loc, diag::err_objc_object_assignment) 12547 << LHSType; 12548 12549 // If the RHS is a unary plus or minus, check to see if they = and + are 12550 // right next to each other. If so, the user may have typo'd "x =+ 4" 12551 // instead of "x += 4". 12552 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 12553 RHSCheck = ICE->getSubExpr(); 12554 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 12555 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 12556 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 12557 // Only if the two operators are exactly adjacent. 12558 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 12559 // And there is a space or other character before the subexpr of the 12560 // unary +/-. We don't want to warn on "x=-1". 12561 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 12562 UO->getSubExpr()->getBeginLoc().isFileID()) { 12563 Diag(Loc, diag::warn_not_compound_assign) 12564 << (UO->getOpcode() == UO_Plus ? "+" : "-") 12565 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 12566 } 12567 } 12568 12569 if (ConvTy == Compatible) { 12570 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 12571 // Warn about retain cycles where a block captures the LHS, but 12572 // not if the LHS is a simple variable into which the block is 12573 // being stored...unless that variable can be captured by reference! 12574 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 12575 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 12576 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 12577 checkRetainCycles(LHSExpr, RHS.get()); 12578 } 12579 12580 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 12581 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 12582 // It is safe to assign a weak reference into a strong variable. 12583 // Although this code can still have problems: 12584 // id x = self.weakProp; 12585 // id y = self.weakProp; 12586 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12587 // paths through the function. This should be revisited if 12588 // -Wrepeated-use-of-weak is made flow-sensitive. 12589 // For ObjCWeak only, we do not warn if the assign is to a non-weak 12590 // variable, which will be valid for the current autorelease scope. 12591 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12592 RHS.get()->getBeginLoc())) 12593 getCurFunction()->markSafeWeakUse(RHS.get()); 12594 12595 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 12596 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 12597 } 12598 } 12599 } else { 12600 // Compound assignment "x += y" 12601 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 12602 } 12603 12604 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 12605 RHS.get(), AA_Assigning)) 12606 return QualType(); 12607 12608 CheckForNullPointerDereference(*this, LHSExpr); 12609 12610 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 12611 if (CompoundType.isNull()) { 12612 // C++2a [expr.ass]p5: 12613 // A simple-assignment whose left operand is of a volatile-qualified 12614 // type is deprecated unless the assignment is either a discarded-value 12615 // expression or an unevaluated operand 12616 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 12617 } else { 12618 // C++2a [expr.ass]p6: 12619 // [Compound-assignment] expressions are deprecated if E1 has 12620 // volatile-qualified type 12621 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 12622 } 12623 } 12624 12625 // C99 6.5.16p3: The type of an assignment expression is the type of the 12626 // left operand unless the left operand has qualified type, in which case 12627 // it is the unqualified version of the type of the left operand. 12628 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 12629 // is converted to the type of the assignment expression (above). 12630 // C++ 5.17p1: the type of the assignment expression is that of its left 12631 // operand. 12632 return (getLangOpts().CPlusPlus 12633 ? LHSType : LHSType.getUnqualifiedType()); 12634 } 12635 12636 // Only ignore explicit casts to void. 12637 static bool IgnoreCommaOperand(const Expr *E) { 12638 E = E->IgnoreParens(); 12639 12640 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 12641 if (CE->getCastKind() == CK_ToVoid) { 12642 return true; 12643 } 12644 12645 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 12646 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 12647 CE->getSubExpr()->getType()->isDependentType()) { 12648 return true; 12649 } 12650 } 12651 12652 return false; 12653 } 12654 12655 // Look for instances where it is likely the comma operator is confused with 12656 // another operator. There is a whitelist of acceptable expressions for the 12657 // left hand side of the comma operator, otherwise emit a warning. 12658 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 12659 // No warnings in macros 12660 if (Loc.isMacroID()) 12661 return; 12662 12663 // Don't warn in template instantiations. 12664 if (inTemplateInstantiation()) 12665 return; 12666 12667 // Scope isn't fine-grained enough to whitelist the specific cases, so 12668 // instead, skip more than needed, then call back into here with the 12669 // CommaVisitor in SemaStmt.cpp. 12670 // The whitelisted locations are the initialization and increment portions 12671 // of a for loop. The additional checks are on the condition of 12672 // if statements, do/while loops, and for loops. 12673 // Differences in scope flags for C89 mode requires the extra logic. 12674 const unsigned ForIncrementFlags = 12675 getLangOpts().C99 || getLangOpts().CPlusPlus 12676 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 12677 : Scope::ContinueScope | Scope::BreakScope; 12678 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 12679 const unsigned ScopeFlags = getCurScope()->getFlags(); 12680 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 12681 (ScopeFlags & ForInitFlags) == ForInitFlags) 12682 return; 12683 12684 // If there are multiple comma operators used together, get the RHS of the 12685 // of the comma operator as the LHS. 12686 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 12687 if (BO->getOpcode() != BO_Comma) 12688 break; 12689 LHS = BO->getRHS(); 12690 } 12691 12692 // Only allow some expressions on LHS to not warn. 12693 if (IgnoreCommaOperand(LHS)) 12694 return; 12695 12696 Diag(Loc, diag::warn_comma_operator); 12697 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 12698 << LHS->getSourceRange() 12699 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 12700 LangOpts.CPlusPlus ? "static_cast<void>(" 12701 : "(void)(") 12702 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 12703 ")"); 12704 } 12705 12706 // C99 6.5.17 12707 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 12708 SourceLocation Loc) { 12709 LHS = S.CheckPlaceholderExpr(LHS.get()); 12710 RHS = S.CheckPlaceholderExpr(RHS.get()); 12711 if (LHS.isInvalid() || RHS.isInvalid()) 12712 return QualType(); 12713 12714 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 12715 // operands, but not unary promotions. 12716 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 12717 12718 // So we treat the LHS as a ignored value, and in C++ we allow the 12719 // containing site to determine what should be done with the RHS. 12720 LHS = S.IgnoredValueConversions(LHS.get()); 12721 if (LHS.isInvalid()) 12722 return QualType(); 12723 12724 S.DiagnoseUnusedExprResult(LHS.get()); 12725 12726 if (!S.getLangOpts().CPlusPlus) { 12727 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12728 if (RHS.isInvalid()) 12729 return QualType(); 12730 if (!RHS.get()->getType()->isVoidType()) 12731 S.RequireCompleteType(Loc, RHS.get()->getType(), 12732 diag::err_incomplete_type); 12733 } 12734 12735 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 12736 S.DiagnoseCommaOperator(LHS.get(), Loc); 12737 12738 return RHS.get()->getType(); 12739 } 12740 12741 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 12742 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 12743 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 12744 ExprValueKind &VK, 12745 ExprObjectKind &OK, 12746 SourceLocation OpLoc, 12747 bool IsInc, bool IsPrefix) { 12748 if (Op->isTypeDependent()) 12749 return S.Context.DependentTy; 12750 12751 QualType ResType = Op->getType(); 12752 // Atomic types can be used for increment / decrement where the non-atomic 12753 // versions can, so ignore the _Atomic() specifier for the purpose of 12754 // checking. 12755 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 12756 ResType = ResAtomicType->getValueType(); 12757 12758 assert(!ResType.isNull() && "no type for increment/decrement expression"); 12759 12760 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 12761 // Decrement of bool is not allowed. 12762 if (!IsInc) { 12763 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 12764 return QualType(); 12765 } 12766 // Increment of bool sets it to true, but is deprecated. 12767 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 12768 : diag::warn_increment_bool) 12769 << Op->getSourceRange(); 12770 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 12771 // Error on enum increments and decrements in C++ mode 12772 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 12773 return QualType(); 12774 } else if (ResType->isRealType()) { 12775 // OK! 12776 } else if (ResType->isPointerType()) { 12777 // C99 6.5.2.4p2, 6.5.6p2 12778 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 12779 return QualType(); 12780 } else if (ResType->isObjCObjectPointerType()) { 12781 // On modern runtimes, ObjC pointer arithmetic is forbidden. 12782 // Otherwise, we just need a complete type. 12783 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 12784 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 12785 return QualType(); 12786 } else if (ResType->isAnyComplexType()) { 12787 // C99 does not support ++/-- on complex types, we allow as an extension. 12788 S.Diag(OpLoc, diag::ext_integer_increment_complex) 12789 << ResType << Op->getSourceRange(); 12790 } else if (ResType->isPlaceholderType()) { 12791 ExprResult PR = S.CheckPlaceholderExpr(Op); 12792 if (PR.isInvalid()) return QualType(); 12793 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 12794 IsInc, IsPrefix); 12795 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 12796 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 12797 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 12798 (ResType->castAs<VectorType>()->getVectorKind() != 12799 VectorType::AltiVecBool)) { 12800 // The z vector extensions allow ++ and -- for non-bool vectors. 12801 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 12802 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 12803 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 12804 } else { 12805 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 12806 << ResType << int(IsInc) << Op->getSourceRange(); 12807 return QualType(); 12808 } 12809 // At this point, we know we have a real, complex or pointer type. 12810 // Now make sure the operand is a modifiable lvalue. 12811 if (CheckForModifiableLvalue(Op, OpLoc, S)) 12812 return QualType(); 12813 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 12814 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 12815 // An operand with volatile-qualified type is deprecated 12816 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 12817 << IsInc << ResType; 12818 } 12819 // In C++, a prefix increment is the same type as the operand. Otherwise 12820 // (in C or with postfix), the increment is the unqualified type of the 12821 // operand. 12822 if (IsPrefix && S.getLangOpts().CPlusPlus) { 12823 VK = VK_LValue; 12824 OK = Op->getObjectKind(); 12825 return ResType; 12826 } else { 12827 VK = VK_RValue; 12828 return ResType.getUnqualifiedType(); 12829 } 12830 } 12831 12832 12833 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 12834 /// This routine allows us to typecheck complex/recursive expressions 12835 /// where the declaration is needed for type checking. We only need to 12836 /// handle cases when the expression references a function designator 12837 /// or is an lvalue. Here are some examples: 12838 /// - &(x) => x 12839 /// - &*****f => f for f a function designator. 12840 /// - &s.xx => s 12841 /// - &s.zz[1].yy -> s, if zz is an array 12842 /// - *(x + 1) -> x, if x is an array 12843 /// - &"123"[2] -> 0 12844 /// - & __real__ x -> x 12845 /// 12846 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 12847 /// members. 12848 static ValueDecl *getPrimaryDecl(Expr *E) { 12849 switch (E->getStmtClass()) { 12850 case Stmt::DeclRefExprClass: 12851 return cast<DeclRefExpr>(E)->getDecl(); 12852 case Stmt::MemberExprClass: 12853 // If this is an arrow operator, the address is an offset from 12854 // the base's value, so the object the base refers to is 12855 // irrelevant. 12856 if (cast<MemberExpr>(E)->isArrow()) 12857 return nullptr; 12858 // Otherwise, the expression refers to a part of the base 12859 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 12860 case Stmt::ArraySubscriptExprClass: { 12861 // FIXME: This code shouldn't be necessary! We should catch the implicit 12862 // promotion of register arrays earlier. 12863 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 12864 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 12865 if (ICE->getSubExpr()->getType()->isArrayType()) 12866 return getPrimaryDecl(ICE->getSubExpr()); 12867 } 12868 return nullptr; 12869 } 12870 case Stmt::UnaryOperatorClass: { 12871 UnaryOperator *UO = cast<UnaryOperator>(E); 12872 12873 switch(UO->getOpcode()) { 12874 case UO_Real: 12875 case UO_Imag: 12876 case UO_Extension: 12877 return getPrimaryDecl(UO->getSubExpr()); 12878 default: 12879 return nullptr; 12880 } 12881 } 12882 case Stmt::ParenExprClass: 12883 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 12884 case Stmt::ImplicitCastExprClass: 12885 // If the result of an implicit cast is an l-value, we care about 12886 // the sub-expression; otherwise, the result here doesn't matter. 12887 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 12888 case Stmt::CXXUuidofExprClass: 12889 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 12890 default: 12891 return nullptr; 12892 } 12893 } 12894 12895 namespace { 12896 enum { 12897 AO_Bit_Field = 0, 12898 AO_Vector_Element = 1, 12899 AO_Property_Expansion = 2, 12900 AO_Register_Variable = 3, 12901 AO_No_Error = 4 12902 }; 12903 } 12904 /// Diagnose invalid operand for address of operations. 12905 /// 12906 /// \param Type The type of operand which cannot have its address taken. 12907 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 12908 Expr *E, unsigned Type) { 12909 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 12910 } 12911 12912 /// CheckAddressOfOperand - The operand of & must be either a function 12913 /// designator or an lvalue designating an object. If it is an lvalue, the 12914 /// object cannot be declared with storage class register or be a bit field. 12915 /// Note: The usual conversions are *not* applied to the operand of the & 12916 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 12917 /// In C++, the operand might be an overloaded function name, in which case 12918 /// we allow the '&' but retain the overloaded-function type. 12919 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 12920 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 12921 if (PTy->getKind() == BuiltinType::Overload) { 12922 Expr *E = OrigOp.get()->IgnoreParens(); 12923 if (!isa<OverloadExpr>(E)) { 12924 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 12925 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 12926 << OrigOp.get()->getSourceRange(); 12927 return QualType(); 12928 } 12929 12930 OverloadExpr *Ovl = cast<OverloadExpr>(E); 12931 if (isa<UnresolvedMemberExpr>(Ovl)) 12932 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 12933 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12934 << OrigOp.get()->getSourceRange(); 12935 return QualType(); 12936 } 12937 12938 return Context.OverloadTy; 12939 } 12940 12941 if (PTy->getKind() == BuiltinType::UnknownAny) 12942 return Context.UnknownAnyTy; 12943 12944 if (PTy->getKind() == BuiltinType::BoundMember) { 12945 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12946 << OrigOp.get()->getSourceRange(); 12947 return QualType(); 12948 } 12949 12950 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 12951 if (OrigOp.isInvalid()) return QualType(); 12952 } 12953 12954 if (OrigOp.get()->isTypeDependent()) 12955 return Context.DependentTy; 12956 12957 assert(!OrigOp.get()->getType()->isPlaceholderType()); 12958 12959 // Make sure to ignore parentheses in subsequent checks 12960 Expr *op = OrigOp.get()->IgnoreParens(); 12961 12962 // In OpenCL captures for blocks called as lambda functions 12963 // are located in the private address space. Blocks used in 12964 // enqueue_kernel can be located in a different address space 12965 // depending on a vendor implementation. Thus preventing 12966 // taking an address of the capture to avoid invalid AS casts. 12967 if (LangOpts.OpenCL) { 12968 auto* VarRef = dyn_cast<DeclRefExpr>(op); 12969 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 12970 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 12971 return QualType(); 12972 } 12973 } 12974 12975 if (getLangOpts().C99) { 12976 // Implement C99-only parts of addressof rules. 12977 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 12978 if (uOp->getOpcode() == UO_Deref) 12979 // Per C99 6.5.3.2, the address of a deref always returns a valid result 12980 // (assuming the deref expression is valid). 12981 return uOp->getSubExpr()->getType(); 12982 } 12983 // Technically, there should be a check for array subscript 12984 // expressions here, but the result of one is always an lvalue anyway. 12985 } 12986 ValueDecl *dcl = getPrimaryDecl(op); 12987 12988 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 12989 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12990 op->getBeginLoc())) 12991 return QualType(); 12992 12993 Expr::LValueClassification lval = op->ClassifyLValue(Context); 12994 unsigned AddressOfError = AO_No_Error; 12995 12996 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 12997 bool sfinae = (bool)isSFINAEContext(); 12998 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 12999 : diag::ext_typecheck_addrof_temporary) 13000 << op->getType() << op->getSourceRange(); 13001 if (sfinae) 13002 return QualType(); 13003 // Materialize the temporary as an lvalue so that we can take its address. 13004 OrigOp = op = 13005 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13006 } else if (isa<ObjCSelectorExpr>(op)) { 13007 return Context.getPointerType(op->getType()); 13008 } else if (lval == Expr::LV_MemberFunction) { 13009 // If it's an instance method, make a member pointer. 13010 // The expression must have exactly the form &A::foo. 13011 13012 // If the underlying expression isn't a decl ref, give up. 13013 if (!isa<DeclRefExpr>(op)) { 13014 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13015 << OrigOp.get()->getSourceRange(); 13016 return QualType(); 13017 } 13018 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13019 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13020 13021 // The id-expression was parenthesized. 13022 if (OrigOp.get() != DRE) { 13023 Diag(OpLoc, diag::err_parens_pointer_member_function) 13024 << OrigOp.get()->getSourceRange(); 13025 13026 // The method was named without a qualifier. 13027 } else if (!DRE->getQualifier()) { 13028 if (MD->getParent()->getName().empty()) 13029 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13030 << op->getSourceRange(); 13031 else { 13032 SmallString<32> Str; 13033 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13034 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13035 << op->getSourceRange() 13036 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13037 } 13038 } 13039 13040 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13041 if (isa<CXXDestructorDecl>(MD)) 13042 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13043 13044 QualType MPTy = Context.getMemberPointerType( 13045 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13046 // Under the MS ABI, lock down the inheritance model now. 13047 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13048 (void)isCompleteType(OpLoc, MPTy); 13049 return MPTy; 13050 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13051 // C99 6.5.3.2p1 13052 // The operand must be either an l-value or a function designator 13053 if (!op->getType()->isFunctionType()) { 13054 // Use a special diagnostic for loads from property references. 13055 if (isa<PseudoObjectExpr>(op)) { 13056 AddressOfError = AO_Property_Expansion; 13057 } else { 13058 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13059 << op->getType() << op->getSourceRange(); 13060 return QualType(); 13061 } 13062 } 13063 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13064 // The operand cannot be a bit-field 13065 AddressOfError = AO_Bit_Field; 13066 } else if (op->getObjectKind() == OK_VectorComponent) { 13067 // The operand cannot be an element of a vector 13068 AddressOfError = AO_Vector_Element; 13069 } else if (dcl) { // C99 6.5.3.2p1 13070 // We have an lvalue with a decl. Make sure the decl is not declared 13071 // with the register storage-class specifier. 13072 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13073 // in C++ it is not error to take address of a register 13074 // variable (c++03 7.1.1P3) 13075 if (vd->getStorageClass() == SC_Register && 13076 !getLangOpts().CPlusPlus) { 13077 AddressOfError = AO_Register_Variable; 13078 } 13079 } else if (isa<MSPropertyDecl>(dcl)) { 13080 AddressOfError = AO_Property_Expansion; 13081 } else if (isa<FunctionTemplateDecl>(dcl)) { 13082 return Context.OverloadTy; 13083 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13084 // Okay: we can take the address of a field. 13085 // Could be a pointer to member, though, if there is an explicit 13086 // scope qualifier for the class. 13087 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13088 DeclContext *Ctx = dcl->getDeclContext(); 13089 if (Ctx && Ctx->isRecord()) { 13090 if (dcl->getType()->isReferenceType()) { 13091 Diag(OpLoc, 13092 diag::err_cannot_form_pointer_to_member_of_reference_type) 13093 << dcl->getDeclName() << dcl->getType(); 13094 return QualType(); 13095 } 13096 13097 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13098 Ctx = Ctx->getParent(); 13099 13100 QualType MPTy = Context.getMemberPointerType( 13101 op->getType(), 13102 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13103 // Under the MS ABI, lock down the inheritance model now. 13104 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13105 (void)isCompleteType(OpLoc, MPTy); 13106 return MPTy; 13107 } 13108 } 13109 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13110 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13111 llvm_unreachable("Unknown/unexpected decl type"); 13112 } 13113 13114 if (AddressOfError != AO_No_Error) { 13115 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13116 return QualType(); 13117 } 13118 13119 if (lval == Expr::LV_IncompleteVoidType) { 13120 // Taking the address of a void variable is technically illegal, but we 13121 // allow it in cases which are otherwise valid. 13122 // Example: "extern void x; void* y = &x;". 13123 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13124 } 13125 13126 // If the operand has type "type", the result has type "pointer to type". 13127 if (op->getType()->isObjCObjectType()) 13128 return Context.getObjCObjectPointerType(op->getType()); 13129 13130 CheckAddressOfPackedMember(op); 13131 13132 return Context.getPointerType(op->getType()); 13133 } 13134 13135 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13136 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13137 if (!DRE) 13138 return; 13139 const Decl *D = DRE->getDecl(); 13140 if (!D) 13141 return; 13142 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13143 if (!Param) 13144 return; 13145 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13146 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13147 return; 13148 if (FunctionScopeInfo *FD = S.getCurFunction()) 13149 if (!FD->ModifiedNonNullParams.count(Param)) 13150 FD->ModifiedNonNullParams.insert(Param); 13151 } 13152 13153 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13154 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13155 SourceLocation OpLoc) { 13156 if (Op->isTypeDependent()) 13157 return S.Context.DependentTy; 13158 13159 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13160 if (ConvResult.isInvalid()) 13161 return QualType(); 13162 Op = ConvResult.get(); 13163 QualType OpTy = Op->getType(); 13164 QualType Result; 13165 13166 if (isa<CXXReinterpretCastExpr>(Op)) { 13167 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13168 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13169 Op->getSourceRange()); 13170 } 13171 13172 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13173 { 13174 Result = PT->getPointeeType(); 13175 } 13176 else if (const ObjCObjectPointerType *OPT = 13177 OpTy->getAs<ObjCObjectPointerType>()) 13178 Result = OPT->getPointeeType(); 13179 else { 13180 ExprResult PR = S.CheckPlaceholderExpr(Op); 13181 if (PR.isInvalid()) return QualType(); 13182 if (PR.get() != Op) 13183 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13184 } 13185 13186 if (Result.isNull()) { 13187 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13188 << OpTy << Op->getSourceRange(); 13189 return QualType(); 13190 } 13191 13192 // Note that per both C89 and C99, indirection is always legal, even if Result 13193 // is an incomplete type or void. It would be possible to warn about 13194 // dereferencing a void pointer, but it's completely well-defined, and such a 13195 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13196 // for pointers to 'void' but is fine for any other pointer type: 13197 // 13198 // C++ [expr.unary.op]p1: 13199 // [...] the expression to which [the unary * operator] is applied shall 13200 // be a pointer to an object type, or a pointer to a function type 13201 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13202 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13203 << OpTy << Op->getSourceRange(); 13204 13205 // Dereferences are usually l-values... 13206 VK = VK_LValue; 13207 13208 // ...except that certain expressions are never l-values in C. 13209 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13210 VK = VK_RValue; 13211 13212 return Result; 13213 } 13214 13215 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13216 BinaryOperatorKind Opc; 13217 switch (Kind) { 13218 default: llvm_unreachable("Unknown binop!"); 13219 case tok::periodstar: Opc = BO_PtrMemD; break; 13220 case tok::arrowstar: Opc = BO_PtrMemI; break; 13221 case tok::star: Opc = BO_Mul; break; 13222 case tok::slash: Opc = BO_Div; break; 13223 case tok::percent: Opc = BO_Rem; break; 13224 case tok::plus: Opc = BO_Add; break; 13225 case tok::minus: Opc = BO_Sub; break; 13226 case tok::lessless: Opc = BO_Shl; break; 13227 case tok::greatergreater: Opc = BO_Shr; break; 13228 case tok::lessequal: Opc = BO_LE; break; 13229 case tok::less: Opc = BO_LT; break; 13230 case tok::greaterequal: Opc = BO_GE; break; 13231 case tok::greater: Opc = BO_GT; break; 13232 case tok::exclaimequal: Opc = BO_NE; break; 13233 case tok::equalequal: Opc = BO_EQ; break; 13234 case tok::spaceship: Opc = BO_Cmp; break; 13235 case tok::amp: Opc = BO_And; break; 13236 case tok::caret: Opc = BO_Xor; break; 13237 case tok::pipe: Opc = BO_Or; break; 13238 case tok::ampamp: Opc = BO_LAnd; break; 13239 case tok::pipepipe: Opc = BO_LOr; break; 13240 case tok::equal: Opc = BO_Assign; break; 13241 case tok::starequal: Opc = BO_MulAssign; break; 13242 case tok::slashequal: Opc = BO_DivAssign; break; 13243 case tok::percentequal: Opc = BO_RemAssign; break; 13244 case tok::plusequal: Opc = BO_AddAssign; break; 13245 case tok::minusequal: Opc = BO_SubAssign; break; 13246 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13247 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13248 case tok::ampequal: Opc = BO_AndAssign; break; 13249 case tok::caretequal: Opc = BO_XorAssign; break; 13250 case tok::pipeequal: Opc = BO_OrAssign; break; 13251 case tok::comma: Opc = BO_Comma; break; 13252 } 13253 return Opc; 13254 } 13255 13256 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13257 tok::TokenKind Kind) { 13258 UnaryOperatorKind Opc; 13259 switch (Kind) { 13260 default: llvm_unreachable("Unknown unary op!"); 13261 case tok::plusplus: Opc = UO_PreInc; break; 13262 case tok::minusminus: Opc = UO_PreDec; break; 13263 case tok::amp: Opc = UO_AddrOf; break; 13264 case tok::star: Opc = UO_Deref; break; 13265 case tok::plus: Opc = UO_Plus; break; 13266 case tok::minus: Opc = UO_Minus; break; 13267 case tok::tilde: Opc = UO_Not; break; 13268 case tok::exclaim: Opc = UO_LNot; break; 13269 case tok::kw___real: Opc = UO_Real; break; 13270 case tok::kw___imag: Opc = UO_Imag; break; 13271 case tok::kw___extension__: Opc = UO_Extension; break; 13272 } 13273 return Opc; 13274 } 13275 13276 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13277 /// This warning suppressed in the event of macro expansions. 13278 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13279 SourceLocation OpLoc, bool IsBuiltin) { 13280 if (S.inTemplateInstantiation()) 13281 return; 13282 if (S.isUnevaluatedContext()) 13283 return; 13284 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13285 return; 13286 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13287 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13288 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13289 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13290 if (!LHSDeclRef || !RHSDeclRef || 13291 LHSDeclRef->getLocation().isMacroID() || 13292 RHSDeclRef->getLocation().isMacroID()) 13293 return; 13294 const ValueDecl *LHSDecl = 13295 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13296 const ValueDecl *RHSDecl = 13297 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13298 if (LHSDecl != RHSDecl) 13299 return; 13300 if (LHSDecl->getType().isVolatileQualified()) 13301 return; 13302 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13303 if (RefTy->getPointeeType().isVolatileQualified()) 13304 return; 13305 13306 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13307 : diag::warn_self_assignment_overloaded) 13308 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13309 << RHSExpr->getSourceRange(); 13310 } 13311 13312 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13313 /// is usually indicative of introspection within the Objective-C pointer. 13314 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13315 SourceLocation OpLoc) { 13316 if (!S.getLangOpts().ObjC) 13317 return; 13318 13319 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13320 const Expr *LHS = L.get(); 13321 const Expr *RHS = R.get(); 13322 13323 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13324 ObjCPointerExpr = LHS; 13325 OtherExpr = RHS; 13326 } 13327 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13328 ObjCPointerExpr = RHS; 13329 OtherExpr = LHS; 13330 } 13331 13332 // This warning is deliberately made very specific to reduce false 13333 // positives with logic that uses '&' for hashing. This logic mainly 13334 // looks for code trying to introspect into tagged pointers, which 13335 // code should generally never do. 13336 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13337 unsigned Diag = diag::warn_objc_pointer_masking; 13338 // Determine if we are introspecting the result of performSelectorXXX. 13339 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13340 // Special case messages to -performSelector and friends, which 13341 // can return non-pointer values boxed in a pointer value. 13342 // Some clients may wish to silence warnings in this subcase. 13343 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13344 Selector S = ME->getSelector(); 13345 StringRef SelArg0 = S.getNameForSlot(0); 13346 if (SelArg0.startswith("performSelector")) 13347 Diag = diag::warn_objc_pointer_masking_performSelector; 13348 } 13349 13350 S.Diag(OpLoc, Diag) 13351 << ObjCPointerExpr->getSourceRange(); 13352 } 13353 } 13354 13355 static NamedDecl *getDeclFromExpr(Expr *E) { 13356 if (!E) 13357 return nullptr; 13358 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13359 return DRE->getDecl(); 13360 if (auto *ME = dyn_cast<MemberExpr>(E)) 13361 return ME->getMemberDecl(); 13362 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13363 return IRE->getDecl(); 13364 return nullptr; 13365 } 13366 13367 // This helper function promotes a binary operator's operands (which are of a 13368 // half vector type) to a vector of floats and then truncates the result to 13369 // a vector of either half or short. 13370 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13371 BinaryOperatorKind Opc, QualType ResultTy, 13372 ExprValueKind VK, ExprObjectKind OK, 13373 bool IsCompAssign, SourceLocation OpLoc, 13374 FPOptions FPFeatures) { 13375 auto &Context = S.getASTContext(); 13376 assert((isVector(ResultTy, Context.HalfTy) || 13377 isVector(ResultTy, Context.ShortTy)) && 13378 "Result must be a vector of half or short"); 13379 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13380 isVector(RHS.get()->getType(), Context.HalfTy) && 13381 "both operands expected to be a half vector"); 13382 13383 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13384 QualType BinOpResTy = RHS.get()->getType(); 13385 13386 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13387 // change BinOpResTy to a vector of ints. 13388 if (isVector(ResultTy, Context.ShortTy)) 13389 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13390 13391 if (IsCompAssign) 13392 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13393 ResultTy, VK, OK, OpLoc, FPFeatures, 13394 BinOpResTy, BinOpResTy); 13395 13396 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13397 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13398 BinOpResTy, VK, OK, OpLoc, FPFeatures); 13399 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13400 } 13401 13402 static std::pair<ExprResult, ExprResult> 13403 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13404 Expr *RHSExpr) { 13405 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13406 if (!S.getLangOpts().CPlusPlus) { 13407 // C cannot handle TypoExpr nodes on either side of a binop because it 13408 // doesn't handle dependent types properly, so make sure any TypoExprs have 13409 // been dealt with before checking the operands. 13410 LHS = S.CorrectDelayedTyposInExpr(LHS); 13411 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 13412 if (Opc != BO_Assign) 13413 return ExprResult(E); 13414 // Avoid correcting the RHS to the same Expr as the LHS. 13415 Decl *D = getDeclFromExpr(E); 13416 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13417 }); 13418 } 13419 return std::make_pair(LHS, RHS); 13420 } 13421 13422 /// Returns true if conversion between vectors of halfs and vectors of floats 13423 /// is needed. 13424 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13425 Expr *E0, Expr *E1 = nullptr) { 13426 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13427 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13428 return false; 13429 13430 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13431 QualType Ty = E->IgnoreImplicit()->getType(); 13432 13433 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13434 // to vectors of floats. Although the element type of the vectors is __fp16, 13435 // the vectors shouldn't be treated as storage-only types. See the 13436 // discussion here: https://reviews.llvm.org/rG825235c140e7 13437 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13438 if (VT->getVectorKind() == VectorType::NeonVector) 13439 return false; 13440 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13441 } 13442 return false; 13443 }; 13444 13445 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13446 } 13447 13448 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 13449 /// operator @p Opc at location @c TokLoc. This routine only supports 13450 /// built-in operations; ActOnBinOp handles overloaded operators. 13451 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 13452 BinaryOperatorKind Opc, 13453 Expr *LHSExpr, Expr *RHSExpr) { 13454 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 13455 // The syntax only allows initializer lists on the RHS of assignment, 13456 // so we don't need to worry about accepting invalid code for 13457 // non-assignment operators. 13458 // C++11 5.17p9: 13459 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 13460 // of x = {} is x = T(). 13461 InitializationKind Kind = InitializationKind::CreateDirectList( 13462 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13463 InitializedEntity Entity = 13464 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 13465 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 13466 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 13467 if (Init.isInvalid()) 13468 return Init; 13469 RHSExpr = Init.get(); 13470 } 13471 13472 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13473 QualType ResultTy; // Result type of the binary operator. 13474 // The following two variables are used for compound assignment operators 13475 QualType CompLHSTy; // Type of LHS after promotions for computation 13476 QualType CompResultTy; // Type of computation result 13477 ExprValueKind VK = VK_RValue; 13478 ExprObjectKind OK = OK_Ordinary; 13479 bool ConvertHalfVec = false; 13480 13481 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13482 if (!LHS.isUsable() || !RHS.isUsable()) 13483 return ExprError(); 13484 13485 if (getLangOpts().OpenCL) { 13486 QualType LHSTy = LHSExpr->getType(); 13487 QualType RHSTy = RHSExpr->getType(); 13488 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 13489 // the ATOMIC_VAR_INIT macro. 13490 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 13491 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13492 if (BO_Assign == Opc) 13493 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 13494 else 13495 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13496 return ExprError(); 13497 } 13498 13499 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13500 // only with a builtin functions and therefore should be disallowed here. 13501 if (LHSTy->isImageType() || RHSTy->isImageType() || 13502 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 13503 LHSTy->isPipeType() || RHSTy->isPipeType() || 13504 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 13505 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13506 return ExprError(); 13507 } 13508 } 13509 13510 // Diagnose operations on the unsupported types for OpenMP device compilation. 13511 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 13512 if (Opc != BO_Assign && Opc != BO_Comma) { 13513 checkOpenMPDeviceExpr(LHSExpr); 13514 checkOpenMPDeviceExpr(RHSExpr); 13515 } 13516 } 13517 13518 switch (Opc) { 13519 case BO_Assign: 13520 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 13521 if (getLangOpts().CPlusPlus && 13522 LHS.get()->getObjectKind() != OK_ObjCProperty) { 13523 VK = LHS.get()->getValueKind(); 13524 OK = LHS.get()->getObjectKind(); 13525 } 13526 if (!ResultTy.isNull()) { 13527 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13528 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 13529 13530 // Avoid copying a block to the heap if the block is assigned to a local 13531 // auto variable that is declared in the same scope as the block. This 13532 // optimization is unsafe if the local variable is declared in an outer 13533 // scope. For example: 13534 // 13535 // BlockTy b; 13536 // { 13537 // b = ^{...}; 13538 // } 13539 // // It is unsafe to invoke the block here if it wasn't copied to the 13540 // // heap. 13541 // b(); 13542 13543 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 13544 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 13545 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 13546 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 13547 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13548 13549 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13550 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 13551 NTCUC_Assignment, NTCUK_Copy); 13552 } 13553 RecordModifiableNonNullParam(*this, LHS.get()); 13554 break; 13555 case BO_PtrMemD: 13556 case BO_PtrMemI: 13557 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 13558 Opc == BO_PtrMemI); 13559 break; 13560 case BO_Mul: 13561 case BO_Div: 13562 ConvertHalfVec = true; 13563 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 13564 Opc == BO_Div); 13565 break; 13566 case BO_Rem: 13567 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 13568 break; 13569 case BO_Add: 13570 ConvertHalfVec = true; 13571 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 13572 break; 13573 case BO_Sub: 13574 ConvertHalfVec = true; 13575 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 13576 break; 13577 case BO_Shl: 13578 case BO_Shr: 13579 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 13580 break; 13581 case BO_LE: 13582 case BO_LT: 13583 case BO_GE: 13584 case BO_GT: 13585 ConvertHalfVec = true; 13586 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13587 break; 13588 case BO_EQ: 13589 case BO_NE: 13590 ConvertHalfVec = true; 13591 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13592 break; 13593 case BO_Cmp: 13594 ConvertHalfVec = true; 13595 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13596 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 13597 break; 13598 case BO_And: 13599 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 13600 LLVM_FALLTHROUGH; 13601 case BO_Xor: 13602 case BO_Or: 13603 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13604 break; 13605 case BO_LAnd: 13606 case BO_LOr: 13607 ConvertHalfVec = true; 13608 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 13609 break; 13610 case BO_MulAssign: 13611 case BO_DivAssign: 13612 ConvertHalfVec = true; 13613 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 13614 Opc == BO_DivAssign); 13615 CompLHSTy = CompResultTy; 13616 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13617 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13618 break; 13619 case BO_RemAssign: 13620 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 13621 CompLHSTy = CompResultTy; 13622 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13623 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13624 break; 13625 case BO_AddAssign: 13626 ConvertHalfVec = true; 13627 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 13628 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13629 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13630 break; 13631 case BO_SubAssign: 13632 ConvertHalfVec = true; 13633 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 13634 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13635 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13636 break; 13637 case BO_ShlAssign: 13638 case BO_ShrAssign: 13639 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 13640 CompLHSTy = CompResultTy; 13641 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13642 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13643 break; 13644 case BO_AndAssign: 13645 case BO_OrAssign: // fallthrough 13646 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13647 LLVM_FALLTHROUGH; 13648 case BO_XorAssign: 13649 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13650 CompLHSTy = CompResultTy; 13651 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13652 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13653 break; 13654 case BO_Comma: 13655 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 13656 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 13657 VK = RHS.get()->getValueKind(); 13658 OK = RHS.get()->getObjectKind(); 13659 } 13660 break; 13661 } 13662 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 13663 return ExprError(); 13664 13665 if (ResultTy->isRealFloatingType() && 13666 (getLangOpts().getFPRoundingMode() != RoundingMode::NearestTiesToEven || 13667 getLangOpts().getFPExceptionMode() != LangOptions::FPE_Ignore)) 13668 // Mark the current function as usng floating point constrained intrinsics 13669 if (FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13670 F->setUsesFPIntrin(true); 13671 } 13672 13673 // Some of the binary operations require promoting operands of half vector to 13674 // float vectors and truncating the result back to half vector. For now, we do 13675 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 13676 // arm64). 13677 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 13678 isVector(LHS.get()->getType(), Context.HalfTy) && 13679 "both sides are half vectors or neither sides are"); 13680 ConvertHalfVec = 13681 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 13682 13683 // Check for array bounds violations for both sides of the BinaryOperator 13684 CheckArrayAccess(LHS.get()); 13685 CheckArrayAccess(RHS.get()); 13686 13687 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 13688 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 13689 &Context.Idents.get("object_setClass"), 13690 SourceLocation(), LookupOrdinaryName); 13691 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 13692 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 13693 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 13694 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 13695 "object_setClass(") 13696 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 13697 ",") 13698 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 13699 } 13700 else 13701 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 13702 } 13703 else if (const ObjCIvarRefExpr *OIRE = 13704 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 13705 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 13706 13707 // Opc is not a compound assignment if CompResultTy is null. 13708 if (CompResultTy.isNull()) { 13709 if (ConvertHalfVec) 13710 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 13711 OpLoc, CurFPFeatures); 13712 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 13713 VK, OK, OpLoc, CurFPFeatures); 13714 } 13715 13716 // Handle compound assignments. 13717 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 13718 OK_ObjCProperty) { 13719 VK = VK_LValue; 13720 OK = LHS.get()->getObjectKind(); 13721 } 13722 13723 // The LHS is not converted to the result type for fixed-point compound 13724 // assignment as the common type is computed on demand. Reset the CompLHSTy 13725 // to the LHS type we would have gotten after unary conversions. 13726 if (CompResultTy->isFixedPointType()) 13727 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 13728 13729 if (ConvertHalfVec) 13730 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 13731 OpLoc, CurFPFeatures); 13732 13733 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13734 ResultTy, VK, OK, OpLoc, CurFPFeatures, 13735 CompLHSTy, CompResultTy); 13736 } 13737 13738 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 13739 /// operators are mixed in a way that suggests that the programmer forgot that 13740 /// comparison operators have higher precedence. The most typical example of 13741 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 13742 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 13743 SourceLocation OpLoc, Expr *LHSExpr, 13744 Expr *RHSExpr) { 13745 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 13746 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 13747 13748 // Check that one of the sides is a comparison operator and the other isn't. 13749 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 13750 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 13751 if (isLeftComp == isRightComp) 13752 return; 13753 13754 // Bitwise operations are sometimes used as eager logical ops. 13755 // Don't diagnose this. 13756 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 13757 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 13758 if (isLeftBitwise || isRightBitwise) 13759 return; 13760 13761 SourceRange DiagRange = isLeftComp 13762 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 13763 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 13764 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 13765 SourceRange ParensRange = 13766 isLeftComp 13767 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 13768 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 13769 13770 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 13771 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 13772 SuggestParentheses(Self, OpLoc, 13773 Self.PDiag(diag::note_precedence_silence) << OpStr, 13774 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 13775 SuggestParentheses(Self, OpLoc, 13776 Self.PDiag(diag::note_precedence_bitwise_first) 13777 << BinaryOperator::getOpcodeStr(Opc), 13778 ParensRange); 13779 } 13780 13781 /// It accepts a '&&' expr that is inside a '||' one. 13782 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 13783 /// in parentheses. 13784 static void 13785 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 13786 BinaryOperator *Bop) { 13787 assert(Bop->getOpcode() == BO_LAnd); 13788 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 13789 << Bop->getSourceRange() << OpLoc; 13790 SuggestParentheses(Self, Bop->getOperatorLoc(), 13791 Self.PDiag(diag::note_precedence_silence) 13792 << Bop->getOpcodeStr(), 13793 Bop->getSourceRange()); 13794 } 13795 13796 /// Returns true if the given expression can be evaluated as a constant 13797 /// 'true'. 13798 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 13799 bool Res; 13800 return !E->isValueDependent() && 13801 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 13802 } 13803 13804 /// Returns true if the given expression can be evaluated as a constant 13805 /// 'false'. 13806 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 13807 bool Res; 13808 return !E->isValueDependent() && 13809 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 13810 } 13811 13812 /// Look for '&&' in the left hand of a '||' expr. 13813 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 13814 Expr *LHSExpr, Expr *RHSExpr) { 13815 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 13816 if (Bop->getOpcode() == BO_LAnd) { 13817 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 13818 if (EvaluatesAsFalse(S, RHSExpr)) 13819 return; 13820 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 13821 if (!EvaluatesAsTrue(S, Bop->getLHS())) 13822 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13823 } else if (Bop->getOpcode() == BO_LOr) { 13824 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 13825 // If it's "a || b && 1 || c" we didn't warn earlier for 13826 // "a || b && 1", but warn now. 13827 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 13828 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 13829 } 13830 } 13831 } 13832 } 13833 13834 /// Look for '&&' in the right hand of a '||' expr. 13835 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 13836 Expr *LHSExpr, Expr *RHSExpr) { 13837 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 13838 if (Bop->getOpcode() == BO_LAnd) { 13839 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 13840 if (EvaluatesAsFalse(S, LHSExpr)) 13841 return; 13842 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 13843 if (!EvaluatesAsTrue(S, Bop->getRHS())) 13844 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13845 } 13846 } 13847 } 13848 13849 /// Look for bitwise op in the left or right hand of a bitwise op with 13850 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 13851 /// the '&' expression in parentheses. 13852 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 13853 SourceLocation OpLoc, Expr *SubExpr) { 13854 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13855 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 13856 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 13857 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 13858 << Bop->getSourceRange() << OpLoc; 13859 SuggestParentheses(S, Bop->getOperatorLoc(), 13860 S.PDiag(diag::note_precedence_silence) 13861 << Bop->getOpcodeStr(), 13862 Bop->getSourceRange()); 13863 } 13864 } 13865 } 13866 13867 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 13868 Expr *SubExpr, StringRef Shift) { 13869 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13870 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 13871 StringRef Op = Bop->getOpcodeStr(); 13872 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 13873 << Bop->getSourceRange() << OpLoc << Shift << Op; 13874 SuggestParentheses(S, Bop->getOperatorLoc(), 13875 S.PDiag(diag::note_precedence_silence) << Op, 13876 Bop->getSourceRange()); 13877 } 13878 } 13879 } 13880 13881 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 13882 Expr *LHSExpr, Expr *RHSExpr) { 13883 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 13884 if (!OCE) 13885 return; 13886 13887 FunctionDecl *FD = OCE->getDirectCallee(); 13888 if (!FD || !FD->isOverloadedOperator()) 13889 return; 13890 13891 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 13892 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 13893 return; 13894 13895 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 13896 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 13897 << (Kind == OO_LessLess); 13898 SuggestParentheses(S, OCE->getOperatorLoc(), 13899 S.PDiag(diag::note_precedence_silence) 13900 << (Kind == OO_LessLess ? "<<" : ">>"), 13901 OCE->getSourceRange()); 13902 SuggestParentheses( 13903 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 13904 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 13905 } 13906 13907 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 13908 /// precedence. 13909 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 13910 SourceLocation OpLoc, Expr *LHSExpr, 13911 Expr *RHSExpr){ 13912 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 13913 if (BinaryOperator::isBitwiseOp(Opc)) 13914 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 13915 13916 // Diagnose "arg1 & arg2 | arg3" 13917 if ((Opc == BO_Or || Opc == BO_Xor) && 13918 !OpLoc.isMacroID()/* Don't warn in macros. */) { 13919 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 13920 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 13921 } 13922 13923 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 13924 // We don't warn for 'assert(a || b && "bad")' since this is safe. 13925 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 13926 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 13927 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 13928 } 13929 13930 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 13931 || Opc == BO_Shr) { 13932 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 13933 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 13934 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 13935 } 13936 13937 // Warn on overloaded shift operators and comparisons, such as: 13938 // cout << 5 == 4; 13939 if (BinaryOperator::isComparisonOp(Opc)) 13940 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 13941 } 13942 13943 // Binary Operators. 'Tok' is the token for the operator. 13944 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 13945 tok::TokenKind Kind, 13946 Expr *LHSExpr, Expr *RHSExpr) { 13947 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 13948 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 13949 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 13950 13951 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 13952 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 13953 13954 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 13955 } 13956 13957 /// Build an overloaded binary operator expression in the given scope. 13958 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 13959 BinaryOperatorKind Opc, 13960 Expr *LHS, Expr *RHS) { 13961 switch (Opc) { 13962 case BO_Assign: 13963 case BO_DivAssign: 13964 case BO_RemAssign: 13965 case BO_SubAssign: 13966 case BO_AndAssign: 13967 case BO_OrAssign: 13968 case BO_XorAssign: 13969 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 13970 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 13971 break; 13972 default: 13973 break; 13974 } 13975 13976 // Find all of the overloaded operators visible from this 13977 // point. We perform both an operator-name lookup from the local 13978 // scope and an argument-dependent lookup based on the types of 13979 // the arguments. 13980 UnresolvedSet<16> Functions; 13981 OverloadedOperatorKind OverOp 13982 = BinaryOperator::getOverloadedOperator(Opc); 13983 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 13984 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 13985 RHS->getType(), Functions); 13986 13987 // In C++20 onwards, we may have a second operator to look up. 13988 if (S.getLangOpts().CPlusPlus20) { 13989 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 13990 S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(), 13991 RHS->getType(), Functions); 13992 } 13993 13994 // Build the (potentially-overloaded, potentially-dependent) 13995 // binary operation. 13996 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 13997 } 13998 13999 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14000 BinaryOperatorKind Opc, 14001 Expr *LHSExpr, Expr *RHSExpr) { 14002 ExprResult LHS, RHS; 14003 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14004 if (!LHS.isUsable() || !RHS.isUsable()) 14005 return ExprError(); 14006 LHSExpr = LHS.get(); 14007 RHSExpr = RHS.get(); 14008 14009 // We want to end up calling one of checkPseudoObjectAssignment 14010 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14011 // both expressions are overloadable or either is type-dependent), 14012 // or CreateBuiltinBinOp (in any other case). We also want to get 14013 // any placeholder types out of the way. 14014 14015 // Handle pseudo-objects in the LHS. 14016 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14017 // Assignments with a pseudo-object l-value need special analysis. 14018 if (pty->getKind() == BuiltinType::PseudoObject && 14019 BinaryOperator::isAssignmentOp(Opc)) 14020 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14021 14022 // Don't resolve overloads if the other type is overloadable. 14023 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14024 // We can't actually test that if we still have a placeholder, 14025 // though. Fortunately, none of the exceptions we see in that 14026 // code below are valid when the LHS is an overload set. Note 14027 // that an overload set can be dependently-typed, but it never 14028 // instantiates to having an overloadable type. 14029 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14030 if (resolvedRHS.isInvalid()) return ExprError(); 14031 RHSExpr = resolvedRHS.get(); 14032 14033 if (RHSExpr->isTypeDependent() || 14034 RHSExpr->getType()->isOverloadableType()) 14035 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14036 } 14037 14038 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14039 // template, diagnose the missing 'template' keyword instead of diagnosing 14040 // an invalid use of a bound member function. 14041 // 14042 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14043 // to C++1z [over.over]/1.4, but we already checked for that case above. 14044 if (Opc == BO_LT && inTemplateInstantiation() && 14045 (pty->getKind() == BuiltinType::BoundMember || 14046 pty->getKind() == BuiltinType::Overload)) { 14047 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14048 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14049 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14050 return isa<FunctionTemplateDecl>(ND); 14051 })) { 14052 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14053 : OE->getNameLoc(), 14054 diag::err_template_kw_missing) 14055 << OE->getName().getAsString() << ""; 14056 return ExprError(); 14057 } 14058 } 14059 14060 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14061 if (LHS.isInvalid()) return ExprError(); 14062 LHSExpr = LHS.get(); 14063 } 14064 14065 // Handle pseudo-objects in the RHS. 14066 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14067 // An overload in the RHS can potentially be resolved by the type 14068 // being assigned to. 14069 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14070 if (getLangOpts().CPlusPlus && 14071 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14072 LHSExpr->getType()->isOverloadableType())) 14073 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14074 14075 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14076 } 14077 14078 // Don't resolve overloads if the other type is overloadable. 14079 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14080 LHSExpr->getType()->isOverloadableType()) 14081 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14082 14083 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14084 if (!resolvedRHS.isUsable()) return ExprError(); 14085 RHSExpr = resolvedRHS.get(); 14086 } 14087 14088 if (getLangOpts().CPlusPlus) { 14089 // If either expression is type-dependent, always build an 14090 // overloaded op. 14091 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14092 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14093 14094 // Otherwise, build an overloaded op if either expression has an 14095 // overloadable type. 14096 if (LHSExpr->getType()->isOverloadableType() || 14097 RHSExpr->getType()->isOverloadableType()) 14098 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14099 } 14100 14101 // Build a built-in binary operation. 14102 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14103 } 14104 14105 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14106 if (T.isNull() || T->isDependentType()) 14107 return false; 14108 14109 if (!T->isPromotableIntegerType()) 14110 return true; 14111 14112 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14113 } 14114 14115 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14116 UnaryOperatorKind Opc, 14117 Expr *InputExpr) { 14118 ExprResult Input = InputExpr; 14119 ExprValueKind VK = VK_RValue; 14120 ExprObjectKind OK = OK_Ordinary; 14121 QualType resultType; 14122 bool CanOverflow = false; 14123 14124 bool ConvertHalfVec = false; 14125 if (getLangOpts().OpenCL) { 14126 QualType Ty = InputExpr->getType(); 14127 // The only legal unary operation for atomics is '&'. 14128 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14129 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14130 // only with a builtin functions and therefore should be disallowed here. 14131 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14132 || Ty->isBlockPointerType())) { 14133 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14134 << InputExpr->getType() 14135 << Input.get()->getSourceRange()); 14136 } 14137 } 14138 // Diagnose operations on the unsupported types for OpenMP device compilation. 14139 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 14140 if (UnaryOperator::isIncrementDecrementOp(Opc) || 14141 UnaryOperator::isArithmeticOp(Opc)) 14142 checkOpenMPDeviceExpr(InputExpr); 14143 } 14144 14145 switch (Opc) { 14146 case UO_PreInc: 14147 case UO_PreDec: 14148 case UO_PostInc: 14149 case UO_PostDec: 14150 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14151 OpLoc, 14152 Opc == UO_PreInc || 14153 Opc == UO_PostInc, 14154 Opc == UO_PreInc || 14155 Opc == UO_PreDec); 14156 CanOverflow = isOverflowingIntegerType(Context, resultType); 14157 break; 14158 case UO_AddrOf: 14159 resultType = CheckAddressOfOperand(Input, OpLoc); 14160 CheckAddressOfNoDeref(InputExpr); 14161 RecordModifiableNonNullParam(*this, InputExpr); 14162 break; 14163 case UO_Deref: { 14164 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14165 if (Input.isInvalid()) return ExprError(); 14166 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14167 break; 14168 } 14169 case UO_Plus: 14170 case UO_Minus: 14171 CanOverflow = Opc == UO_Minus && 14172 isOverflowingIntegerType(Context, Input.get()->getType()); 14173 Input = UsualUnaryConversions(Input.get()); 14174 if (Input.isInvalid()) return ExprError(); 14175 // Unary plus and minus require promoting an operand of half vector to a 14176 // float vector and truncating the result back to a half vector. For now, we 14177 // do this only when HalfArgsAndReturns is set (that is, when the target is 14178 // arm or arm64). 14179 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14180 14181 // If the operand is a half vector, promote it to a float vector. 14182 if (ConvertHalfVec) 14183 Input = convertVector(Input.get(), Context.FloatTy, *this); 14184 resultType = Input.get()->getType(); 14185 if (resultType->isDependentType()) 14186 break; 14187 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14188 break; 14189 else if (resultType->isVectorType() && 14190 // The z vector extensions don't allow + or - with bool vectors. 14191 (!Context.getLangOpts().ZVector || 14192 resultType->castAs<VectorType>()->getVectorKind() != 14193 VectorType::AltiVecBool)) 14194 break; 14195 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14196 Opc == UO_Plus && 14197 resultType->isPointerType()) 14198 break; 14199 14200 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14201 << resultType << Input.get()->getSourceRange()); 14202 14203 case UO_Not: // bitwise complement 14204 Input = UsualUnaryConversions(Input.get()); 14205 if (Input.isInvalid()) 14206 return ExprError(); 14207 resultType = Input.get()->getType(); 14208 if (resultType->isDependentType()) 14209 break; 14210 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14211 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14212 // C99 does not support '~' for complex conjugation. 14213 Diag(OpLoc, diag::ext_integer_complement_complex) 14214 << resultType << Input.get()->getSourceRange(); 14215 else if (resultType->hasIntegerRepresentation()) 14216 break; 14217 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14218 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14219 // on vector float types. 14220 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14221 if (!T->isIntegerType()) 14222 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14223 << resultType << Input.get()->getSourceRange()); 14224 } else { 14225 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14226 << resultType << Input.get()->getSourceRange()); 14227 } 14228 break; 14229 14230 case UO_LNot: // logical negation 14231 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14232 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14233 if (Input.isInvalid()) return ExprError(); 14234 resultType = Input.get()->getType(); 14235 14236 // Though we still have to promote half FP to float... 14237 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14238 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14239 resultType = Context.FloatTy; 14240 } 14241 14242 if (resultType->isDependentType()) 14243 break; 14244 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14245 // C99 6.5.3.3p1: ok, fallthrough; 14246 if (Context.getLangOpts().CPlusPlus) { 14247 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14248 // operand contextually converted to bool. 14249 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14250 ScalarTypeToBooleanCastKind(resultType)); 14251 } else if (Context.getLangOpts().OpenCL && 14252 Context.getLangOpts().OpenCLVersion < 120) { 14253 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14254 // operate on scalar float types. 14255 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14256 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14257 << resultType << Input.get()->getSourceRange()); 14258 } 14259 } else if (resultType->isExtVectorType()) { 14260 if (Context.getLangOpts().OpenCL && 14261 Context.getLangOpts().OpenCLVersion < 120 && 14262 !Context.getLangOpts().OpenCLCPlusPlus) { 14263 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14264 // operate on vector float types. 14265 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14266 if (!T->isIntegerType()) 14267 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14268 << resultType << Input.get()->getSourceRange()); 14269 } 14270 // Vector logical not returns the signed variant of the operand type. 14271 resultType = GetSignedVectorType(resultType); 14272 break; 14273 } else { 14274 // FIXME: GCC's vector extension permits the usage of '!' with a vector 14275 // type in C++. We should allow that here too. 14276 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14277 << resultType << Input.get()->getSourceRange()); 14278 } 14279 14280 // LNot always has type int. C99 6.5.3.3p5. 14281 // In C++, it's bool. C++ 5.3.1p8 14282 resultType = Context.getLogicalOperationType(); 14283 break; 14284 case UO_Real: 14285 case UO_Imag: 14286 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14287 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14288 // complex l-values to ordinary l-values and all other values to r-values. 14289 if (Input.isInvalid()) return ExprError(); 14290 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14291 if (Input.get()->getValueKind() != VK_RValue && 14292 Input.get()->getObjectKind() == OK_Ordinary) 14293 VK = Input.get()->getValueKind(); 14294 } else if (!getLangOpts().CPlusPlus) { 14295 // In C, a volatile scalar is read by __imag. In C++, it is not. 14296 Input = DefaultLvalueConversion(Input.get()); 14297 } 14298 break; 14299 case UO_Extension: 14300 resultType = Input.get()->getType(); 14301 VK = Input.get()->getValueKind(); 14302 OK = Input.get()->getObjectKind(); 14303 break; 14304 case UO_Coawait: 14305 // It's unnecessary to represent the pass-through operator co_await in the 14306 // AST; just return the input expression instead. 14307 assert(!Input.get()->getType()->isDependentType() && 14308 "the co_await expression must be non-dependant before " 14309 "building operator co_await"); 14310 return Input; 14311 } 14312 if (resultType.isNull() || Input.isInvalid()) 14313 return ExprError(); 14314 14315 // Check for array bounds violations in the operand of the UnaryOperator, 14316 // except for the '*' and '&' operators that have to be handled specially 14317 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14318 // that are explicitly defined as valid by the standard). 14319 if (Opc != UO_AddrOf && Opc != UO_Deref) 14320 CheckArrayAccess(Input.get()); 14321 14322 auto *UO = new (Context) 14323 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 14324 14325 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14326 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 14327 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14328 14329 // Convert the result back to a half vector. 14330 if (ConvertHalfVec) 14331 return convertVector(UO, Context.HalfTy, *this); 14332 return UO; 14333 } 14334 14335 /// Determine whether the given expression is a qualified member 14336 /// access expression, of a form that could be turned into a pointer to member 14337 /// with the address-of operator. 14338 bool Sema::isQualifiedMemberAccess(Expr *E) { 14339 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14340 if (!DRE->getQualifier()) 14341 return false; 14342 14343 ValueDecl *VD = DRE->getDecl(); 14344 if (!VD->isCXXClassMember()) 14345 return false; 14346 14347 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14348 return true; 14349 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14350 return Method->isInstance(); 14351 14352 return false; 14353 } 14354 14355 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14356 if (!ULE->getQualifier()) 14357 return false; 14358 14359 for (NamedDecl *D : ULE->decls()) { 14360 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14361 if (Method->isInstance()) 14362 return true; 14363 } else { 14364 // Overload set does not contain methods. 14365 break; 14366 } 14367 } 14368 14369 return false; 14370 } 14371 14372 return false; 14373 } 14374 14375 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 14376 UnaryOperatorKind Opc, Expr *Input) { 14377 // First things first: handle placeholders so that the 14378 // overloaded-operator check considers the right type. 14379 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 14380 // Increment and decrement of pseudo-object references. 14381 if (pty->getKind() == BuiltinType::PseudoObject && 14382 UnaryOperator::isIncrementDecrementOp(Opc)) 14383 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 14384 14385 // extension is always a builtin operator. 14386 if (Opc == UO_Extension) 14387 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14388 14389 // & gets special logic for several kinds of placeholder. 14390 // The builtin code knows what to do. 14391 if (Opc == UO_AddrOf && 14392 (pty->getKind() == BuiltinType::Overload || 14393 pty->getKind() == BuiltinType::UnknownAny || 14394 pty->getKind() == BuiltinType::BoundMember)) 14395 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14396 14397 // Anything else needs to be handled now. 14398 ExprResult Result = CheckPlaceholderExpr(Input); 14399 if (Result.isInvalid()) return ExprError(); 14400 Input = Result.get(); 14401 } 14402 14403 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14404 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14405 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14406 // Find all of the overloaded operators visible from this 14407 // point. We perform both an operator-name lookup from the local 14408 // scope and an argument-dependent lookup based on the types of 14409 // the arguments. 14410 UnresolvedSet<16> Functions; 14411 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14412 if (S && OverOp != OO_None) 14413 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 14414 Functions); 14415 14416 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14417 } 14418 14419 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14420 } 14421 14422 // Unary Operators. 'Tok' is the token for the operator. 14423 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 14424 tok::TokenKind Op, Expr *Input) { 14425 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 14426 } 14427 14428 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 14429 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 14430 LabelDecl *TheDecl) { 14431 TheDecl->markUsed(Context); 14432 // Create the AST node. The address of a label always has type 'void*'. 14433 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 14434 Context.getPointerType(Context.VoidTy)); 14435 } 14436 14437 void Sema::ActOnStartStmtExpr() { 14438 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14439 } 14440 14441 void Sema::ActOnStmtExprError() { 14442 // Note that function is also called by TreeTransform when leaving a 14443 // StmtExpr scope without rebuilding anything. 14444 14445 DiscardCleanupsInEvaluationContext(); 14446 PopExpressionEvaluationContext(); 14447 } 14448 14449 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 14450 SourceLocation RPLoc) { 14451 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 14452 } 14453 14454 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 14455 SourceLocation RPLoc, unsigned TemplateDepth) { 14456 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 14457 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 14458 14459 if (hasAnyUnrecoverableErrorsInThisFunction()) 14460 DiscardCleanupsInEvaluationContext(); 14461 assert(!Cleanup.exprNeedsCleanups() && 14462 "cleanups within StmtExpr not correctly bound!"); 14463 PopExpressionEvaluationContext(); 14464 14465 // FIXME: there are a variety of strange constraints to enforce here, for 14466 // example, it is not possible to goto into a stmt expression apparently. 14467 // More semantic analysis is needed. 14468 14469 // If there are sub-stmts in the compound stmt, take the type of the last one 14470 // as the type of the stmtexpr. 14471 QualType Ty = Context.VoidTy; 14472 bool StmtExprMayBindToTemp = false; 14473 if (!Compound->body_empty()) { 14474 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 14475 if (const auto *LastStmt = 14476 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 14477 if (const Expr *Value = LastStmt->getExprStmt()) { 14478 StmtExprMayBindToTemp = true; 14479 Ty = Value->getType(); 14480 } 14481 } 14482 } 14483 14484 // FIXME: Check that expression type is complete/non-abstract; statement 14485 // expressions are not lvalues. 14486 Expr *ResStmtExpr = 14487 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 14488 if (StmtExprMayBindToTemp) 14489 return MaybeBindToTemporary(ResStmtExpr); 14490 return ResStmtExpr; 14491 } 14492 14493 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 14494 if (ER.isInvalid()) 14495 return ExprError(); 14496 14497 // Do function/array conversion on the last expression, but not 14498 // lvalue-to-rvalue. However, initialize an unqualified type. 14499 ER = DefaultFunctionArrayConversion(ER.get()); 14500 if (ER.isInvalid()) 14501 return ExprError(); 14502 Expr *E = ER.get(); 14503 14504 if (E->isTypeDependent()) 14505 return E; 14506 14507 // In ARC, if the final expression ends in a consume, splice 14508 // the consume out and bind it later. In the alternate case 14509 // (when dealing with a retainable type), the result 14510 // initialization will create a produce. In both cases the 14511 // result will be +1, and we'll need to balance that out with 14512 // a bind. 14513 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 14514 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 14515 return Cast->getSubExpr(); 14516 14517 // FIXME: Provide a better location for the initialization. 14518 return PerformCopyInitialization( 14519 InitializedEntity::InitializeStmtExprResult( 14520 E->getBeginLoc(), E->getType().getUnqualifiedType()), 14521 SourceLocation(), E); 14522 } 14523 14524 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 14525 TypeSourceInfo *TInfo, 14526 ArrayRef<OffsetOfComponent> Components, 14527 SourceLocation RParenLoc) { 14528 QualType ArgTy = TInfo->getType(); 14529 bool Dependent = ArgTy->isDependentType(); 14530 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 14531 14532 // We must have at least one component that refers to the type, and the first 14533 // one is known to be a field designator. Verify that the ArgTy represents 14534 // a struct/union/class. 14535 if (!Dependent && !ArgTy->isRecordType()) 14536 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 14537 << ArgTy << TypeRange); 14538 14539 // Type must be complete per C99 7.17p3 because a declaring a variable 14540 // with an incomplete type would be ill-formed. 14541 if (!Dependent 14542 && RequireCompleteType(BuiltinLoc, ArgTy, 14543 diag::err_offsetof_incomplete_type, TypeRange)) 14544 return ExprError(); 14545 14546 bool DidWarnAboutNonPOD = false; 14547 QualType CurrentType = ArgTy; 14548 SmallVector<OffsetOfNode, 4> Comps; 14549 SmallVector<Expr*, 4> Exprs; 14550 for (const OffsetOfComponent &OC : Components) { 14551 if (OC.isBrackets) { 14552 // Offset of an array sub-field. TODO: Should we allow vector elements? 14553 if (!CurrentType->isDependentType()) { 14554 const ArrayType *AT = Context.getAsArrayType(CurrentType); 14555 if(!AT) 14556 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 14557 << CurrentType); 14558 CurrentType = AT->getElementType(); 14559 } else 14560 CurrentType = Context.DependentTy; 14561 14562 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 14563 if (IdxRval.isInvalid()) 14564 return ExprError(); 14565 Expr *Idx = IdxRval.get(); 14566 14567 // The expression must be an integral expression. 14568 // FIXME: An integral constant expression? 14569 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 14570 !Idx->getType()->isIntegerType()) 14571 return ExprError( 14572 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 14573 << Idx->getSourceRange()); 14574 14575 // Record this array index. 14576 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 14577 Exprs.push_back(Idx); 14578 continue; 14579 } 14580 14581 // Offset of a field. 14582 if (CurrentType->isDependentType()) { 14583 // We have the offset of a field, but we can't look into the dependent 14584 // type. Just record the identifier of the field. 14585 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 14586 CurrentType = Context.DependentTy; 14587 continue; 14588 } 14589 14590 // We need to have a complete type to look into. 14591 if (RequireCompleteType(OC.LocStart, CurrentType, 14592 diag::err_offsetof_incomplete_type)) 14593 return ExprError(); 14594 14595 // Look for the designated field. 14596 const RecordType *RC = CurrentType->getAs<RecordType>(); 14597 if (!RC) 14598 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 14599 << CurrentType); 14600 RecordDecl *RD = RC->getDecl(); 14601 14602 // C++ [lib.support.types]p5: 14603 // The macro offsetof accepts a restricted set of type arguments in this 14604 // International Standard. type shall be a POD structure or a POD union 14605 // (clause 9). 14606 // C++11 [support.types]p4: 14607 // If type is not a standard-layout class (Clause 9), the results are 14608 // undefined. 14609 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14610 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 14611 unsigned DiagID = 14612 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 14613 : diag::ext_offsetof_non_pod_type; 14614 14615 if (!IsSafe && !DidWarnAboutNonPOD && 14616 DiagRuntimeBehavior(BuiltinLoc, nullptr, 14617 PDiag(DiagID) 14618 << SourceRange(Components[0].LocStart, OC.LocEnd) 14619 << CurrentType)) 14620 DidWarnAboutNonPOD = true; 14621 } 14622 14623 // Look for the field. 14624 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 14625 LookupQualifiedName(R, RD); 14626 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 14627 IndirectFieldDecl *IndirectMemberDecl = nullptr; 14628 if (!MemberDecl) { 14629 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 14630 MemberDecl = IndirectMemberDecl->getAnonField(); 14631 } 14632 14633 if (!MemberDecl) 14634 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 14635 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 14636 OC.LocEnd)); 14637 14638 // C99 7.17p3: 14639 // (If the specified member is a bit-field, the behavior is undefined.) 14640 // 14641 // We diagnose this as an error. 14642 if (MemberDecl->isBitField()) { 14643 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 14644 << MemberDecl->getDeclName() 14645 << SourceRange(BuiltinLoc, RParenLoc); 14646 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 14647 return ExprError(); 14648 } 14649 14650 RecordDecl *Parent = MemberDecl->getParent(); 14651 if (IndirectMemberDecl) 14652 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 14653 14654 // If the member was found in a base class, introduce OffsetOfNodes for 14655 // the base class indirections. 14656 CXXBasePaths Paths; 14657 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 14658 Paths)) { 14659 if (Paths.getDetectedVirtual()) { 14660 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 14661 << MemberDecl->getDeclName() 14662 << SourceRange(BuiltinLoc, RParenLoc); 14663 return ExprError(); 14664 } 14665 14666 CXXBasePath &Path = Paths.front(); 14667 for (const CXXBasePathElement &B : Path) 14668 Comps.push_back(OffsetOfNode(B.Base)); 14669 } 14670 14671 if (IndirectMemberDecl) { 14672 for (auto *FI : IndirectMemberDecl->chain()) { 14673 assert(isa<FieldDecl>(FI)); 14674 Comps.push_back(OffsetOfNode(OC.LocStart, 14675 cast<FieldDecl>(FI), OC.LocEnd)); 14676 } 14677 } else 14678 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 14679 14680 CurrentType = MemberDecl->getType().getNonReferenceType(); 14681 } 14682 14683 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 14684 Comps, Exprs, RParenLoc); 14685 } 14686 14687 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 14688 SourceLocation BuiltinLoc, 14689 SourceLocation TypeLoc, 14690 ParsedType ParsedArgTy, 14691 ArrayRef<OffsetOfComponent> Components, 14692 SourceLocation RParenLoc) { 14693 14694 TypeSourceInfo *ArgTInfo; 14695 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 14696 if (ArgTy.isNull()) 14697 return ExprError(); 14698 14699 if (!ArgTInfo) 14700 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 14701 14702 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 14703 } 14704 14705 14706 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 14707 Expr *CondExpr, 14708 Expr *LHSExpr, Expr *RHSExpr, 14709 SourceLocation RPLoc) { 14710 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 14711 14712 ExprValueKind VK = VK_RValue; 14713 ExprObjectKind OK = OK_Ordinary; 14714 QualType resType; 14715 bool CondIsTrue = false; 14716 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 14717 resType = Context.DependentTy; 14718 } else { 14719 // The conditional expression is required to be a constant expression. 14720 llvm::APSInt condEval(32); 14721 ExprResult CondICE 14722 = VerifyIntegerConstantExpression(CondExpr, &condEval, 14723 diag::err_typecheck_choose_expr_requires_constant, false); 14724 if (CondICE.isInvalid()) 14725 return ExprError(); 14726 CondExpr = CondICE.get(); 14727 CondIsTrue = condEval.getZExtValue(); 14728 14729 // If the condition is > zero, then the AST type is the same as the LHSExpr. 14730 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 14731 14732 resType = ActiveExpr->getType(); 14733 VK = ActiveExpr->getValueKind(); 14734 OK = ActiveExpr->getObjectKind(); 14735 } 14736 14737 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 14738 resType, VK, OK, RPLoc, CondIsTrue); 14739 } 14740 14741 //===----------------------------------------------------------------------===// 14742 // Clang Extensions. 14743 //===----------------------------------------------------------------------===// 14744 14745 /// ActOnBlockStart - This callback is invoked when a block literal is started. 14746 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 14747 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 14748 14749 if (LangOpts.CPlusPlus) { 14750 MangleNumberingContext *MCtx; 14751 Decl *ManglingContextDecl; 14752 std::tie(MCtx, ManglingContextDecl) = 14753 getCurrentMangleNumberContext(Block->getDeclContext()); 14754 if (MCtx) { 14755 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 14756 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 14757 } 14758 } 14759 14760 PushBlockScope(CurScope, Block); 14761 CurContext->addDecl(Block); 14762 if (CurScope) 14763 PushDeclContext(CurScope, Block); 14764 else 14765 CurContext = Block; 14766 14767 getCurBlock()->HasImplicitReturnType = true; 14768 14769 // Enter a new evaluation context to insulate the block from any 14770 // cleanups from the enclosing full-expression. 14771 PushExpressionEvaluationContext( 14772 ExpressionEvaluationContext::PotentiallyEvaluated); 14773 } 14774 14775 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 14776 Scope *CurScope) { 14777 assert(ParamInfo.getIdentifier() == nullptr && 14778 "block-id should have no identifier!"); 14779 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 14780 BlockScopeInfo *CurBlock = getCurBlock(); 14781 14782 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 14783 QualType T = Sig->getType(); 14784 14785 // FIXME: We should allow unexpanded parameter packs here, but that would, 14786 // in turn, make the block expression contain unexpanded parameter packs. 14787 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 14788 // Drop the parameters. 14789 FunctionProtoType::ExtProtoInfo EPI; 14790 EPI.HasTrailingReturn = false; 14791 EPI.TypeQuals.addConst(); 14792 T = Context.getFunctionType(Context.DependentTy, None, EPI); 14793 Sig = Context.getTrivialTypeSourceInfo(T); 14794 } 14795 14796 // GetTypeForDeclarator always produces a function type for a block 14797 // literal signature. Furthermore, it is always a FunctionProtoType 14798 // unless the function was written with a typedef. 14799 assert(T->isFunctionType() && 14800 "GetTypeForDeclarator made a non-function block signature"); 14801 14802 // Look for an explicit signature in that function type. 14803 FunctionProtoTypeLoc ExplicitSignature; 14804 14805 if ((ExplicitSignature = Sig->getTypeLoc() 14806 .getAsAdjusted<FunctionProtoTypeLoc>())) { 14807 14808 // Check whether that explicit signature was synthesized by 14809 // GetTypeForDeclarator. If so, don't save that as part of the 14810 // written signature. 14811 if (ExplicitSignature.getLocalRangeBegin() == 14812 ExplicitSignature.getLocalRangeEnd()) { 14813 // This would be much cheaper if we stored TypeLocs instead of 14814 // TypeSourceInfos. 14815 TypeLoc Result = ExplicitSignature.getReturnLoc(); 14816 unsigned Size = Result.getFullDataSize(); 14817 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 14818 Sig->getTypeLoc().initializeFullCopy(Result, Size); 14819 14820 ExplicitSignature = FunctionProtoTypeLoc(); 14821 } 14822 } 14823 14824 CurBlock->TheDecl->setSignatureAsWritten(Sig); 14825 CurBlock->FunctionType = T; 14826 14827 const FunctionType *Fn = T->getAs<FunctionType>(); 14828 QualType RetTy = Fn->getReturnType(); 14829 bool isVariadic = 14830 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 14831 14832 CurBlock->TheDecl->setIsVariadic(isVariadic); 14833 14834 // Context.DependentTy is used as a placeholder for a missing block 14835 // return type. TODO: what should we do with declarators like: 14836 // ^ * { ... } 14837 // If the answer is "apply template argument deduction".... 14838 if (RetTy != Context.DependentTy) { 14839 CurBlock->ReturnType = RetTy; 14840 CurBlock->TheDecl->setBlockMissingReturnType(false); 14841 CurBlock->HasImplicitReturnType = false; 14842 } 14843 14844 // Push block parameters from the declarator if we had them. 14845 SmallVector<ParmVarDecl*, 8> Params; 14846 if (ExplicitSignature) { 14847 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 14848 ParmVarDecl *Param = ExplicitSignature.getParam(I); 14849 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 14850 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 14851 // Diagnose this as an extension in C17 and earlier. 14852 if (!getLangOpts().C2x) 14853 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14854 } 14855 Params.push_back(Param); 14856 } 14857 14858 // Fake up parameter variables if we have a typedef, like 14859 // ^ fntype { ... } 14860 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 14861 for (const auto &I : Fn->param_types()) { 14862 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 14863 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 14864 Params.push_back(Param); 14865 } 14866 } 14867 14868 // Set the parameters on the block decl. 14869 if (!Params.empty()) { 14870 CurBlock->TheDecl->setParams(Params); 14871 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 14872 /*CheckParameterNames=*/false); 14873 } 14874 14875 // Finally we can process decl attributes. 14876 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 14877 14878 // Put the parameter variables in scope. 14879 for (auto AI : CurBlock->TheDecl->parameters()) { 14880 AI->setOwningFunction(CurBlock->TheDecl); 14881 14882 // If this has an identifier, add it to the scope stack. 14883 if (AI->getIdentifier()) { 14884 CheckShadow(CurBlock->TheScope, AI); 14885 14886 PushOnScopeChains(AI, CurBlock->TheScope); 14887 } 14888 } 14889 } 14890 14891 /// ActOnBlockError - If there is an error parsing a block, this callback 14892 /// is invoked to pop the information about the block from the action impl. 14893 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 14894 // Leave the expression-evaluation context. 14895 DiscardCleanupsInEvaluationContext(); 14896 PopExpressionEvaluationContext(); 14897 14898 // Pop off CurBlock, handle nested blocks. 14899 PopDeclContext(); 14900 PopFunctionScopeInfo(); 14901 } 14902 14903 /// ActOnBlockStmtExpr - This is called when the body of a block statement 14904 /// literal was successfully completed. ^(int x){...} 14905 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 14906 Stmt *Body, Scope *CurScope) { 14907 // If blocks are disabled, emit an error. 14908 if (!LangOpts.Blocks) 14909 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 14910 14911 // Leave the expression-evaluation context. 14912 if (hasAnyUnrecoverableErrorsInThisFunction()) 14913 DiscardCleanupsInEvaluationContext(); 14914 assert(!Cleanup.exprNeedsCleanups() && 14915 "cleanups within block not correctly bound!"); 14916 PopExpressionEvaluationContext(); 14917 14918 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 14919 BlockDecl *BD = BSI->TheDecl; 14920 14921 if (BSI->HasImplicitReturnType) 14922 deduceClosureReturnType(*BSI); 14923 14924 QualType RetTy = Context.VoidTy; 14925 if (!BSI->ReturnType.isNull()) 14926 RetTy = BSI->ReturnType; 14927 14928 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 14929 QualType BlockTy; 14930 14931 // If the user wrote a function type in some form, try to use that. 14932 if (!BSI->FunctionType.isNull()) { 14933 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 14934 14935 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 14936 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 14937 14938 // Turn protoless block types into nullary block types. 14939 if (isa<FunctionNoProtoType>(FTy)) { 14940 FunctionProtoType::ExtProtoInfo EPI; 14941 EPI.ExtInfo = Ext; 14942 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14943 14944 // Otherwise, if we don't need to change anything about the function type, 14945 // preserve its sugar structure. 14946 } else if (FTy->getReturnType() == RetTy && 14947 (!NoReturn || FTy->getNoReturnAttr())) { 14948 BlockTy = BSI->FunctionType; 14949 14950 // Otherwise, make the minimal modifications to the function type. 14951 } else { 14952 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 14953 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 14954 EPI.TypeQuals = Qualifiers(); 14955 EPI.ExtInfo = Ext; 14956 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 14957 } 14958 14959 // If we don't have a function type, just build one from nothing. 14960 } else { 14961 FunctionProtoType::ExtProtoInfo EPI; 14962 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 14963 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14964 } 14965 14966 DiagnoseUnusedParameters(BD->parameters()); 14967 BlockTy = Context.getBlockPointerType(BlockTy); 14968 14969 // If needed, diagnose invalid gotos and switches in the block. 14970 if (getCurFunction()->NeedsScopeChecking() && 14971 !PP.isCodeCompletionEnabled()) 14972 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 14973 14974 BD->setBody(cast<CompoundStmt>(Body)); 14975 14976 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14977 DiagnoseUnguardedAvailabilityViolations(BD); 14978 14979 // Try to apply the named return value optimization. We have to check again 14980 // if we can do this, though, because blocks keep return statements around 14981 // to deduce an implicit return type. 14982 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 14983 !BD->isDependentContext()) 14984 computeNRVO(Body, BSI); 14985 14986 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 14987 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 14988 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 14989 NTCUK_Destruct|NTCUK_Copy); 14990 14991 PopDeclContext(); 14992 14993 // Pop the block scope now but keep it alive to the end of this function. 14994 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14995 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 14996 14997 // Set the captured variables on the block. 14998 SmallVector<BlockDecl::Capture, 4> Captures; 14999 for (Capture &Cap : BSI->Captures) { 15000 if (Cap.isInvalid() || Cap.isThisCapture()) 15001 continue; 15002 15003 VarDecl *Var = Cap.getVariable(); 15004 Expr *CopyExpr = nullptr; 15005 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15006 if (const RecordType *Record = 15007 Cap.getCaptureType()->getAs<RecordType>()) { 15008 // The capture logic needs the destructor, so make sure we mark it. 15009 // Usually this is unnecessary because most local variables have 15010 // their destructors marked at declaration time, but parameters are 15011 // an exception because it's technically only the call site that 15012 // actually requires the destructor. 15013 if (isa<ParmVarDecl>(Var)) 15014 FinalizeVarWithDestructor(Var, Record); 15015 15016 // Enter a separate potentially-evaluated context while building block 15017 // initializers to isolate their cleanups from those of the block 15018 // itself. 15019 // FIXME: Is this appropriate even when the block itself occurs in an 15020 // unevaluated operand? 15021 EnterExpressionEvaluationContext EvalContext( 15022 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15023 15024 SourceLocation Loc = Cap.getLocation(); 15025 15026 ExprResult Result = BuildDeclarationNameExpr( 15027 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15028 15029 // According to the blocks spec, the capture of a variable from 15030 // the stack requires a const copy constructor. This is not true 15031 // of the copy/move done to move a __block variable to the heap. 15032 if (!Result.isInvalid() && 15033 !Result.get()->getType().isConstQualified()) { 15034 Result = ImpCastExprToType(Result.get(), 15035 Result.get()->getType().withConst(), 15036 CK_NoOp, VK_LValue); 15037 } 15038 15039 if (!Result.isInvalid()) { 15040 Result = PerformCopyInitialization( 15041 InitializedEntity::InitializeBlock(Var->getLocation(), 15042 Cap.getCaptureType(), false), 15043 Loc, Result.get()); 15044 } 15045 15046 // Build a full-expression copy expression if initialization 15047 // succeeded and used a non-trivial constructor. Recover from 15048 // errors by pretending that the copy isn't necessary. 15049 if (!Result.isInvalid() && 15050 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15051 ->isTrivial()) { 15052 Result = MaybeCreateExprWithCleanups(Result); 15053 CopyExpr = Result.get(); 15054 } 15055 } 15056 } 15057 15058 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15059 CopyExpr); 15060 Captures.push_back(NewCap); 15061 } 15062 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15063 15064 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15065 15066 // If the block isn't obviously global, i.e. it captures anything at 15067 // all, then we need to do a few things in the surrounding context: 15068 if (Result->getBlockDecl()->hasCaptures()) { 15069 // First, this expression has a new cleanup object. 15070 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15071 Cleanup.setExprNeedsCleanups(true); 15072 15073 // It also gets a branch-protected scope if any of the captured 15074 // variables needs destruction. 15075 for (const auto &CI : Result->getBlockDecl()->captures()) { 15076 const VarDecl *var = CI.getVariable(); 15077 if (var->getType().isDestructedType() != QualType::DK_none) { 15078 setFunctionHasBranchProtectedScope(); 15079 break; 15080 } 15081 } 15082 } 15083 15084 if (getCurFunction()) 15085 getCurFunction()->addBlock(BD); 15086 15087 return Result; 15088 } 15089 15090 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15091 SourceLocation RPLoc) { 15092 TypeSourceInfo *TInfo; 15093 GetTypeFromParser(Ty, &TInfo); 15094 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15095 } 15096 15097 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15098 Expr *E, TypeSourceInfo *TInfo, 15099 SourceLocation RPLoc) { 15100 Expr *OrigExpr = E; 15101 bool IsMS = false; 15102 15103 // CUDA device code does not support varargs. 15104 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15105 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15106 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15107 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15108 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15109 } 15110 } 15111 15112 // NVPTX does not support va_arg expression. 15113 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15114 Context.getTargetInfo().getTriple().isNVPTX()) 15115 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15116 15117 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15118 // as Microsoft ABI on an actual Microsoft platform, where 15119 // __builtin_ms_va_list and __builtin_va_list are the same.) 15120 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15121 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15122 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15123 if (Context.hasSameType(MSVaListType, E->getType())) { 15124 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15125 return ExprError(); 15126 IsMS = true; 15127 } 15128 } 15129 15130 // Get the va_list type 15131 QualType VaListType = Context.getBuiltinVaListType(); 15132 if (!IsMS) { 15133 if (VaListType->isArrayType()) { 15134 // Deal with implicit array decay; for example, on x86-64, 15135 // va_list is an array, but it's supposed to decay to 15136 // a pointer for va_arg. 15137 VaListType = Context.getArrayDecayedType(VaListType); 15138 // Make sure the input expression also decays appropriately. 15139 ExprResult Result = UsualUnaryConversions(E); 15140 if (Result.isInvalid()) 15141 return ExprError(); 15142 E = Result.get(); 15143 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15144 // If va_list is a record type and we are compiling in C++ mode, 15145 // check the argument using reference binding. 15146 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15147 Context, Context.getLValueReferenceType(VaListType), false); 15148 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15149 if (Init.isInvalid()) 15150 return ExprError(); 15151 E = Init.getAs<Expr>(); 15152 } else { 15153 // Otherwise, the va_list argument must be an l-value because 15154 // it is modified by va_arg. 15155 if (!E->isTypeDependent() && 15156 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15157 return ExprError(); 15158 } 15159 } 15160 15161 if (!IsMS && !E->isTypeDependent() && 15162 !Context.hasSameType(VaListType, E->getType())) 15163 return ExprError( 15164 Diag(E->getBeginLoc(), 15165 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15166 << OrigExpr->getType() << E->getSourceRange()); 15167 15168 if (!TInfo->getType()->isDependentType()) { 15169 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15170 diag::err_second_parameter_to_va_arg_incomplete, 15171 TInfo->getTypeLoc())) 15172 return ExprError(); 15173 15174 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15175 TInfo->getType(), 15176 diag::err_second_parameter_to_va_arg_abstract, 15177 TInfo->getTypeLoc())) 15178 return ExprError(); 15179 15180 if (!TInfo->getType().isPODType(Context)) { 15181 Diag(TInfo->getTypeLoc().getBeginLoc(), 15182 TInfo->getType()->isObjCLifetimeType() 15183 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15184 : diag::warn_second_parameter_to_va_arg_not_pod) 15185 << TInfo->getType() 15186 << TInfo->getTypeLoc().getSourceRange(); 15187 } 15188 15189 // Check for va_arg where arguments of the given type will be promoted 15190 // (i.e. this va_arg is guaranteed to have undefined behavior). 15191 QualType PromoteType; 15192 if (TInfo->getType()->isPromotableIntegerType()) { 15193 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15194 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 15195 PromoteType = QualType(); 15196 } 15197 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15198 PromoteType = Context.DoubleTy; 15199 if (!PromoteType.isNull()) 15200 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15201 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15202 << TInfo->getType() 15203 << PromoteType 15204 << TInfo->getTypeLoc().getSourceRange()); 15205 } 15206 15207 QualType T = TInfo->getType().getNonLValueExprType(Context); 15208 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15209 } 15210 15211 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15212 // The type of __null will be int or long, depending on the size of 15213 // pointers on the target. 15214 QualType Ty; 15215 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15216 if (pw == Context.getTargetInfo().getIntWidth()) 15217 Ty = Context.IntTy; 15218 else if (pw == Context.getTargetInfo().getLongWidth()) 15219 Ty = Context.LongTy; 15220 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15221 Ty = Context.LongLongTy; 15222 else { 15223 llvm_unreachable("I don't know size of pointer!"); 15224 } 15225 15226 return new (Context) GNUNullExpr(Ty, TokenLoc); 15227 } 15228 15229 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15230 SourceLocation BuiltinLoc, 15231 SourceLocation RPLoc) { 15232 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15233 } 15234 15235 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15236 SourceLocation BuiltinLoc, 15237 SourceLocation RPLoc, 15238 DeclContext *ParentContext) { 15239 return new (Context) 15240 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15241 } 15242 15243 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15244 bool Diagnose) { 15245 if (!getLangOpts().ObjC) 15246 return false; 15247 15248 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15249 if (!PT) 15250 return false; 15251 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15252 15253 // Ignore any parens, implicit casts (should only be 15254 // array-to-pointer decays), and not-so-opaque values. The last is 15255 // important for making this trigger for property assignments. 15256 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15257 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15258 if (OV->getSourceExpr()) 15259 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15260 15261 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15262 if (!PT->isObjCIdType() && 15263 !(ID && ID->getIdentifier()->isStr("NSString"))) 15264 return false; 15265 if (!SL->isAscii()) 15266 return false; 15267 15268 if (Diagnose) { 15269 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15270 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15271 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15272 } 15273 return true; 15274 } 15275 15276 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15277 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15278 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15279 !SrcExpr->isNullPointerConstant( 15280 getASTContext(), Expr::NPC_NeverValueDependent)) { 15281 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15282 return false; 15283 if (Diagnose) { 15284 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15285 << /*number*/1 15286 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 15287 Expr *NumLit = 15288 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 15289 if (NumLit) 15290 Exp = NumLit; 15291 } 15292 return true; 15293 } 15294 15295 return false; 15296 } 15297 15298 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15299 const Expr *SrcExpr) { 15300 if (!DstType->isFunctionPointerType() || 15301 !SrcExpr->getType()->isFunctionType()) 15302 return false; 15303 15304 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15305 if (!DRE) 15306 return false; 15307 15308 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15309 if (!FD) 15310 return false; 15311 15312 return !S.checkAddressOfFunctionIsAvailable(FD, 15313 /*Complain=*/true, 15314 SrcExpr->getBeginLoc()); 15315 } 15316 15317 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15318 SourceLocation Loc, 15319 QualType DstType, QualType SrcType, 15320 Expr *SrcExpr, AssignmentAction Action, 15321 bool *Complained) { 15322 if (Complained) 15323 *Complained = false; 15324 15325 // Decode the result (notice that AST's are still created for extensions). 15326 bool CheckInferredResultType = false; 15327 bool isInvalid = false; 15328 unsigned DiagKind = 0; 15329 FixItHint Hint; 15330 ConversionFixItGenerator ConvHints; 15331 bool MayHaveConvFixit = false; 15332 bool MayHaveFunctionDiff = false; 15333 const ObjCInterfaceDecl *IFace = nullptr; 15334 const ObjCProtocolDecl *PDecl = nullptr; 15335 15336 switch (ConvTy) { 15337 case Compatible: 15338 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 15339 return false; 15340 15341 case PointerToInt: 15342 if (getLangOpts().CPlusPlus) { 15343 DiagKind = diag::err_typecheck_convert_pointer_int; 15344 isInvalid = true; 15345 } else { 15346 DiagKind = diag::ext_typecheck_convert_pointer_int; 15347 } 15348 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15349 MayHaveConvFixit = true; 15350 break; 15351 case IntToPointer: 15352 if (getLangOpts().CPlusPlus) { 15353 DiagKind = diag::err_typecheck_convert_int_pointer; 15354 isInvalid = true; 15355 } else { 15356 DiagKind = diag::ext_typecheck_convert_int_pointer; 15357 } 15358 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15359 MayHaveConvFixit = true; 15360 break; 15361 case IncompatibleFunctionPointer: 15362 if (getLangOpts().CPlusPlus) { 15363 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 15364 isInvalid = true; 15365 } else { 15366 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 15367 } 15368 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15369 MayHaveConvFixit = true; 15370 break; 15371 case IncompatiblePointer: 15372 if (Action == AA_Passing_CFAudited) { 15373 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 15374 } else if (getLangOpts().CPlusPlus) { 15375 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 15376 isInvalid = true; 15377 } else { 15378 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 15379 } 15380 CheckInferredResultType = DstType->isObjCObjectPointerType() && 15381 SrcType->isObjCObjectPointerType(); 15382 if (Hint.isNull() && !CheckInferredResultType) { 15383 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15384 } 15385 else if (CheckInferredResultType) { 15386 SrcType = SrcType.getUnqualifiedType(); 15387 DstType = DstType.getUnqualifiedType(); 15388 } 15389 MayHaveConvFixit = true; 15390 break; 15391 case IncompatiblePointerSign: 15392 if (getLangOpts().CPlusPlus) { 15393 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 15394 isInvalid = true; 15395 } else { 15396 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 15397 } 15398 break; 15399 case FunctionVoidPointer: 15400 if (getLangOpts().CPlusPlus) { 15401 DiagKind = diag::err_typecheck_convert_pointer_void_func; 15402 isInvalid = true; 15403 } else { 15404 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 15405 } 15406 break; 15407 case IncompatiblePointerDiscardsQualifiers: { 15408 // Perform array-to-pointer decay if necessary. 15409 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 15410 15411 isInvalid = true; 15412 15413 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 15414 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 15415 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 15416 DiagKind = diag::err_typecheck_incompatible_address_space; 15417 break; 15418 15419 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 15420 DiagKind = diag::err_typecheck_incompatible_ownership; 15421 break; 15422 } 15423 15424 llvm_unreachable("unknown error case for discarding qualifiers!"); 15425 // fallthrough 15426 } 15427 case CompatiblePointerDiscardsQualifiers: 15428 // If the qualifiers lost were because we were applying the 15429 // (deprecated) C++ conversion from a string literal to a char* 15430 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 15431 // Ideally, this check would be performed in 15432 // checkPointerTypesForAssignment. However, that would require a 15433 // bit of refactoring (so that the second argument is an 15434 // expression, rather than a type), which should be done as part 15435 // of a larger effort to fix checkPointerTypesForAssignment for 15436 // C++ semantics. 15437 if (getLangOpts().CPlusPlus && 15438 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 15439 return false; 15440 if (getLangOpts().CPlusPlus) { 15441 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 15442 isInvalid = true; 15443 } else { 15444 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 15445 } 15446 15447 break; 15448 case IncompatibleNestedPointerQualifiers: 15449 if (getLangOpts().CPlusPlus) { 15450 isInvalid = true; 15451 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 15452 } else { 15453 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 15454 } 15455 break; 15456 case IncompatibleNestedPointerAddressSpaceMismatch: 15457 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 15458 isInvalid = true; 15459 break; 15460 case IntToBlockPointer: 15461 DiagKind = diag::err_int_to_block_pointer; 15462 isInvalid = true; 15463 break; 15464 case IncompatibleBlockPointer: 15465 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 15466 isInvalid = true; 15467 break; 15468 case IncompatibleObjCQualifiedId: { 15469 if (SrcType->isObjCQualifiedIdType()) { 15470 const ObjCObjectPointerType *srcOPT = 15471 SrcType->castAs<ObjCObjectPointerType>(); 15472 for (auto *srcProto : srcOPT->quals()) { 15473 PDecl = srcProto; 15474 break; 15475 } 15476 if (const ObjCInterfaceType *IFaceT = 15477 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15478 IFace = IFaceT->getDecl(); 15479 } 15480 else if (DstType->isObjCQualifiedIdType()) { 15481 const ObjCObjectPointerType *dstOPT = 15482 DstType->castAs<ObjCObjectPointerType>(); 15483 for (auto *dstProto : dstOPT->quals()) { 15484 PDecl = dstProto; 15485 break; 15486 } 15487 if (const ObjCInterfaceType *IFaceT = 15488 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15489 IFace = IFaceT->getDecl(); 15490 } 15491 if (getLangOpts().CPlusPlus) { 15492 DiagKind = diag::err_incompatible_qualified_id; 15493 isInvalid = true; 15494 } else { 15495 DiagKind = diag::warn_incompatible_qualified_id; 15496 } 15497 break; 15498 } 15499 case IncompatibleVectors: 15500 if (getLangOpts().CPlusPlus) { 15501 DiagKind = diag::err_incompatible_vectors; 15502 isInvalid = true; 15503 } else { 15504 DiagKind = diag::warn_incompatible_vectors; 15505 } 15506 break; 15507 case IncompatibleObjCWeakRef: 15508 DiagKind = diag::err_arc_weak_unavailable_assign; 15509 isInvalid = true; 15510 break; 15511 case Incompatible: 15512 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 15513 if (Complained) 15514 *Complained = true; 15515 return true; 15516 } 15517 15518 DiagKind = diag::err_typecheck_convert_incompatible; 15519 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15520 MayHaveConvFixit = true; 15521 isInvalid = true; 15522 MayHaveFunctionDiff = true; 15523 break; 15524 } 15525 15526 QualType FirstType, SecondType; 15527 switch (Action) { 15528 case AA_Assigning: 15529 case AA_Initializing: 15530 // The destination type comes first. 15531 FirstType = DstType; 15532 SecondType = SrcType; 15533 break; 15534 15535 case AA_Returning: 15536 case AA_Passing: 15537 case AA_Passing_CFAudited: 15538 case AA_Converting: 15539 case AA_Sending: 15540 case AA_Casting: 15541 // The source type comes first. 15542 FirstType = SrcType; 15543 SecondType = DstType; 15544 break; 15545 } 15546 15547 PartialDiagnostic FDiag = PDiag(DiagKind); 15548 if (Action == AA_Passing_CFAudited) 15549 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 15550 else 15551 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 15552 15553 // If we can fix the conversion, suggest the FixIts. 15554 assert(ConvHints.isNull() || Hint.isNull()); 15555 if (!ConvHints.isNull()) { 15556 for (FixItHint &H : ConvHints.Hints) 15557 FDiag << H; 15558 } else { 15559 FDiag << Hint; 15560 } 15561 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 15562 15563 if (MayHaveFunctionDiff) 15564 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 15565 15566 Diag(Loc, FDiag); 15567 if ((DiagKind == diag::warn_incompatible_qualified_id || 15568 DiagKind == diag::err_incompatible_qualified_id) && 15569 PDecl && IFace && !IFace->hasDefinition()) 15570 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 15571 << IFace << PDecl; 15572 15573 if (SecondType == Context.OverloadTy) 15574 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 15575 FirstType, /*TakingAddress=*/true); 15576 15577 if (CheckInferredResultType) 15578 EmitRelatedResultTypeNote(SrcExpr); 15579 15580 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 15581 EmitRelatedResultTypeNoteForReturn(DstType); 15582 15583 if (Complained) 15584 *Complained = true; 15585 return isInvalid; 15586 } 15587 15588 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15589 llvm::APSInt *Result) { 15590 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 15591 public: 15592 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 15593 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 15594 } 15595 } Diagnoser; 15596 15597 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 15598 } 15599 15600 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15601 llvm::APSInt *Result, 15602 unsigned DiagID, 15603 bool AllowFold) { 15604 class IDDiagnoser : public VerifyICEDiagnoser { 15605 unsigned DiagID; 15606 15607 public: 15608 IDDiagnoser(unsigned DiagID) 15609 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 15610 15611 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 15612 S.Diag(Loc, DiagID) << SR; 15613 } 15614 } Diagnoser(DiagID); 15615 15616 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 15617 } 15618 15619 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 15620 SourceRange SR) { 15621 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 15622 } 15623 15624 ExprResult 15625 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 15626 VerifyICEDiagnoser &Diagnoser, 15627 bool AllowFold) { 15628 SourceLocation DiagLoc = E->getBeginLoc(); 15629 15630 if (getLangOpts().CPlusPlus11) { 15631 // C++11 [expr.const]p5: 15632 // If an expression of literal class type is used in a context where an 15633 // integral constant expression is required, then that class type shall 15634 // have a single non-explicit conversion function to an integral or 15635 // unscoped enumeration type 15636 ExprResult Converted; 15637 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 15638 public: 15639 CXX11ConvertDiagnoser(bool Silent) 15640 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 15641 Silent, true) {} 15642 15643 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 15644 QualType T) override { 15645 return S.Diag(Loc, diag::err_ice_not_integral) << T; 15646 } 15647 15648 SemaDiagnosticBuilder diagnoseIncomplete( 15649 Sema &S, SourceLocation Loc, QualType T) override { 15650 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 15651 } 15652 15653 SemaDiagnosticBuilder diagnoseExplicitConv( 15654 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15655 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 15656 } 15657 15658 SemaDiagnosticBuilder noteExplicitConv( 15659 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15660 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15661 << ConvTy->isEnumeralType() << ConvTy; 15662 } 15663 15664 SemaDiagnosticBuilder diagnoseAmbiguous( 15665 Sema &S, SourceLocation Loc, QualType T) override { 15666 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 15667 } 15668 15669 SemaDiagnosticBuilder noteAmbiguous( 15670 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15671 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15672 << ConvTy->isEnumeralType() << ConvTy; 15673 } 15674 15675 SemaDiagnosticBuilder diagnoseConversion( 15676 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15677 llvm_unreachable("conversion functions are permitted"); 15678 } 15679 } ConvertDiagnoser(Diagnoser.Suppress); 15680 15681 Converted = PerformContextualImplicitConversion(DiagLoc, E, 15682 ConvertDiagnoser); 15683 if (Converted.isInvalid()) 15684 return Converted; 15685 E = Converted.get(); 15686 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 15687 return ExprError(); 15688 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15689 // An ICE must be of integral or unscoped enumeration type. 15690 if (!Diagnoser.Suppress) 15691 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15692 return ExprError(); 15693 } 15694 15695 ExprResult RValueExpr = DefaultLvalueConversion(E); 15696 if (RValueExpr.isInvalid()) 15697 return ExprError(); 15698 15699 E = RValueExpr.get(); 15700 15701 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 15702 // in the non-ICE case. 15703 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 15704 if (Result) 15705 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 15706 if (!isa<ConstantExpr>(E)) 15707 E = ConstantExpr::Create(Context, E); 15708 return E; 15709 } 15710 15711 Expr::EvalResult EvalResult; 15712 SmallVector<PartialDiagnosticAt, 8> Notes; 15713 EvalResult.Diag = &Notes; 15714 15715 // Try to evaluate the expression, and produce diagnostics explaining why it's 15716 // not a constant expression as a side-effect. 15717 bool Folded = 15718 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 15719 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 15720 15721 if (!isa<ConstantExpr>(E)) 15722 E = ConstantExpr::Create(Context, E, EvalResult.Val); 15723 15724 // In C++11, we can rely on diagnostics being produced for any expression 15725 // which is not a constant expression. If no diagnostics were produced, then 15726 // this is a constant expression. 15727 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 15728 if (Result) 15729 *Result = EvalResult.Val.getInt(); 15730 return E; 15731 } 15732 15733 // If our only note is the usual "invalid subexpression" note, just point 15734 // the caret at its location rather than producing an essentially 15735 // redundant note. 15736 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 15737 diag::note_invalid_subexpr_in_const_expr) { 15738 DiagLoc = Notes[0].first; 15739 Notes.clear(); 15740 } 15741 15742 if (!Folded || !AllowFold) { 15743 if (!Diagnoser.Suppress) { 15744 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15745 for (const PartialDiagnosticAt &Note : Notes) 15746 Diag(Note.first, Note.second); 15747 } 15748 15749 return ExprError(); 15750 } 15751 15752 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 15753 for (const PartialDiagnosticAt &Note : Notes) 15754 Diag(Note.first, Note.second); 15755 15756 if (Result) 15757 *Result = EvalResult.Val.getInt(); 15758 return E; 15759 } 15760 15761 namespace { 15762 // Handle the case where we conclude a expression which we speculatively 15763 // considered to be unevaluated is actually evaluated. 15764 class TransformToPE : public TreeTransform<TransformToPE> { 15765 typedef TreeTransform<TransformToPE> BaseTransform; 15766 15767 public: 15768 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 15769 15770 // Make sure we redo semantic analysis 15771 bool AlwaysRebuild() { return true; } 15772 bool ReplacingOriginal() { return true; } 15773 15774 // We need to special-case DeclRefExprs referring to FieldDecls which 15775 // are not part of a member pointer formation; normal TreeTransforming 15776 // doesn't catch this case because of the way we represent them in the AST. 15777 // FIXME: This is a bit ugly; is it really the best way to handle this 15778 // case? 15779 // 15780 // Error on DeclRefExprs referring to FieldDecls. 15781 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 15782 if (isa<FieldDecl>(E->getDecl()) && 15783 !SemaRef.isUnevaluatedContext()) 15784 return SemaRef.Diag(E->getLocation(), 15785 diag::err_invalid_non_static_member_use) 15786 << E->getDecl() << E->getSourceRange(); 15787 15788 return BaseTransform::TransformDeclRefExpr(E); 15789 } 15790 15791 // Exception: filter out member pointer formation 15792 ExprResult TransformUnaryOperator(UnaryOperator *E) { 15793 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 15794 return E; 15795 15796 return BaseTransform::TransformUnaryOperator(E); 15797 } 15798 15799 // The body of a lambda-expression is in a separate expression evaluation 15800 // context so never needs to be transformed. 15801 // FIXME: Ideally we wouldn't transform the closure type either, and would 15802 // just recreate the capture expressions and lambda expression. 15803 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 15804 return SkipLambdaBody(E, Body); 15805 } 15806 }; 15807 } 15808 15809 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 15810 assert(isUnevaluatedContext() && 15811 "Should only transform unevaluated expressions"); 15812 ExprEvalContexts.back().Context = 15813 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 15814 if (isUnevaluatedContext()) 15815 return E; 15816 return TransformToPE(*this).TransformExpr(E); 15817 } 15818 15819 void 15820 Sema::PushExpressionEvaluationContext( 15821 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 15822 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15823 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 15824 LambdaContextDecl, ExprContext); 15825 Cleanup.reset(); 15826 if (!MaybeODRUseExprs.empty()) 15827 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 15828 } 15829 15830 void 15831 Sema::PushExpressionEvaluationContext( 15832 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 15833 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15834 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 15835 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 15836 } 15837 15838 namespace { 15839 15840 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 15841 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 15842 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 15843 if (E->getOpcode() == UO_Deref) 15844 return CheckPossibleDeref(S, E->getSubExpr()); 15845 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 15846 return CheckPossibleDeref(S, E->getBase()); 15847 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 15848 return CheckPossibleDeref(S, E->getBase()); 15849 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 15850 QualType Inner; 15851 QualType Ty = E->getType(); 15852 if (const auto *Ptr = Ty->getAs<PointerType>()) 15853 Inner = Ptr->getPointeeType(); 15854 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 15855 Inner = Arr->getElementType(); 15856 else 15857 return nullptr; 15858 15859 if (Inner->hasAttr(attr::NoDeref)) 15860 return E; 15861 } 15862 return nullptr; 15863 } 15864 15865 } // namespace 15866 15867 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 15868 for (const Expr *E : Rec.PossibleDerefs) { 15869 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 15870 if (DeclRef) { 15871 const ValueDecl *Decl = DeclRef->getDecl(); 15872 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 15873 << Decl->getName() << E->getSourceRange(); 15874 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 15875 } else { 15876 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 15877 << E->getSourceRange(); 15878 } 15879 } 15880 Rec.PossibleDerefs.clear(); 15881 } 15882 15883 /// Check whether E, which is either a discarded-value expression or an 15884 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 15885 /// and if so, remove it from the list of volatile-qualified assignments that 15886 /// we are going to warn are deprecated. 15887 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 15888 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 15889 return; 15890 15891 // Note: ignoring parens here is not justified by the standard rules, but 15892 // ignoring parentheses seems like a more reasonable approach, and this only 15893 // drives a deprecation warning so doesn't affect conformance. 15894 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 15895 if (BO->getOpcode() == BO_Assign) { 15896 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 15897 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 15898 LHSs.end()); 15899 } 15900 } 15901 } 15902 15903 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 15904 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 15905 RebuildingImmediateInvocation) 15906 return E; 15907 15908 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 15909 /// It's OK if this fails; we'll also remove this in 15910 /// HandleImmediateInvocations, but catching it here allows us to avoid 15911 /// walking the AST looking for it in simple cases. 15912 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 15913 if (auto *DeclRef = 15914 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 15915 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 15916 15917 E = MaybeCreateExprWithCleanups(E); 15918 15919 ConstantExpr *Res = ConstantExpr::Create( 15920 getASTContext(), E.get(), 15921 ConstantExpr::getStorageKind(E.get()->getType().getTypePtr(), 15922 getASTContext()), 15923 /*IsImmediateInvocation*/ true); 15924 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 15925 return Res; 15926 } 15927 15928 static void EvaluateAndDiagnoseImmediateInvocation( 15929 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 15930 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 15931 Expr::EvalResult Eval; 15932 Eval.Diag = &Notes; 15933 ConstantExpr *CE = Candidate.getPointer(); 15934 bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen, 15935 SemaRef.getASTContext(), true); 15936 if (!Result || !Notes.empty()) { 15937 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 15938 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 15939 InnerExpr = FunctionalCast->getSubExpr(); 15940 FunctionDecl *FD = nullptr; 15941 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 15942 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 15943 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 15944 FD = Call->getConstructor(); 15945 else 15946 llvm_unreachable("unhandled decl kind"); 15947 assert(FD->isConsteval()); 15948 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 15949 for (auto &Note : Notes) 15950 SemaRef.Diag(Note.first, Note.second); 15951 return; 15952 } 15953 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 15954 } 15955 15956 static void RemoveNestedImmediateInvocation( 15957 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 15958 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 15959 struct ComplexRemove : TreeTransform<ComplexRemove> { 15960 using Base = TreeTransform<ComplexRemove>; 15961 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 15962 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 15963 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 15964 CurrentII; 15965 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 15966 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 15967 SmallVector<Sema::ImmediateInvocationCandidate, 15968 4>::reverse_iterator Current) 15969 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 15970 void RemoveImmediateInvocation(ConstantExpr* E) { 15971 auto It = std::find_if(CurrentII, IISet.rend(), 15972 [E](Sema::ImmediateInvocationCandidate Elem) { 15973 return Elem.getPointer() == E; 15974 }); 15975 assert(It != IISet.rend() && 15976 "ConstantExpr marked IsImmediateInvocation should " 15977 "be present"); 15978 It->setInt(1); // Mark as deleted 15979 } 15980 ExprResult TransformConstantExpr(ConstantExpr *E) { 15981 if (!E->isImmediateInvocation()) 15982 return Base::TransformConstantExpr(E); 15983 RemoveImmediateInvocation(E); 15984 return Base::TransformExpr(E->getSubExpr()); 15985 } 15986 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 15987 /// we need to remove its DeclRefExpr from the DRSet. 15988 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 15989 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 15990 return Base::TransformCXXOperatorCallExpr(E); 15991 } 15992 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 15993 /// here. 15994 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 15995 if (!Init) 15996 return Init; 15997 /// ConstantExpr are the first layer of implicit node to be removed so if 15998 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 15999 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16000 if (CE->isImmediateInvocation()) 16001 RemoveImmediateInvocation(CE); 16002 return Base::TransformInitializer(Init, NotCopyInit); 16003 } 16004 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16005 DRSet.erase(E); 16006 return E; 16007 } 16008 bool AlwaysRebuild() { return false; } 16009 bool ReplacingOriginal() { return true; } 16010 bool AllowSkippingCXXConstructExpr() { 16011 bool Res = AllowSkippingFirstCXXConstructExpr; 16012 AllowSkippingFirstCXXConstructExpr = true; 16013 return Res; 16014 } 16015 bool AllowSkippingFirstCXXConstructExpr = true; 16016 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16017 Rec.ImmediateInvocationCandidates, It); 16018 16019 /// CXXConstructExpr with a single argument are getting skipped by 16020 /// TreeTransform in some situtation because they could be implicit. This 16021 /// can only occur for the top-level CXXConstructExpr because it is used 16022 /// nowhere in the expression being transformed therefore will not be rebuilt. 16023 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16024 /// skipping the first CXXConstructExpr. 16025 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16026 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16027 16028 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16029 assert(Res.isUsable()); 16030 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16031 It->getPointer()->setSubExpr(Res.get()); 16032 } 16033 16034 static void 16035 HandleImmediateInvocations(Sema &SemaRef, 16036 Sema::ExpressionEvaluationContextRecord &Rec) { 16037 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16038 Rec.ReferenceToConsteval.size() == 0) || 16039 SemaRef.RebuildingImmediateInvocation) 16040 return; 16041 16042 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16043 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16044 /// need to remove ReferenceToConsteval in the immediate invocation. 16045 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16046 16047 /// Prevent sema calls during the tree transform from adding pointers that 16048 /// are already in the sets. 16049 llvm::SaveAndRestore<bool> DisableIITracking( 16050 SemaRef.RebuildingImmediateInvocation, true); 16051 16052 /// Prevent diagnostic during tree transfrom as they are duplicates 16053 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16054 16055 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16056 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16057 if (!It->getInt()) 16058 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16059 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16060 Rec.ReferenceToConsteval.size()) { 16061 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16062 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16063 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16064 bool VisitDeclRefExpr(DeclRefExpr *E) { 16065 DRSet.erase(E); 16066 return DRSet.size(); 16067 } 16068 } Visitor(Rec.ReferenceToConsteval); 16069 Visitor.TraverseStmt( 16070 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16071 } 16072 for (auto CE : Rec.ImmediateInvocationCandidates) 16073 if (!CE.getInt()) 16074 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16075 for (auto DR : Rec.ReferenceToConsteval) { 16076 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16077 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16078 << FD; 16079 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16080 } 16081 } 16082 16083 void Sema::PopExpressionEvaluationContext() { 16084 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16085 unsigned NumTypos = Rec.NumTypos; 16086 16087 if (!Rec.Lambdas.empty()) { 16088 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16089 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 16090 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 16091 unsigned D; 16092 if (Rec.isUnevaluated()) { 16093 // C++11 [expr.prim.lambda]p2: 16094 // A lambda-expression shall not appear in an unevaluated operand 16095 // (Clause 5). 16096 D = diag::err_lambda_unevaluated_operand; 16097 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16098 // C++1y [expr.const]p2: 16099 // A conditional-expression e is a core constant expression unless the 16100 // evaluation of e, following the rules of the abstract machine, would 16101 // evaluate [...] a lambda-expression. 16102 D = diag::err_lambda_in_constant_expression; 16103 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16104 // C++17 [expr.prim.lamda]p2: 16105 // A lambda-expression shall not appear [...] in a template-argument. 16106 D = diag::err_lambda_in_invalid_context; 16107 } else 16108 llvm_unreachable("Couldn't infer lambda error message."); 16109 16110 for (const auto *L : Rec.Lambdas) 16111 Diag(L->getBeginLoc(), D); 16112 } 16113 } 16114 16115 WarnOnPendingNoDerefs(Rec); 16116 HandleImmediateInvocations(*this, Rec); 16117 16118 // Warn on any volatile-qualified simple-assignments that are not discarded- 16119 // value expressions nor unevaluated operands (those cases get removed from 16120 // this list by CheckUnusedVolatileAssignment). 16121 for (auto *BO : Rec.VolatileAssignmentLHSs) 16122 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16123 << BO->getType(); 16124 16125 // When are coming out of an unevaluated context, clear out any 16126 // temporaries that we may have created as part of the evaluation of 16127 // the expression in that context: they aren't relevant because they 16128 // will never be constructed. 16129 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16130 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16131 ExprCleanupObjects.end()); 16132 Cleanup = Rec.ParentCleanup; 16133 CleanupVarDeclMarking(); 16134 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16135 // Otherwise, merge the contexts together. 16136 } else { 16137 Cleanup.mergeFrom(Rec.ParentCleanup); 16138 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16139 Rec.SavedMaybeODRUseExprs.end()); 16140 } 16141 16142 // Pop the current expression evaluation context off the stack. 16143 ExprEvalContexts.pop_back(); 16144 16145 // The global expression evaluation context record is never popped. 16146 ExprEvalContexts.back().NumTypos += NumTypos; 16147 } 16148 16149 void Sema::DiscardCleanupsInEvaluationContext() { 16150 ExprCleanupObjects.erase( 16151 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16152 ExprCleanupObjects.end()); 16153 Cleanup.reset(); 16154 MaybeODRUseExprs.clear(); 16155 } 16156 16157 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16158 ExprResult Result = CheckPlaceholderExpr(E); 16159 if (Result.isInvalid()) 16160 return ExprError(); 16161 E = Result.get(); 16162 if (!E->getType()->isVariablyModifiedType()) 16163 return E; 16164 return TransformToPotentiallyEvaluated(E); 16165 } 16166 16167 /// Are we in a context that is potentially constant evaluated per C++20 16168 /// [expr.const]p12? 16169 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16170 /// C++2a [expr.const]p12: 16171 // An expression or conversion is potentially constant evaluated if it is 16172 switch (SemaRef.ExprEvalContexts.back().Context) { 16173 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16174 // -- a manifestly constant-evaluated expression, 16175 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16176 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16177 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16178 // -- a potentially-evaluated expression, 16179 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16180 // -- an immediate subexpression of a braced-init-list, 16181 16182 // -- [FIXME] an expression of the form & cast-expression that occurs 16183 // within a templated entity 16184 // -- a subexpression of one of the above that is not a subexpression of 16185 // a nested unevaluated operand. 16186 return true; 16187 16188 case Sema::ExpressionEvaluationContext::Unevaluated: 16189 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16190 // Expressions in this context are never evaluated. 16191 return false; 16192 } 16193 llvm_unreachable("Invalid context"); 16194 } 16195 16196 /// Return true if this function has a calling convention that requires mangling 16197 /// in the size of the parameter pack. 16198 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16199 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16200 // we don't need parameter type sizes. 16201 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16202 if (!TT.isOSWindows() || !TT.isX86()) 16203 return false; 16204 16205 // If this is C++ and this isn't an extern "C" function, parameters do not 16206 // need to be complete. In this case, C++ mangling will apply, which doesn't 16207 // use the size of the parameters. 16208 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16209 return false; 16210 16211 // Stdcall, fastcall, and vectorcall need this special treatment. 16212 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16213 switch (CC) { 16214 case CC_X86StdCall: 16215 case CC_X86FastCall: 16216 case CC_X86VectorCall: 16217 return true; 16218 default: 16219 break; 16220 } 16221 return false; 16222 } 16223 16224 /// Require that all of the parameter types of function be complete. Normally, 16225 /// parameter types are only required to be complete when a function is called 16226 /// or defined, but to mangle functions with certain calling conventions, the 16227 /// mangler needs to know the size of the parameter list. In this situation, 16228 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16229 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16230 /// result in a linker error. Clang doesn't implement this behavior, and instead 16231 /// attempts to error at compile time. 16232 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16233 SourceLocation Loc) { 16234 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16235 FunctionDecl *FD; 16236 ParmVarDecl *Param; 16237 16238 public: 16239 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16240 : FD(FD), Param(Param) {} 16241 16242 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16243 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16244 StringRef CCName; 16245 switch (CC) { 16246 case CC_X86StdCall: 16247 CCName = "stdcall"; 16248 break; 16249 case CC_X86FastCall: 16250 CCName = "fastcall"; 16251 break; 16252 case CC_X86VectorCall: 16253 CCName = "vectorcall"; 16254 break; 16255 default: 16256 llvm_unreachable("CC does not need mangling"); 16257 } 16258 16259 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16260 << Param->getDeclName() << FD->getDeclName() << CCName; 16261 } 16262 }; 16263 16264 for (ParmVarDecl *Param : FD->parameters()) { 16265 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16266 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16267 } 16268 } 16269 16270 namespace { 16271 enum class OdrUseContext { 16272 /// Declarations in this context are not odr-used. 16273 None, 16274 /// Declarations in this context are formally odr-used, but this is a 16275 /// dependent context. 16276 Dependent, 16277 /// Declarations in this context are odr-used but not actually used (yet). 16278 FormallyOdrUsed, 16279 /// Declarations in this context are used. 16280 Used 16281 }; 16282 } 16283 16284 /// Are we within a context in which references to resolved functions or to 16285 /// variables result in odr-use? 16286 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16287 OdrUseContext Result; 16288 16289 switch (SemaRef.ExprEvalContexts.back().Context) { 16290 case Sema::ExpressionEvaluationContext::Unevaluated: 16291 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16292 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16293 return OdrUseContext::None; 16294 16295 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16296 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16297 Result = OdrUseContext::Used; 16298 break; 16299 16300 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16301 Result = OdrUseContext::FormallyOdrUsed; 16302 break; 16303 16304 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16305 // A default argument formally results in odr-use, but doesn't actually 16306 // result in a use in any real sense until it itself is used. 16307 Result = OdrUseContext::FormallyOdrUsed; 16308 break; 16309 } 16310 16311 if (SemaRef.CurContext->isDependentContext()) 16312 return OdrUseContext::Dependent; 16313 16314 return Result; 16315 } 16316 16317 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 16318 return Func->isConstexpr() && 16319 (Func->isImplicitlyInstantiable() || !Func->isUserProvided()); 16320 } 16321 16322 /// Mark a function referenced, and check whether it is odr-used 16323 /// (C++ [basic.def.odr]p2, C99 6.9p3) 16324 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 16325 bool MightBeOdrUse) { 16326 assert(Func && "No function?"); 16327 16328 Func->setReferenced(); 16329 16330 // Recursive functions aren't really used until they're used from some other 16331 // context. 16332 bool IsRecursiveCall = CurContext == Func; 16333 16334 // C++11 [basic.def.odr]p3: 16335 // A function whose name appears as a potentially-evaluated expression is 16336 // odr-used if it is the unique lookup result or the selected member of a 16337 // set of overloaded functions [...]. 16338 // 16339 // We (incorrectly) mark overload resolution as an unevaluated context, so we 16340 // can just check that here. 16341 OdrUseContext OdrUse = 16342 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 16343 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 16344 OdrUse = OdrUseContext::FormallyOdrUsed; 16345 16346 // Trivial default constructors and destructors are never actually used. 16347 // FIXME: What about other special members? 16348 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 16349 OdrUse == OdrUseContext::Used) { 16350 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 16351 if (Constructor->isDefaultConstructor()) 16352 OdrUse = OdrUseContext::FormallyOdrUsed; 16353 if (isa<CXXDestructorDecl>(Func)) 16354 OdrUse = OdrUseContext::FormallyOdrUsed; 16355 } 16356 16357 // C++20 [expr.const]p12: 16358 // A function [...] is needed for constant evaluation if it is [...] a 16359 // constexpr function that is named by an expression that is potentially 16360 // constant evaluated 16361 bool NeededForConstantEvaluation = 16362 isPotentiallyConstantEvaluatedContext(*this) && 16363 isImplicitlyDefinableConstexprFunction(Func); 16364 16365 // Determine whether we require a function definition to exist, per 16366 // C++11 [temp.inst]p3: 16367 // Unless a function template specialization has been explicitly 16368 // instantiated or explicitly specialized, the function template 16369 // specialization is implicitly instantiated when the specialization is 16370 // referenced in a context that requires a function definition to exist. 16371 // C++20 [temp.inst]p7: 16372 // The existence of a definition of a [...] function is considered to 16373 // affect the semantics of the program if the [...] function is needed for 16374 // constant evaluation by an expression 16375 // C++20 [basic.def.odr]p10: 16376 // Every program shall contain exactly one definition of every non-inline 16377 // function or variable that is odr-used in that program outside of a 16378 // discarded statement 16379 // C++20 [special]p1: 16380 // The implementation will implicitly define [defaulted special members] 16381 // if they are odr-used or needed for constant evaluation. 16382 // 16383 // Note that we skip the implicit instantiation of templates that are only 16384 // used in unused default arguments or by recursive calls to themselves. 16385 // This is formally non-conforming, but seems reasonable in practice. 16386 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 16387 NeededForConstantEvaluation); 16388 16389 // C++14 [temp.expl.spec]p6: 16390 // If a template [...] is explicitly specialized then that specialization 16391 // shall be declared before the first use of that specialization that would 16392 // cause an implicit instantiation to take place, in every translation unit 16393 // in which such a use occurs 16394 if (NeedDefinition && 16395 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 16396 Func->getMemberSpecializationInfo())) 16397 checkSpecializationVisibility(Loc, Func); 16398 16399 if (getLangOpts().CUDA) 16400 CheckCUDACall(Loc, Func); 16401 16402 // If we need a definition, try to create one. 16403 if (NeedDefinition && !Func->getBody()) { 16404 runWithSufficientStackSpace(Loc, [&] { 16405 if (CXXConstructorDecl *Constructor = 16406 dyn_cast<CXXConstructorDecl>(Func)) { 16407 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 16408 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 16409 if (Constructor->isDefaultConstructor()) { 16410 if (Constructor->isTrivial() && 16411 !Constructor->hasAttr<DLLExportAttr>()) 16412 return; 16413 DefineImplicitDefaultConstructor(Loc, Constructor); 16414 } else if (Constructor->isCopyConstructor()) { 16415 DefineImplicitCopyConstructor(Loc, Constructor); 16416 } else if (Constructor->isMoveConstructor()) { 16417 DefineImplicitMoveConstructor(Loc, Constructor); 16418 } 16419 } else if (Constructor->getInheritedConstructor()) { 16420 DefineInheritingConstructor(Loc, Constructor); 16421 } 16422 } else if (CXXDestructorDecl *Destructor = 16423 dyn_cast<CXXDestructorDecl>(Func)) { 16424 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 16425 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 16426 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 16427 return; 16428 DefineImplicitDestructor(Loc, Destructor); 16429 } 16430 if (Destructor->isVirtual() && getLangOpts().AppleKext) 16431 MarkVTableUsed(Loc, Destructor->getParent()); 16432 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 16433 if (MethodDecl->isOverloadedOperator() && 16434 MethodDecl->getOverloadedOperator() == OO_Equal) { 16435 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 16436 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 16437 if (MethodDecl->isCopyAssignmentOperator()) 16438 DefineImplicitCopyAssignment(Loc, MethodDecl); 16439 else if (MethodDecl->isMoveAssignmentOperator()) 16440 DefineImplicitMoveAssignment(Loc, MethodDecl); 16441 } 16442 } else if (isa<CXXConversionDecl>(MethodDecl) && 16443 MethodDecl->getParent()->isLambda()) { 16444 CXXConversionDecl *Conversion = 16445 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 16446 if (Conversion->isLambdaToBlockPointerConversion()) 16447 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 16448 else 16449 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 16450 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 16451 MarkVTableUsed(Loc, MethodDecl->getParent()); 16452 } 16453 16454 if (Func->isDefaulted() && !Func->isDeleted()) { 16455 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 16456 if (DCK != DefaultedComparisonKind::None) 16457 DefineDefaultedComparison(Loc, Func, DCK); 16458 } 16459 16460 // Implicit instantiation of function templates and member functions of 16461 // class templates. 16462 if (Func->isImplicitlyInstantiable()) { 16463 TemplateSpecializationKind TSK = 16464 Func->getTemplateSpecializationKindForInstantiation(); 16465 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 16466 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16467 if (FirstInstantiation) { 16468 PointOfInstantiation = Loc; 16469 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16470 } else if (TSK != TSK_ImplicitInstantiation) { 16471 // Use the point of use as the point of instantiation, instead of the 16472 // point of explicit instantiation (which we track as the actual point 16473 // of instantiation). This gives better backtraces in diagnostics. 16474 PointOfInstantiation = Loc; 16475 } 16476 16477 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 16478 Func->isConstexpr()) { 16479 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 16480 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 16481 CodeSynthesisContexts.size()) 16482 PendingLocalImplicitInstantiations.push_back( 16483 std::make_pair(Func, PointOfInstantiation)); 16484 else if (Func->isConstexpr()) 16485 // Do not defer instantiations of constexpr functions, to avoid the 16486 // expression evaluator needing to call back into Sema if it sees a 16487 // call to such a function. 16488 InstantiateFunctionDefinition(PointOfInstantiation, Func); 16489 else { 16490 Func->setInstantiationIsPending(true); 16491 PendingInstantiations.push_back( 16492 std::make_pair(Func, PointOfInstantiation)); 16493 // Notify the consumer that a function was implicitly instantiated. 16494 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 16495 } 16496 } 16497 } else { 16498 // Walk redefinitions, as some of them may be instantiable. 16499 for (auto i : Func->redecls()) { 16500 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 16501 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 16502 } 16503 } 16504 }); 16505 } 16506 16507 // C++14 [except.spec]p17: 16508 // An exception-specification is considered to be needed when: 16509 // - the function is odr-used or, if it appears in an unevaluated operand, 16510 // would be odr-used if the expression were potentially-evaluated; 16511 // 16512 // Note, we do this even if MightBeOdrUse is false. That indicates that the 16513 // function is a pure virtual function we're calling, and in that case the 16514 // function was selected by overload resolution and we need to resolve its 16515 // exception specification for a different reason. 16516 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 16517 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 16518 ResolveExceptionSpec(Loc, FPT); 16519 16520 // If this is the first "real" use, act on that. 16521 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 16522 // Keep track of used but undefined functions. 16523 if (!Func->isDefined()) { 16524 if (mightHaveNonExternalLinkage(Func)) 16525 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16526 else if (Func->getMostRecentDecl()->isInlined() && 16527 !LangOpts.GNUInline && 16528 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 16529 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16530 else if (isExternalWithNoLinkageType(Func)) 16531 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16532 } 16533 16534 // Some x86 Windows calling conventions mangle the size of the parameter 16535 // pack into the name. Computing the size of the parameters requires the 16536 // parameter types to be complete. Check that now. 16537 if (funcHasParameterSizeMangling(*this, Func)) 16538 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 16539 16540 // In the MS C++ ABI, the compiler emits destructor variants where they are 16541 // used. If the destructor is used here but defined elsewhere, mark the 16542 // virtual base destructors referenced. If those virtual base destructors 16543 // are inline, this will ensure they are defined when emitting the complete 16544 // destructor variant. This checking may be redundant if the destructor is 16545 // provided later in this TU. 16546 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 16547 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 16548 CXXRecordDecl *Parent = Dtor->getParent(); 16549 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 16550 CheckCompleteDestructorVariant(Loc, Dtor); 16551 } 16552 } 16553 16554 Func->markUsed(Context); 16555 } 16556 } 16557 16558 /// Directly mark a variable odr-used. Given a choice, prefer to use 16559 /// MarkVariableReferenced since it does additional checks and then 16560 /// calls MarkVarDeclODRUsed. 16561 /// If the variable must be captured: 16562 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 16563 /// - else capture it in the DeclContext that maps to the 16564 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 16565 static void 16566 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 16567 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 16568 // Keep track of used but undefined variables. 16569 // FIXME: We shouldn't suppress this warning for static data members. 16570 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 16571 (!Var->isExternallyVisible() || Var->isInline() || 16572 SemaRef.isExternalWithNoLinkageType(Var)) && 16573 !(Var->isStaticDataMember() && Var->hasInit())) { 16574 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 16575 if (old.isInvalid()) 16576 old = Loc; 16577 } 16578 QualType CaptureType, DeclRefType; 16579 if (SemaRef.LangOpts.OpenMP) 16580 SemaRef.tryCaptureOpenMPLambdas(Var); 16581 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 16582 /*EllipsisLoc*/ SourceLocation(), 16583 /*BuildAndDiagnose*/ true, 16584 CaptureType, DeclRefType, 16585 FunctionScopeIndexToStopAt); 16586 16587 Var->markUsed(SemaRef.Context); 16588 } 16589 16590 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 16591 SourceLocation Loc, 16592 unsigned CapturingScopeIndex) { 16593 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 16594 } 16595 16596 static void 16597 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 16598 ValueDecl *var, DeclContext *DC) { 16599 DeclContext *VarDC = var->getDeclContext(); 16600 16601 // If the parameter still belongs to the translation unit, then 16602 // we're actually just using one parameter in the declaration of 16603 // the next. 16604 if (isa<ParmVarDecl>(var) && 16605 isa<TranslationUnitDecl>(VarDC)) 16606 return; 16607 16608 // For C code, don't diagnose about capture if we're not actually in code 16609 // right now; it's impossible to write a non-constant expression outside of 16610 // function context, so we'll get other (more useful) diagnostics later. 16611 // 16612 // For C++, things get a bit more nasty... it would be nice to suppress this 16613 // diagnostic for certain cases like using a local variable in an array bound 16614 // for a member of a local class, but the correct predicate is not obvious. 16615 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 16616 return; 16617 16618 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 16619 unsigned ContextKind = 3; // unknown 16620 if (isa<CXXMethodDecl>(VarDC) && 16621 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 16622 ContextKind = 2; 16623 } else if (isa<FunctionDecl>(VarDC)) { 16624 ContextKind = 0; 16625 } else if (isa<BlockDecl>(VarDC)) { 16626 ContextKind = 1; 16627 } 16628 16629 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 16630 << var << ValueKind << ContextKind << VarDC; 16631 S.Diag(var->getLocation(), diag::note_entity_declared_at) 16632 << var; 16633 16634 // FIXME: Add additional diagnostic info about class etc. which prevents 16635 // capture. 16636 } 16637 16638 16639 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 16640 bool &SubCapturesAreNested, 16641 QualType &CaptureType, 16642 QualType &DeclRefType) { 16643 // Check whether we've already captured it. 16644 if (CSI->CaptureMap.count(Var)) { 16645 // If we found a capture, any subcaptures are nested. 16646 SubCapturesAreNested = true; 16647 16648 // Retrieve the capture type for this variable. 16649 CaptureType = CSI->getCapture(Var).getCaptureType(); 16650 16651 // Compute the type of an expression that refers to this variable. 16652 DeclRefType = CaptureType.getNonReferenceType(); 16653 16654 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 16655 // are mutable in the sense that user can change their value - they are 16656 // private instances of the captured declarations. 16657 const Capture &Cap = CSI->getCapture(Var); 16658 if (Cap.isCopyCapture() && 16659 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 16660 !(isa<CapturedRegionScopeInfo>(CSI) && 16661 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 16662 DeclRefType.addConst(); 16663 return true; 16664 } 16665 return false; 16666 } 16667 16668 // Only block literals, captured statements, and lambda expressions can 16669 // capture; other scopes don't work. 16670 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 16671 SourceLocation Loc, 16672 const bool Diagnose, Sema &S) { 16673 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 16674 return getLambdaAwareParentOfDeclContext(DC); 16675 else if (Var->hasLocalStorage()) { 16676 if (Diagnose) 16677 diagnoseUncapturableValueReference(S, Loc, Var, DC); 16678 } 16679 return nullptr; 16680 } 16681 16682 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16683 // certain types of variables (unnamed, variably modified types etc.) 16684 // so check for eligibility. 16685 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 16686 SourceLocation Loc, 16687 const bool Diagnose, Sema &S) { 16688 16689 bool IsBlock = isa<BlockScopeInfo>(CSI); 16690 bool IsLambda = isa<LambdaScopeInfo>(CSI); 16691 16692 // Lambdas are not allowed to capture unnamed variables 16693 // (e.g. anonymous unions). 16694 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 16695 // assuming that's the intent. 16696 if (IsLambda && !Var->getDeclName()) { 16697 if (Diagnose) { 16698 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 16699 S.Diag(Var->getLocation(), diag::note_declared_at); 16700 } 16701 return false; 16702 } 16703 16704 // Prohibit variably-modified types in blocks; they're difficult to deal with. 16705 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 16706 if (Diagnose) { 16707 S.Diag(Loc, diag::err_ref_vm_type); 16708 S.Diag(Var->getLocation(), diag::note_previous_decl) 16709 << Var->getDeclName(); 16710 } 16711 return false; 16712 } 16713 // Prohibit structs with flexible array members too. 16714 // We cannot capture what is in the tail end of the struct. 16715 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 16716 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 16717 if (Diagnose) { 16718 if (IsBlock) 16719 S.Diag(Loc, diag::err_ref_flexarray_type); 16720 else 16721 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 16722 << Var->getDeclName(); 16723 S.Diag(Var->getLocation(), diag::note_previous_decl) 16724 << Var->getDeclName(); 16725 } 16726 return false; 16727 } 16728 } 16729 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 16730 // Lambdas and captured statements are not allowed to capture __block 16731 // variables; they don't support the expected semantics. 16732 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 16733 if (Diagnose) { 16734 S.Diag(Loc, diag::err_capture_block_variable) 16735 << Var->getDeclName() << !IsLambda; 16736 S.Diag(Var->getLocation(), diag::note_previous_decl) 16737 << Var->getDeclName(); 16738 } 16739 return false; 16740 } 16741 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 16742 if (S.getLangOpts().OpenCL && IsBlock && 16743 Var->getType()->isBlockPointerType()) { 16744 if (Diagnose) 16745 S.Diag(Loc, diag::err_opencl_block_ref_block); 16746 return false; 16747 } 16748 16749 return true; 16750 } 16751 16752 // Returns true if the capture by block was successful. 16753 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 16754 SourceLocation Loc, 16755 const bool BuildAndDiagnose, 16756 QualType &CaptureType, 16757 QualType &DeclRefType, 16758 const bool Nested, 16759 Sema &S, bool Invalid) { 16760 bool ByRef = false; 16761 16762 // Blocks are not allowed to capture arrays, excepting OpenCL. 16763 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 16764 // (decayed to pointers). 16765 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 16766 if (BuildAndDiagnose) { 16767 S.Diag(Loc, diag::err_ref_array_type); 16768 S.Diag(Var->getLocation(), diag::note_previous_decl) 16769 << Var->getDeclName(); 16770 Invalid = true; 16771 } else { 16772 return false; 16773 } 16774 } 16775 16776 // Forbid the block-capture of autoreleasing variables. 16777 if (!Invalid && 16778 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 16779 if (BuildAndDiagnose) { 16780 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 16781 << /*block*/ 0; 16782 S.Diag(Var->getLocation(), diag::note_previous_decl) 16783 << Var->getDeclName(); 16784 Invalid = true; 16785 } else { 16786 return false; 16787 } 16788 } 16789 16790 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 16791 if (const auto *PT = CaptureType->getAs<PointerType>()) { 16792 QualType PointeeTy = PT->getPointeeType(); 16793 16794 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 16795 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 16796 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 16797 if (BuildAndDiagnose) { 16798 SourceLocation VarLoc = Var->getLocation(); 16799 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 16800 S.Diag(VarLoc, diag::note_declare_parameter_strong); 16801 } 16802 } 16803 } 16804 16805 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 16806 if (HasBlocksAttr || CaptureType->isReferenceType() || 16807 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 16808 // Block capture by reference does not change the capture or 16809 // declaration reference types. 16810 ByRef = true; 16811 } else { 16812 // Block capture by copy introduces 'const'. 16813 CaptureType = CaptureType.getNonReferenceType().withConst(); 16814 DeclRefType = CaptureType; 16815 } 16816 16817 // Actually capture the variable. 16818 if (BuildAndDiagnose) 16819 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 16820 CaptureType, Invalid); 16821 16822 return !Invalid; 16823 } 16824 16825 16826 /// Capture the given variable in the captured region. 16827 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 16828 VarDecl *Var, 16829 SourceLocation Loc, 16830 const bool BuildAndDiagnose, 16831 QualType &CaptureType, 16832 QualType &DeclRefType, 16833 const bool RefersToCapturedVariable, 16834 Sema &S, bool Invalid) { 16835 // By default, capture variables by reference. 16836 bool ByRef = true; 16837 // Using an LValue reference type is consistent with Lambdas (see below). 16838 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 16839 if (S.isOpenMPCapturedDecl(Var)) { 16840 bool HasConst = DeclRefType.isConstQualified(); 16841 DeclRefType = DeclRefType.getUnqualifiedType(); 16842 // Don't lose diagnostics about assignments to const. 16843 if (HasConst) 16844 DeclRefType.addConst(); 16845 } 16846 // Do not capture firstprivates in tasks. 16847 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 16848 OMPC_unknown) 16849 return true; 16850 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 16851 RSI->OpenMPCaptureLevel); 16852 } 16853 16854 if (ByRef) 16855 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 16856 else 16857 CaptureType = DeclRefType; 16858 16859 // Actually capture the variable. 16860 if (BuildAndDiagnose) 16861 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 16862 Loc, SourceLocation(), CaptureType, Invalid); 16863 16864 return !Invalid; 16865 } 16866 16867 /// Capture the given variable in the lambda. 16868 static bool captureInLambda(LambdaScopeInfo *LSI, 16869 VarDecl *Var, 16870 SourceLocation Loc, 16871 const bool BuildAndDiagnose, 16872 QualType &CaptureType, 16873 QualType &DeclRefType, 16874 const bool RefersToCapturedVariable, 16875 const Sema::TryCaptureKind Kind, 16876 SourceLocation EllipsisLoc, 16877 const bool IsTopScope, 16878 Sema &S, bool Invalid) { 16879 // Determine whether we are capturing by reference or by value. 16880 bool ByRef = false; 16881 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 16882 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 16883 } else { 16884 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 16885 } 16886 16887 // Compute the type of the field that will capture this variable. 16888 if (ByRef) { 16889 // C++11 [expr.prim.lambda]p15: 16890 // An entity is captured by reference if it is implicitly or 16891 // explicitly captured but not captured by copy. It is 16892 // unspecified whether additional unnamed non-static data 16893 // members are declared in the closure type for entities 16894 // captured by reference. 16895 // 16896 // FIXME: It is not clear whether we want to build an lvalue reference 16897 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 16898 // to do the former, while EDG does the latter. Core issue 1249 will 16899 // clarify, but for now we follow GCC because it's a more permissive and 16900 // easily defensible position. 16901 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 16902 } else { 16903 // C++11 [expr.prim.lambda]p14: 16904 // For each entity captured by copy, an unnamed non-static 16905 // data member is declared in the closure type. The 16906 // declaration order of these members is unspecified. The type 16907 // of such a data member is the type of the corresponding 16908 // captured entity if the entity is not a reference to an 16909 // object, or the referenced type otherwise. [Note: If the 16910 // captured entity is a reference to a function, the 16911 // corresponding data member is also a reference to a 16912 // function. - end note ] 16913 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 16914 if (!RefType->getPointeeType()->isFunctionType()) 16915 CaptureType = RefType->getPointeeType(); 16916 } 16917 16918 // Forbid the lambda copy-capture of autoreleasing variables. 16919 if (!Invalid && 16920 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 16921 if (BuildAndDiagnose) { 16922 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 16923 S.Diag(Var->getLocation(), diag::note_previous_decl) 16924 << Var->getDeclName(); 16925 Invalid = true; 16926 } else { 16927 return false; 16928 } 16929 } 16930 16931 // Make sure that by-copy captures are of a complete and non-abstract type. 16932 if (!Invalid && BuildAndDiagnose) { 16933 if (!CaptureType->isDependentType() && 16934 S.RequireCompleteSizedType( 16935 Loc, CaptureType, 16936 diag::err_capture_of_incomplete_or_sizeless_type, 16937 Var->getDeclName())) 16938 Invalid = true; 16939 else if (S.RequireNonAbstractType(Loc, CaptureType, 16940 diag::err_capture_of_abstract_type)) 16941 Invalid = true; 16942 } 16943 } 16944 16945 // Compute the type of a reference to this captured variable. 16946 if (ByRef) 16947 DeclRefType = CaptureType.getNonReferenceType(); 16948 else { 16949 // C++ [expr.prim.lambda]p5: 16950 // The closure type for a lambda-expression has a public inline 16951 // function call operator [...]. This function call operator is 16952 // declared const (9.3.1) if and only if the lambda-expression's 16953 // parameter-declaration-clause is not followed by mutable. 16954 DeclRefType = CaptureType.getNonReferenceType(); 16955 if (!LSI->Mutable && !CaptureType->isReferenceType()) 16956 DeclRefType.addConst(); 16957 } 16958 16959 // Add the capture. 16960 if (BuildAndDiagnose) 16961 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 16962 Loc, EllipsisLoc, CaptureType, Invalid); 16963 16964 return !Invalid; 16965 } 16966 16967 bool Sema::tryCaptureVariable( 16968 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 16969 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 16970 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 16971 // An init-capture is notionally from the context surrounding its 16972 // declaration, but its parent DC is the lambda class. 16973 DeclContext *VarDC = Var->getDeclContext(); 16974 if (Var->isInitCapture()) 16975 VarDC = VarDC->getParent(); 16976 16977 DeclContext *DC = CurContext; 16978 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 16979 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 16980 // We need to sync up the Declaration Context with the 16981 // FunctionScopeIndexToStopAt 16982 if (FunctionScopeIndexToStopAt) { 16983 unsigned FSIndex = FunctionScopes.size() - 1; 16984 while (FSIndex != MaxFunctionScopesIndex) { 16985 DC = getLambdaAwareParentOfDeclContext(DC); 16986 --FSIndex; 16987 } 16988 } 16989 16990 16991 // If the variable is declared in the current context, there is no need to 16992 // capture it. 16993 if (VarDC == DC) return true; 16994 16995 // Capture global variables if it is required to use private copy of this 16996 // variable. 16997 bool IsGlobal = !Var->hasLocalStorage(); 16998 if (IsGlobal && 16999 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17000 MaxFunctionScopesIndex))) 17001 return true; 17002 Var = Var->getCanonicalDecl(); 17003 17004 // Walk up the stack to determine whether we can capture the variable, 17005 // performing the "simple" checks that don't depend on type. We stop when 17006 // we've either hit the declared scope of the variable or find an existing 17007 // capture of that variable. We start from the innermost capturing-entity 17008 // (the DC) and ensure that all intervening capturing-entities 17009 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17010 // declcontext can either capture the variable or have already captured 17011 // the variable. 17012 CaptureType = Var->getType(); 17013 DeclRefType = CaptureType.getNonReferenceType(); 17014 bool Nested = false; 17015 bool Explicit = (Kind != TryCapture_Implicit); 17016 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17017 do { 17018 // Only block literals, captured statements, and lambda expressions can 17019 // capture; other scopes don't work. 17020 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17021 ExprLoc, 17022 BuildAndDiagnose, 17023 *this); 17024 // We need to check for the parent *first* because, if we *have* 17025 // private-captured a global variable, we need to recursively capture it in 17026 // intermediate blocks, lambdas, etc. 17027 if (!ParentDC) { 17028 if (IsGlobal) { 17029 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17030 break; 17031 } 17032 return true; 17033 } 17034 17035 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17036 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17037 17038 17039 // Check whether we've already captured it. 17040 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17041 DeclRefType)) { 17042 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17043 break; 17044 } 17045 // If we are instantiating a generic lambda call operator body, 17046 // we do not want to capture new variables. What was captured 17047 // during either a lambdas transformation or initial parsing 17048 // should be used. 17049 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17050 if (BuildAndDiagnose) { 17051 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17052 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17053 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 17054 Diag(Var->getLocation(), diag::note_previous_decl) 17055 << Var->getDeclName(); 17056 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17057 } else 17058 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17059 } 17060 return true; 17061 } 17062 17063 // Try to capture variable-length arrays types. 17064 if (Var->getType()->isVariablyModifiedType()) { 17065 // We're going to walk down into the type and look for VLA 17066 // expressions. 17067 QualType QTy = Var->getType(); 17068 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17069 QTy = PVD->getOriginalType(); 17070 captureVariablyModifiedType(Context, QTy, CSI); 17071 } 17072 17073 if (getLangOpts().OpenMP) { 17074 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17075 // OpenMP private variables should not be captured in outer scope, so 17076 // just break here. Similarly, global variables that are captured in a 17077 // target region should not be captured outside the scope of the region. 17078 if (RSI->CapRegionKind == CR_OpenMP) { 17079 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17080 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17081 // If the variable is private (i.e. not captured) and has variably 17082 // modified type, we still need to capture the type for correct 17083 // codegen in all regions, associated with the construct. Currently, 17084 // it is captured in the innermost captured region only. 17085 if (IsOpenMPPrivateDecl != OMPC_unknown && 17086 Var->getType()->isVariablyModifiedType()) { 17087 QualType QTy = Var->getType(); 17088 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17089 QTy = PVD->getOriginalType(); 17090 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17091 I < E; ++I) { 17092 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17093 FunctionScopes[FunctionScopesIndex - I]); 17094 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17095 "Wrong number of captured regions associated with the " 17096 "OpenMP construct."); 17097 captureVariablyModifiedType(Context, QTy, OuterRSI); 17098 } 17099 } 17100 bool IsTargetCap = 17101 IsOpenMPPrivateDecl != OMPC_private && 17102 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17103 RSI->OpenMPCaptureLevel); 17104 // Do not capture global if it is not privatized in outer regions. 17105 bool IsGlobalCap = 17106 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17107 RSI->OpenMPCaptureLevel); 17108 17109 // When we detect target captures we are looking from inside the 17110 // target region, therefore we need to propagate the capture from the 17111 // enclosing region. Therefore, the capture is not initially nested. 17112 if (IsTargetCap) 17113 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17114 17115 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17116 (IsGlobal && !IsGlobalCap)) { 17117 Nested = !IsTargetCap; 17118 DeclRefType = DeclRefType.getUnqualifiedType(); 17119 CaptureType = Context.getLValueReferenceType(DeclRefType); 17120 break; 17121 } 17122 } 17123 } 17124 } 17125 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17126 // No capture-default, and this is not an explicit capture 17127 // so cannot capture this variable. 17128 if (BuildAndDiagnose) { 17129 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 17130 Diag(Var->getLocation(), diag::note_previous_decl) 17131 << Var->getDeclName(); 17132 if (cast<LambdaScopeInfo>(CSI)->Lambda) 17133 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 17134 diag::note_lambda_decl); 17135 // FIXME: If we error out because an outer lambda can not implicitly 17136 // capture a variable that an inner lambda explicitly captures, we 17137 // should have the inner lambda do the explicit capture - because 17138 // it makes for cleaner diagnostics later. This would purely be done 17139 // so that the diagnostic does not misleadingly claim that a variable 17140 // can not be captured by a lambda implicitly even though it is captured 17141 // explicitly. Suggestion: 17142 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 17143 // at the function head 17144 // - cache the StartingDeclContext - this must be a lambda 17145 // - captureInLambda in the innermost lambda the variable. 17146 } 17147 return true; 17148 } 17149 17150 FunctionScopesIndex--; 17151 DC = ParentDC; 17152 Explicit = false; 17153 } while (!VarDC->Equals(DC)); 17154 17155 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 17156 // computing the type of the capture at each step, checking type-specific 17157 // requirements, and adding captures if requested. 17158 // If the variable had already been captured previously, we start capturing 17159 // at the lambda nested within that one. 17160 bool Invalid = false; 17161 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 17162 ++I) { 17163 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 17164 17165 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17166 // certain types of variables (unnamed, variably modified types etc.) 17167 // so check for eligibility. 17168 if (!Invalid) 17169 Invalid = 17170 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 17171 17172 // After encountering an error, if we're actually supposed to capture, keep 17173 // capturing in nested contexts to suppress any follow-on diagnostics. 17174 if (Invalid && !BuildAndDiagnose) 17175 return true; 17176 17177 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 17178 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17179 DeclRefType, Nested, *this, Invalid); 17180 Nested = true; 17181 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17182 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 17183 CaptureType, DeclRefType, Nested, 17184 *this, Invalid); 17185 Nested = true; 17186 } else { 17187 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17188 Invalid = 17189 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17190 DeclRefType, Nested, Kind, EllipsisLoc, 17191 /*IsTopScope*/ I == N - 1, *this, Invalid); 17192 Nested = true; 17193 } 17194 17195 if (Invalid && !BuildAndDiagnose) 17196 return true; 17197 } 17198 return Invalid; 17199 } 17200 17201 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 17202 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 17203 QualType CaptureType; 17204 QualType DeclRefType; 17205 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 17206 /*BuildAndDiagnose=*/true, CaptureType, 17207 DeclRefType, nullptr); 17208 } 17209 17210 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 17211 QualType CaptureType; 17212 QualType DeclRefType; 17213 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17214 /*BuildAndDiagnose=*/false, CaptureType, 17215 DeclRefType, nullptr); 17216 } 17217 17218 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 17219 QualType CaptureType; 17220 QualType DeclRefType; 17221 17222 // Determine whether we can capture this variable. 17223 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17224 /*BuildAndDiagnose=*/false, CaptureType, 17225 DeclRefType, nullptr)) 17226 return QualType(); 17227 17228 return DeclRefType; 17229 } 17230 17231 namespace { 17232 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 17233 // The produced TemplateArgumentListInfo* points to data stored within this 17234 // object, so should only be used in contexts where the pointer will not be 17235 // used after the CopiedTemplateArgs object is destroyed. 17236 class CopiedTemplateArgs { 17237 bool HasArgs; 17238 TemplateArgumentListInfo TemplateArgStorage; 17239 public: 17240 template<typename RefExpr> 17241 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 17242 if (HasArgs) 17243 E->copyTemplateArgumentsInto(TemplateArgStorage); 17244 } 17245 operator TemplateArgumentListInfo*() 17246 #ifdef __has_cpp_attribute 17247 #if __has_cpp_attribute(clang::lifetimebound) 17248 [[clang::lifetimebound]] 17249 #endif 17250 #endif 17251 { 17252 return HasArgs ? &TemplateArgStorage : nullptr; 17253 } 17254 }; 17255 } 17256 17257 /// Walk the set of potential results of an expression and mark them all as 17258 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 17259 /// 17260 /// \return A new expression if we found any potential results, ExprEmpty() if 17261 /// not, and ExprError() if we diagnosed an error. 17262 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 17263 NonOdrUseReason NOUR) { 17264 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 17265 // an object that satisfies the requirements for appearing in a 17266 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 17267 // is immediately applied." This function handles the lvalue-to-rvalue 17268 // conversion part. 17269 // 17270 // If we encounter a node that claims to be an odr-use but shouldn't be, we 17271 // transform it into the relevant kind of non-odr-use node and rebuild the 17272 // tree of nodes leading to it. 17273 // 17274 // This is a mini-TreeTransform that only transforms a restricted subset of 17275 // nodes (and only certain operands of them). 17276 17277 // Rebuild a subexpression. 17278 auto Rebuild = [&](Expr *Sub) { 17279 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 17280 }; 17281 17282 // Check whether a potential result satisfies the requirements of NOUR. 17283 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 17284 // Any entity other than a VarDecl is always odr-used whenever it's named 17285 // in a potentially-evaluated expression. 17286 auto *VD = dyn_cast<VarDecl>(D); 17287 if (!VD) 17288 return true; 17289 17290 // C++2a [basic.def.odr]p4: 17291 // A variable x whose name appears as a potentially-evalauted expression 17292 // e is odr-used by e unless 17293 // -- x is a reference that is usable in constant expressions, or 17294 // -- x is a variable of non-reference type that is usable in constant 17295 // expressions and has no mutable subobjects, and e is an element of 17296 // the set of potential results of an expression of 17297 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17298 // conversion is applied, or 17299 // -- x is a variable of non-reference type, and e is an element of the 17300 // set of potential results of a discarded-value expression to which 17301 // the lvalue-to-rvalue conversion is not applied 17302 // 17303 // We check the first bullet and the "potentially-evaluated" condition in 17304 // BuildDeclRefExpr. We check the type requirements in the second bullet 17305 // in CheckLValueToRValueConversionOperand below. 17306 switch (NOUR) { 17307 case NOUR_None: 17308 case NOUR_Unevaluated: 17309 llvm_unreachable("unexpected non-odr-use-reason"); 17310 17311 case NOUR_Constant: 17312 // Constant references were handled when they were built. 17313 if (VD->getType()->isReferenceType()) 17314 return true; 17315 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 17316 if (RD->hasMutableFields()) 17317 return true; 17318 if (!VD->isUsableInConstantExpressions(S.Context)) 17319 return true; 17320 break; 17321 17322 case NOUR_Discarded: 17323 if (VD->getType()->isReferenceType()) 17324 return true; 17325 break; 17326 } 17327 return false; 17328 }; 17329 17330 // Mark that this expression does not constitute an odr-use. 17331 auto MarkNotOdrUsed = [&] { 17332 S.MaybeODRUseExprs.erase(E); 17333 if (LambdaScopeInfo *LSI = S.getCurLambda()) 17334 LSI->markVariableExprAsNonODRUsed(E); 17335 }; 17336 17337 // C++2a [basic.def.odr]p2: 17338 // The set of potential results of an expression e is defined as follows: 17339 switch (E->getStmtClass()) { 17340 // -- If e is an id-expression, ... 17341 case Expr::DeclRefExprClass: { 17342 auto *DRE = cast<DeclRefExpr>(E); 17343 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 17344 break; 17345 17346 // Rebuild as a non-odr-use DeclRefExpr. 17347 MarkNotOdrUsed(); 17348 return DeclRefExpr::Create( 17349 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 17350 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 17351 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 17352 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 17353 } 17354 17355 case Expr::FunctionParmPackExprClass: { 17356 auto *FPPE = cast<FunctionParmPackExpr>(E); 17357 // If any of the declarations in the pack is odr-used, then the expression 17358 // as a whole constitutes an odr-use. 17359 for (VarDecl *D : *FPPE) 17360 if (IsPotentialResultOdrUsed(D)) 17361 return ExprEmpty(); 17362 17363 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 17364 // nothing cares about whether we marked this as an odr-use, but it might 17365 // be useful for non-compiler tools. 17366 MarkNotOdrUsed(); 17367 break; 17368 } 17369 17370 // -- If e is a subscripting operation with an array operand... 17371 case Expr::ArraySubscriptExprClass: { 17372 auto *ASE = cast<ArraySubscriptExpr>(E); 17373 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 17374 if (!OldBase->getType()->isArrayType()) 17375 break; 17376 ExprResult Base = Rebuild(OldBase); 17377 if (!Base.isUsable()) 17378 return Base; 17379 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 17380 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 17381 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 17382 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 17383 ASE->getRBracketLoc()); 17384 } 17385 17386 case Expr::MemberExprClass: { 17387 auto *ME = cast<MemberExpr>(E); 17388 // -- If e is a class member access expression [...] naming a non-static 17389 // data member... 17390 if (isa<FieldDecl>(ME->getMemberDecl())) { 17391 ExprResult Base = Rebuild(ME->getBase()); 17392 if (!Base.isUsable()) 17393 return Base; 17394 return MemberExpr::Create( 17395 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 17396 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 17397 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 17398 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 17399 ME->getObjectKind(), ME->isNonOdrUse()); 17400 } 17401 17402 if (ME->getMemberDecl()->isCXXInstanceMember()) 17403 break; 17404 17405 // -- If e is a class member access expression naming a static data member, 17406 // ... 17407 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 17408 break; 17409 17410 // Rebuild as a non-odr-use MemberExpr. 17411 MarkNotOdrUsed(); 17412 return MemberExpr::Create( 17413 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 17414 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 17415 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 17416 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 17417 return ExprEmpty(); 17418 } 17419 17420 case Expr::BinaryOperatorClass: { 17421 auto *BO = cast<BinaryOperator>(E); 17422 Expr *LHS = BO->getLHS(); 17423 Expr *RHS = BO->getRHS(); 17424 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 17425 if (BO->getOpcode() == BO_PtrMemD) { 17426 ExprResult Sub = Rebuild(LHS); 17427 if (!Sub.isUsable()) 17428 return Sub; 17429 LHS = Sub.get(); 17430 // -- If e is a comma expression, ... 17431 } else if (BO->getOpcode() == BO_Comma) { 17432 ExprResult Sub = Rebuild(RHS); 17433 if (!Sub.isUsable()) 17434 return Sub; 17435 RHS = Sub.get(); 17436 } else { 17437 break; 17438 } 17439 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 17440 LHS, RHS); 17441 } 17442 17443 // -- If e has the form (e1)... 17444 case Expr::ParenExprClass: { 17445 auto *PE = cast<ParenExpr>(E); 17446 ExprResult Sub = Rebuild(PE->getSubExpr()); 17447 if (!Sub.isUsable()) 17448 return Sub; 17449 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 17450 } 17451 17452 // -- If e is a glvalue conditional expression, ... 17453 // We don't apply this to a binary conditional operator. FIXME: Should we? 17454 case Expr::ConditionalOperatorClass: { 17455 auto *CO = cast<ConditionalOperator>(E); 17456 ExprResult LHS = Rebuild(CO->getLHS()); 17457 if (LHS.isInvalid()) 17458 return ExprError(); 17459 ExprResult RHS = Rebuild(CO->getRHS()); 17460 if (RHS.isInvalid()) 17461 return ExprError(); 17462 if (!LHS.isUsable() && !RHS.isUsable()) 17463 return ExprEmpty(); 17464 if (!LHS.isUsable()) 17465 LHS = CO->getLHS(); 17466 if (!RHS.isUsable()) 17467 RHS = CO->getRHS(); 17468 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 17469 CO->getCond(), LHS.get(), RHS.get()); 17470 } 17471 17472 // [Clang extension] 17473 // -- If e has the form __extension__ e1... 17474 case Expr::UnaryOperatorClass: { 17475 auto *UO = cast<UnaryOperator>(E); 17476 if (UO->getOpcode() != UO_Extension) 17477 break; 17478 ExprResult Sub = Rebuild(UO->getSubExpr()); 17479 if (!Sub.isUsable()) 17480 return Sub; 17481 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 17482 Sub.get()); 17483 } 17484 17485 // [Clang extension] 17486 // -- If e has the form _Generic(...), the set of potential results is the 17487 // union of the sets of potential results of the associated expressions. 17488 case Expr::GenericSelectionExprClass: { 17489 auto *GSE = cast<GenericSelectionExpr>(E); 17490 17491 SmallVector<Expr *, 4> AssocExprs; 17492 bool AnyChanged = false; 17493 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 17494 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 17495 if (AssocExpr.isInvalid()) 17496 return ExprError(); 17497 if (AssocExpr.isUsable()) { 17498 AssocExprs.push_back(AssocExpr.get()); 17499 AnyChanged = true; 17500 } else { 17501 AssocExprs.push_back(OrigAssocExpr); 17502 } 17503 } 17504 17505 return AnyChanged ? S.CreateGenericSelectionExpr( 17506 GSE->getGenericLoc(), GSE->getDefaultLoc(), 17507 GSE->getRParenLoc(), GSE->getControllingExpr(), 17508 GSE->getAssocTypeSourceInfos(), AssocExprs) 17509 : ExprEmpty(); 17510 } 17511 17512 // [Clang extension] 17513 // -- If e has the form __builtin_choose_expr(...), the set of potential 17514 // results is the union of the sets of potential results of the 17515 // second and third subexpressions. 17516 case Expr::ChooseExprClass: { 17517 auto *CE = cast<ChooseExpr>(E); 17518 17519 ExprResult LHS = Rebuild(CE->getLHS()); 17520 if (LHS.isInvalid()) 17521 return ExprError(); 17522 17523 ExprResult RHS = Rebuild(CE->getLHS()); 17524 if (RHS.isInvalid()) 17525 return ExprError(); 17526 17527 if (!LHS.get() && !RHS.get()) 17528 return ExprEmpty(); 17529 if (!LHS.isUsable()) 17530 LHS = CE->getLHS(); 17531 if (!RHS.isUsable()) 17532 RHS = CE->getRHS(); 17533 17534 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 17535 RHS.get(), CE->getRParenLoc()); 17536 } 17537 17538 // Step through non-syntactic nodes. 17539 case Expr::ConstantExprClass: { 17540 auto *CE = cast<ConstantExpr>(E); 17541 ExprResult Sub = Rebuild(CE->getSubExpr()); 17542 if (!Sub.isUsable()) 17543 return Sub; 17544 return ConstantExpr::Create(S.Context, Sub.get()); 17545 } 17546 17547 // We could mostly rely on the recursive rebuilding to rebuild implicit 17548 // casts, but not at the top level, so rebuild them here. 17549 case Expr::ImplicitCastExprClass: { 17550 auto *ICE = cast<ImplicitCastExpr>(E); 17551 // Only step through the narrow set of cast kinds we expect to encounter. 17552 // Anything else suggests we've left the region in which potential results 17553 // can be found. 17554 switch (ICE->getCastKind()) { 17555 case CK_NoOp: 17556 case CK_DerivedToBase: 17557 case CK_UncheckedDerivedToBase: { 17558 ExprResult Sub = Rebuild(ICE->getSubExpr()); 17559 if (!Sub.isUsable()) 17560 return Sub; 17561 CXXCastPath Path(ICE->path()); 17562 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 17563 ICE->getValueKind(), &Path); 17564 } 17565 17566 default: 17567 break; 17568 } 17569 break; 17570 } 17571 17572 default: 17573 break; 17574 } 17575 17576 // Can't traverse through this node. Nothing to do. 17577 return ExprEmpty(); 17578 } 17579 17580 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 17581 // Check whether the operand is or contains an object of non-trivial C union 17582 // type. 17583 if (E->getType().isVolatileQualified() && 17584 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 17585 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 17586 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 17587 Sema::NTCUC_LValueToRValueVolatile, 17588 NTCUK_Destruct|NTCUK_Copy); 17589 17590 // C++2a [basic.def.odr]p4: 17591 // [...] an expression of non-volatile-qualified non-class type to which 17592 // the lvalue-to-rvalue conversion is applied [...] 17593 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 17594 return E; 17595 17596 ExprResult Result = 17597 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 17598 if (Result.isInvalid()) 17599 return ExprError(); 17600 return Result.get() ? Result : E; 17601 } 17602 17603 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 17604 Res = CorrectDelayedTyposInExpr(Res); 17605 17606 if (!Res.isUsable()) 17607 return Res; 17608 17609 // If a constant-expression is a reference to a variable where we delay 17610 // deciding whether it is an odr-use, just assume we will apply the 17611 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 17612 // (a non-type template argument), we have special handling anyway. 17613 return CheckLValueToRValueConversionOperand(Res.get()); 17614 } 17615 17616 void Sema::CleanupVarDeclMarking() { 17617 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 17618 // call. 17619 MaybeODRUseExprSet LocalMaybeODRUseExprs; 17620 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 17621 17622 for (Expr *E : LocalMaybeODRUseExprs) { 17623 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 17624 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 17625 DRE->getLocation(), *this); 17626 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 17627 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 17628 *this); 17629 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 17630 for (VarDecl *VD : *FP) 17631 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 17632 } else { 17633 llvm_unreachable("Unexpected expression"); 17634 } 17635 } 17636 17637 assert(MaybeODRUseExprs.empty() && 17638 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 17639 } 17640 17641 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 17642 VarDecl *Var, Expr *E) { 17643 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 17644 isa<FunctionParmPackExpr>(E)) && 17645 "Invalid Expr argument to DoMarkVarDeclReferenced"); 17646 Var->setReferenced(); 17647 17648 if (Var->isInvalidDecl()) 17649 return; 17650 17651 auto *MSI = Var->getMemberSpecializationInfo(); 17652 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 17653 : Var->getTemplateSpecializationKind(); 17654 17655 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 17656 bool UsableInConstantExpr = 17657 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 17658 17659 // C++20 [expr.const]p12: 17660 // A variable [...] is needed for constant evaluation if it is [...] a 17661 // variable whose name appears as a potentially constant evaluated 17662 // expression that is either a contexpr variable or is of non-volatile 17663 // const-qualified integral type or of reference type 17664 bool NeededForConstantEvaluation = 17665 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 17666 17667 bool NeedDefinition = 17668 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 17669 17670 VarTemplateSpecializationDecl *VarSpec = 17671 dyn_cast<VarTemplateSpecializationDecl>(Var); 17672 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 17673 "Can't instantiate a partial template specialization."); 17674 17675 // If this might be a member specialization of a static data member, check 17676 // the specialization is visible. We already did the checks for variable 17677 // template specializations when we created them. 17678 if (NeedDefinition && TSK != TSK_Undeclared && 17679 !isa<VarTemplateSpecializationDecl>(Var)) 17680 SemaRef.checkSpecializationVisibility(Loc, Var); 17681 17682 // Perform implicit instantiation of static data members, static data member 17683 // templates of class templates, and variable template specializations. Delay 17684 // instantiations of variable templates, except for those that could be used 17685 // in a constant expression. 17686 if (NeedDefinition && isTemplateInstantiation(TSK)) { 17687 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 17688 // instantiation declaration if a variable is usable in a constant 17689 // expression (among other cases). 17690 bool TryInstantiating = 17691 TSK == TSK_ImplicitInstantiation || 17692 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 17693 17694 if (TryInstantiating) { 17695 SourceLocation PointOfInstantiation = 17696 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 17697 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17698 if (FirstInstantiation) { 17699 PointOfInstantiation = Loc; 17700 if (MSI) 17701 MSI->setPointOfInstantiation(PointOfInstantiation); 17702 else 17703 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17704 } 17705 17706 bool InstantiationDependent = false; 17707 bool IsNonDependent = 17708 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 17709 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 17710 : true; 17711 17712 // Do not instantiate specializations that are still type-dependent. 17713 if (IsNonDependent) { 17714 if (UsableInConstantExpr) { 17715 // Do not defer instantiations of variables that could be used in a 17716 // constant expression. 17717 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 17718 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 17719 }); 17720 } else if (FirstInstantiation || 17721 isa<VarTemplateSpecializationDecl>(Var)) { 17722 // FIXME: For a specialization of a variable template, we don't 17723 // distinguish between "declaration and type implicitly instantiated" 17724 // and "implicit instantiation of definition requested", so we have 17725 // no direct way to avoid enqueueing the pending instantiation 17726 // multiple times. 17727 SemaRef.PendingInstantiations 17728 .push_back(std::make_pair(Var, PointOfInstantiation)); 17729 } 17730 } 17731 } 17732 } 17733 17734 // C++2a [basic.def.odr]p4: 17735 // A variable x whose name appears as a potentially-evaluated expression e 17736 // is odr-used by e unless 17737 // -- x is a reference that is usable in constant expressions 17738 // -- x is a variable of non-reference type that is usable in constant 17739 // expressions and has no mutable subobjects [FIXME], and e is an 17740 // element of the set of potential results of an expression of 17741 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17742 // conversion is applied 17743 // -- x is a variable of non-reference type, and e is an element of the set 17744 // of potential results of a discarded-value expression to which the 17745 // lvalue-to-rvalue conversion is not applied [FIXME] 17746 // 17747 // We check the first part of the second bullet here, and 17748 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 17749 // FIXME: To get the third bullet right, we need to delay this even for 17750 // variables that are not usable in constant expressions. 17751 17752 // If we already know this isn't an odr-use, there's nothing more to do. 17753 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 17754 if (DRE->isNonOdrUse()) 17755 return; 17756 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 17757 if (ME->isNonOdrUse()) 17758 return; 17759 17760 switch (OdrUse) { 17761 case OdrUseContext::None: 17762 assert((!E || isa<FunctionParmPackExpr>(E)) && 17763 "missing non-odr-use marking for unevaluated decl ref"); 17764 break; 17765 17766 case OdrUseContext::FormallyOdrUsed: 17767 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 17768 // behavior. 17769 break; 17770 17771 case OdrUseContext::Used: 17772 // If we might later find that this expression isn't actually an odr-use, 17773 // delay the marking. 17774 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 17775 SemaRef.MaybeODRUseExprs.insert(E); 17776 else 17777 MarkVarDeclODRUsed(Var, Loc, SemaRef); 17778 break; 17779 17780 case OdrUseContext::Dependent: 17781 // If this is a dependent context, we don't need to mark variables as 17782 // odr-used, but we may still need to track them for lambda capture. 17783 // FIXME: Do we also need to do this inside dependent typeid expressions 17784 // (which are modeled as unevaluated at this point)? 17785 const bool RefersToEnclosingScope = 17786 (SemaRef.CurContext != Var->getDeclContext() && 17787 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 17788 if (RefersToEnclosingScope) { 17789 LambdaScopeInfo *const LSI = 17790 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 17791 if (LSI && (!LSI->CallOperator || 17792 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 17793 // If a variable could potentially be odr-used, defer marking it so 17794 // until we finish analyzing the full expression for any 17795 // lvalue-to-rvalue 17796 // or discarded value conversions that would obviate odr-use. 17797 // Add it to the list of potential captures that will be analyzed 17798 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 17799 // unless the variable is a reference that was initialized by a constant 17800 // expression (this will never need to be captured or odr-used). 17801 // 17802 // FIXME: We can simplify this a lot after implementing P0588R1. 17803 assert(E && "Capture variable should be used in an expression."); 17804 if (!Var->getType()->isReferenceType() || 17805 !Var->isUsableInConstantExpressions(SemaRef.Context)) 17806 LSI->addPotentialCapture(E->IgnoreParens()); 17807 } 17808 } 17809 break; 17810 } 17811 } 17812 17813 /// Mark a variable referenced, and check whether it is odr-used 17814 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 17815 /// used directly for normal expressions referring to VarDecl. 17816 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 17817 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 17818 } 17819 17820 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 17821 Decl *D, Expr *E, bool MightBeOdrUse) { 17822 if (SemaRef.isInOpenMPDeclareTargetContext()) 17823 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 17824 17825 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 17826 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 17827 return; 17828 } 17829 17830 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 17831 17832 // If this is a call to a method via a cast, also mark the method in the 17833 // derived class used in case codegen can devirtualize the call. 17834 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 17835 if (!ME) 17836 return; 17837 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 17838 if (!MD) 17839 return; 17840 // Only attempt to devirtualize if this is truly a virtual call. 17841 bool IsVirtualCall = MD->isVirtual() && 17842 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 17843 if (!IsVirtualCall) 17844 return; 17845 17846 // If it's possible to devirtualize the call, mark the called function 17847 // referenced. 17848 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 17849 ME->getBase(), SemaRef.getLangOpts().AppleKext); 17850 if (DM) 17851 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 17852 } 17853 17854 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 17855 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 17856 // TODO: update this with DR# once a defect report is filed. 17857 // C++11 defect. The address of a pure member should not be an ODR use, even 17858 // if it's a qualified reference. 17859 bool OdrUse = true; 17860 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 17861 if (Method->isVirtual() && 17862 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 17863 OdrUse = false; 17864 17865 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 17866 if (!isConstantEvaluated() && FD->isConsteval() && 17867 !RebuildingImmediateInvocation) 17868 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 17869 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 17870 } 17871 17872 /// Perform reference-marking and odr-use handling for a MemberExpr. 17873 void Sema::MarkMemberReferenced(MemberExpr *E) { 17874 // C++11 [basic.def.odr]p2: 17875 // A non-overloaded function whose name appears as a potentially-evaluated 17876 // expression or a member of a set of candidate functions, if selected by 17877 // overload resolution when referred to from a potentially-evaluated 17878 // expression, is odr-used, unless it is a pure virtual function and its 17879 // name is not explicitly qualified. 17880 bool MightBeOdrUse = true; 17881 if (E->performsVirtualDispatch(getLangOpts())) { 17882 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 17883 if (Method->isPure()) 17884 MightBeOdrUse = false; 17885 } 17886 SourceLocation Loc = 17887 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 17888 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 17889 } 17890 17891 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 17892 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 17893 for (VarDecl *VD : *E) 17894 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 17895 } 17896 17897 /// Perform marking for a reference to an arbitrary declaration. It 17898 /// marks the declaration referenced, and performs odr-use checking for 17899 /// functions and variables. This method should not be used when building a 17900 /// normal expression which refers to a variable. 17901 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 17902 bool MightBeOdrUse) { 17903 if (MightBeOdrUse) { 17904 if (auto *VD = dyn_cast<VarDecl>(D)) { 17905 MarkVariableReferenced(Loc, VD); 17906 return; 17907 } 17908 } 17909 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 17910 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 17911 return; 17912 } 17913 D->setReferenced(); 17914 } 17915 17916 namespace { 17917 // Mark all of the declarations used by a type as referenced. 17918 // FIXME: Not fully implemented yet! We need to have a better understanding 17919 // of when we're entering a context we should not recurse into. 17920 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 17921 // TreeTransforms rebuilding the type in a new context. Rather than 17922 // duplicating the TreeTransform logic, we should consider reusing it here. 17923 // Currently that causes problems when rebuilding LambdaExprs. 17924 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 17925 Sema &S; 17926 SourceLocation Loc; 17927 17928 public: 17929 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 17930 17931 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 17932 17933 bool TraverseTemplateArgument(const TemplateArgument &Arg); 17934 }; 17935 } 17936 17937 bool MarkReferencedDecls::TraverseTemplateArgument( 17938 const TemplateArgument &Arg) { 17939 { 17940 // A non-type template argument is a constant-evaluated context. 17941 EnterExpressionEvaluationContext Evaluated( 17942 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 17943 if (Arg.getKind() == TemplateArgument::Declaration) { 17944 if (Decl *D = Arg.getAsDecl()) 17945 S.MarkAnyDeclReferenced(Loc, D, true); 17946 } else if (Arg.getKind() == TemplateArgument::Expression) { 17947 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 17948 } 17949 } 17950 17951 return Inherited::TraverseTemplateArgument(Arg); 17952 } 17953 17954 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 17955 MarkReferencedDecls Marker(*this, Loc); 17956 Marker.TraverseType(T); 17957 } 17958 17959 namespace { 17960 /// Helper class that marks all of the declarations referenced by 17961 /// potentially-evaluated subexpressions as "referenced". 17962 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 17963 public: 17964 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 17965 bool SkipLocalVariables; 17966 17967 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 17968 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 17969 17970 void visitUsedDecl(SourceLocation Loc, Decl *D) { 17971 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 17972 } 17973 17974 void VisitDeclRefExpr(DeclRefExpr *E) { 17975 // If we were asked not to visit local variables, don't. 17976 if (SkipLocalVariables) { 17977 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 17978 if (VD->hasLocalStorage()) 17979 return; 17980 } 17981 S.MarkDeclRefReferenced(E); 17982 } 17983 17984 void VisitMemberExpr(MemberExpr *E) { 17985 S.MarkMemberReferenced(E); 17986 Visit(E->getBase()); 17987 } 17988 }; 17989 } // namespace 17990 17991 /// Mark any declarations that appear within this expression or any 17992 /// potentially-evaluated subexpressions as "referenced". 17993 /// 17994 /// \param SkipLocalVariables If true, don't mark local variables as 17995 /// 'referenced'. 17996 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 17997 bool SkipLocalVariables) { 17998 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 17999 } 18000 18001 /// Emit a diagnostic that describes an effect on the run-time behavior 18002 /// of the program being compiled. 18003 /// 18004 /// This routine emits the given diagnostic when the code currently being 18005 /// type-checked is "potentially evaluated", meaning that there is a 18006 /// possibility that the code will actually be executable. Code in sizeof() 18007 /// expressions, code used only during overload resolution, etc., are not 18008 /// potentially evaluated. This routine will suppress such diagnostics or, 18009 /// in the absolutely nutty case of potentially potentially evaluated 18010 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18011 /// later. 18012 /// 18013 /// This routine should be used for all diagnostics that describe the run-time 18014 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18015 /// Failure to do so will likely result in spurious diagnostics or failures 18016 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18017 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18018 const PartialDiagnostic &PD) { 18019 switch (ExprEvalContexts.back().Context) { 18020 case ExpressionEvaluationContext::Unevaluated: 18021 case ExpressionEvaluationContext::UnevaluatedList: 18022 case ExpressionEvaluationContext::UnevaluatedAbstract: 18023 case ExpressionEvaluationContext::DiscardedStatement: 18024 // The argument will never be evaluated, so don't complain. 18025 break; 18026 18027 case ExpressionEvaluationContext::ConstantEvaluated: 18028 // Relevant diagnostics should be produced by constant evaluation. 18029 break; 18030 18031 case ExpressionEvaluationContext::PotentiallyEvaluated: 18032 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18033 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18034 FunctionScopes.back()->PossiblyUnreachableDiags. 18035 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18036 return true; 18037 } 18038 18039 // The initializer of a constexpr variable or of the first declaration of a 18040 // static data member is not syntactically a constant evaluated constant, 18041 // but nonetheless is always required to be a constant expression, so we 18042 // can skip diagnosing. 18043 // FIXME: Using the mangling context here is a hack. 18044 if (auto *VD = dyn_cast_or_null<VarDecl>( 18045 ExprEvalContexts.back().ManglingContextDecl)) { 18046 if (VD->isConstexpr() || 18047 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18048 break; 18049 // FIXME: For any other kind of variable, we should build a CFG for its 18050 // initializer and check whether the context in question is reachable. 18051 } 18052 18053 Diag(Loc, PD); 18054 return true; 18055 } 18056 18057 return false; 18058 } 18059 18060 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18061 const PartialDiagnostic &PD) { 18062 return DiagRuntimeBehavior( 18063 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18064 } 18065 18066 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18067 CallExpr *CE, FunctionDecl *FD) { 18068 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18069 return false; 18070 18071 // If we're inside a decltype's expression, don't check for a valid return 18072 // type or construct temporaries until we know whether this is the last call. 18073 if (ExprEvalContexts.back().ExprContext == 18074 ExpressionEvaluationContextRecord::EK_Decltype) { 18075 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18076 return false; 18077 } 18078 18079 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18080 FunctionDecl *FD; 18081 CallExpr *CE; 18082 18083 public: 18084 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18085 : FD(FD), CE(CE) { } 18086 18087 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18088 if (!FD) { 18089 S.Diag(Loc, diag::err_call_incomplete_return) 18090 << T << CE->getSourceRange(); 18091 return; 18092 } 18093 18094 S.Diag(Loc, diag::err_call_function_incomplete_return) 18095 << CE->getSourceRange() << FD->getDeclName() << T; 18096 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18097 << FD->getDeclName(); 18098 } 18099 } Diagnoser(FD, CE); 18100 18101 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18102 return true; 18103 18104 return false; 18105 } 18106 18107 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18108 // will prevent this condition from triggering, which is what we want. 18109 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18110 SourceLocation Loc; 18111 18112 unsigned diagnostic = diag::warn_condition_is_assignment; 18113 bool IsOrAssign = false; 18114 18115 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18116 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18117 return; 18118 18119 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18120 18121 // Greylist some idioms by putting them into a warning subcategory. 18122 if (ObjCMessageExpr *ME 18123 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18124 Selector Sel = ME->getSelector(); 18125 18126 // self = [<foo> init...] 18127 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18128 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18129 18130 // <foo> = [<bar> nextObject] 18131 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 18132 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18133 } 18134 18135 Loc = Op->getOperatorLoc(); 18136 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 18137 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 18138 return; 18139 18140 IsOrAssign = Op->getOperator() == OO_PipeEqual; 18141 Loc = Op->getOperatorLoc(); 18142 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 18143 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 18144 else { 18145 // Not an assignment. 18146 return; 18147 } 18148 18149 Diag(Loc, diagnostic) << E->getSourceRange(); 18150 18151 SourceLocation Open = E->getBeginLoc(); 18152 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 18153 Diag(Loc, diag::note_condition_assign_silence) 18154 << FixItHint::CreateInsertion(Open, "(") 18155 << FixItHint::CreateInsertion(Close, ")"); 18156 18157 if (IsOrAssign) 18158 Diag(Loc, diag::note_condition_or_assign_to_comparison) 18159 << FixItHint::CreateReplacement(Loc, "!="); 18160 else 18161 Diag(Loc, diag::note_condition_assign_to_comparison) 18162 << FixItHint::CreateReplacement(Loc, "=="); 18163 } 18164 18165 /// Redundant parentheses over an equality comparison can indicate 18166 /// that the user intended an assignment used as condition. 18167 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 18168 // Don't warn if the parens came from a macro. 18169 SourceLocation parenLoc = ParenE->getBeginLoc(); 18170 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 18171 return; 18172 // Don't warn for dependent expressions. 18173 if (ParenE->isTypeDependent()) 18174 return; 18175 18176 Expr *E = ParenE->IgnoreParens(); 18177 18178 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 18179 if (opE->getOpcode() == BO_EQ && 18180 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 18181 == Expr::MLV_Valid) { 18182 SourceLocation Loc = opE->getOperatorLoc(); 18183 18184 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 18185 SourceRange ParenERange = ParenE->getSourceRange(); 18186 Diag(Loc, diag::note_equality_comparison_silence) 18187 << FixItHint::CreateRemoval(ParenERange.getBegin()) 18188 << FixItHint::CreateRemoval(ParenERange.getEnd()); 18189 Diag(Loc, diag::note_equality_comparison_to_assign) 18190 << FixItHint::CreateReplacement(Loc, "="); 18191 } 18192 } 18193 18194 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 18195 bool IsConstexpr) { 18196 DiagnoseAssignmentAsCondition(E); 18197 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 18198 DiagnoseEqualityWithExtraParens(parenE); 18199 18200 ExprResult result = CheckPlaceholderExpr(E); 18201 if (result.isInvalid()) return ExprError(); 18202 E = result.get(); 18203 18204 if (!E->isTypeDependent()) { 18205 if (getLangOpts().CPlusPlus) 18206 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 18207 18208 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 18209 if (ERes.isInvalid()) 18210 return ExprError(); 18211 E = ERes.get(); 18212 18213 QualType T = E->getType(); 18214 if (!T->isScalarType()) { // C99 6.8.4.1p1 18215 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 18216 << T << E->getSourceRange(); 18217 return ExprError(); 18218 } 18219 CheckBoolLikeConversion(E, Loc); 18220 } 18221 18222 return E; 18223 } 18224 18225 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 18226 Expr *SubExpr, ConditionKind CK) { 18227 // Empty conditions are valid in for-statements. 18228 if (!SubExpr) 18229 return ConditionResult(); 18230 18231 ExprResult Cond; 18232 switch (CK) { 18233 case ConditionKind::Boolean: 18234 Cond = CheckBooleanCondition(Loc, SubExpr); 18235 break; 18236 18237 case ConditionKind::ConstexprIf: 18238 Cond = CheckBooleanCondition(Loc, SubExpr, true); 18239 break; 18240 18241 case ConditionKind::Switch: 18242 Cond = CheckSwitchCondition(Loc, SubExpr); 18243 break; 18244 } 18245 if (Cond.isInvalid()) 18246 return ConditionError(); 18247 18248 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 18249 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 18250 if (!FullExpr.get()) 18251 return ConditionError(); 18252 18253 return ConditionResult(*this, nullptr, FullExpr, 18254 CK == ConditionKind::ConstexprIf); 18255 } 18256 18257 namespace { 18258 /// A visitor for rebuilding a call to an __unknown_any expression 18259 /// to have an appropriate type. 18260 struct RebuildUnknownAnyFunction 18261 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 18262 18263 Sema &S; 18264 18265 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 18266 18267 ExprResult VisitStmt(Stmt *S) { 18268 llvm_unreachable("unexpected statement!"); 18269 } 18270 18271 ExprResult VisitExpr(Expr *E) { 18272 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 18273 << E->getSourceRange(); 18274 return ExprError(); 18275 } 18276 18277 /// Rebuild an expression which simply semantically wraps another 18278 /// expression which it shares the type and value kind of. 18279 template <class T> ExprResult rebuildSugarExpr(T *E) { 18280 ExprResult SubResult = Visit(E->getSubExpr()); 18281 if (SubResult.isInvalid()) return ExprError(); 18282 18283 Expr *SubExpr = SubResult.get(); 18284 E->setSubExpr(SubExpr); 18285 E->setType(SubExpr->getType()); 18286 E->setValueKind(SubExpr->getValueKind()); 18287 assert(E->getObjectKind() == OK_Ordinary); 18288 return E; 18289 } 18290 18291 ExprResult VisitParenExpr(ParenExpr *E) { 18292 return rebuildSugarExpr(E); 18293 } 18294 18295 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18296 return rebuildSugarExpr(E); 18297 } 18298 18299 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18300 ExprResult SubResult = Visit(E->getSubExpr()); 18301 if (SubResult.isInvalid()) return ExprError(); 18302 18303 Expr *SubExpr = SubResult.get(); 18304 E->setSubExpr(SubExpr); 18305 E->setType(S.Context.getPointerType(SubExpr->getType())); 18306 assert(E->getValueKind() == VK_RValue); 18307 assert(E->getObjectKind() == OK_Ordinary); 18308 return E; 18309 } 18310 18311 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 18312 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 18313 18314 E->setType(VD->getType()); 18315 18316 assert(E->getValueKind() == VK_RValue); 18317 if (S.getLangOpts().CPlusPlus && 18318 !(isa<CXXMethodDecl>(VD) && 18319 cast<CXXMethodDecl>(VD)->isInstance())) 18320 E->setValueKind(VK_LValue); 18321 18322 return E; 18323 } 18324 18325 ExprResult VisitMemberExpr(MemberExpr *E) { 18326 return resolveDecl(E, E->getMemberDecl()); 18327 } 18328 18329 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18330 return resolveDecl(E, E->getDecl()); 18331 } 18332 }; 18333 } 18334 18335 /// Given a function expression of unknown-any type, try to rebuild it 18336 /// to have a function type. 18337 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 18338 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 18339 if (Result.isInvalid()) return ExprError(); 18340 return S.DefaultFunctionArrayConversion(Result.get()); 18341 } 18342 18343 namespace { 18344 /// A visitor for rebuilding an expression of type __unknown_anytype 18345 /// into one which resolves the type directly on the referring 18346 /// expression. Strict preservation of the original source 18347 /// structure is not a goal. 18348 struct RebuildUnknownAnyExpr 18349 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 18350 18351 Sema &S; 18352 18353 /// The current destination type. 18354 QualType DestType; 18355 18356 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 18357 : S(S), DestType(CastType) {} 18358 18359 ExprResult VisitStmt(Stmt *S) { 18360 llvm_unreachable("unexpected statement!"); 18361 } 18362 18363 ExprResult VisitExpr(Expr *E) { 18364 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18365 << E->getSourceRange(); 18366 return ExprError(); 18367 } 18368 18369 ExprResult VisitCallExpr(CallExpr *E); 18370 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 18371 18372 /// Rebuild an expression which simply semantically wraps another 18373 /// expression which it shares the type and value kind of. 18374 template <class T> ExprResult rebuildSugarExpr(T *E) { 18375 ExprResult SubResult = Visit(E->getSubExpr()); 18376 if (SubResult.isInvalid()) return ExprError(); 18377 Expr *SubExpr = SubResult.get(); 18378 E->setSubExpr(SubExpr); 18379 E->setType(SubExpr->getType()); 18380 E->setValueKind(SubExpr->getValueKind()); 18381 assert(E->getObjectKind() == OK_Ordinary); 18382 return E; 18383 } 18384 18385 ExprResult VisitParenExpr(ParenExpr *E) { 18386 return rebuildSugarExpr(E); 18387 } 18388 18389 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18390 return rebuildSugarExpr(E); 18391 } 18392 18393 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18394 const PointerType *Ptr = DestType->getAs<PointerType>(); 18395 if (!Ptr) { 18396 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 18397 << E->getSourceRange(); 18398 return ExprError(); 18399 } 18400 18401 if (isa<CallExpr>(E->getSubExpr())) { 18402 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 18403 << E->getSourceRange(); 18404 return ExprError(); 18405 } 18406 18407 assert(E->getValueKind() == VK_RValue); 18408 assert(E->getObjectKind() == OK_Ordinary); 18409 E->setType(DestType); 18410 18411 // Build the sub-expression as if it were an object of the pointee type. 18412 DestType = Ptr->getPointeeType(); 18413 ExprResult SubResult = Visit(E->getSubExpr()); 18414 if (SubResult.isInvalid()) return ExprError(); 18415 E->setSubExpr(SubResult.get()); 18416 return E; 18417 } 18418 18419 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 18420 18421 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 18422 18423 ExprResult VisitMemberExpr(MemberExpr *E) { 18424 return resolveDecl(E, E->getMemberDecl()); 18425 } 18426 18427 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18428 return resolveDecl(E, E->getDecl()); 18429 } 18430 }; 18431 } 18432 18433 /// Rebuilds a call expression which yielded __unknown_anytype. 18434 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 18435 Expr *CalleeExpr = E->getCallee(); 18436 18437 enum FnKind { 18438 FK_MemberFunction, 18439 FK_FunctionPointer, 18440 FK_BlockPointer 18441 }; 18442 18443 FnKind Kind; 18444 QualType CalleeType = CalleeExpr->getType(); 18445 if (CalleeType == S.Context.BoundMemberTy) { 18446 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 18447 Kind = FK_MemberFunction; 18448 CalleeType = Expr::findBoundMemberType(CalleeExpr); 18449 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 18450 CalleeType = Ptr->getPointeeType(); 18451 Kind = FK_FunctionPointer; 18452 } else { 18453 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 18454 Kind = FK_BlockPointer; 18455 } 18456 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 18457 18458 // Verify that this is a legal result type of a function. 18459 if (DestType->isArrayType() || DestType->isFunctionType()) { 18460 unsigned diagID = diag::err_func_returning_array_function; 18461 if (Kind == FK_BlockPointer) 18462 diagID = diag::err_block_returning_array_function; 18463 18464 S.Diag(E->getExprLoc(), diagID) 18465 << DestType->isFunctionType() << DestType; 18466 return ExprError(); 18467 } 18468 18469 // Otherwise, go ahead and set DestType as the call's result. 18470 E->setType(DestType.getNonLValueExprType(S.Context)); 18471 E->setValueKind(Expr::getValueKindForType(DestType)); 18472 assert(E->getObjectKind() == OK_Ordinary); 18473 18474 // Rebuild the function type, replacing the result type with DestType. 18475 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 18476 if (Proto) { 18477 // __unknown_anytype(...) is a special case used by the debugger when 18478 // it has no idea what a function's signature is. 18479 // 18480 // We want to build this call essentially under the K&R 18481 // unprototyped rules, but making a FunctionNoProtoType in C++ 18482 // would foul up all sorts of assumptions. However, we cannot 18483 // simply pass all arguments as variadic arguments, nor can we 18484 // portably just call the function under a non-variadic type; see 18485 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 18486 // However, it turns out that in practice it is generally safe to 18487 // call a function declared as "A foo(B,C,D);" under the prototype 18488 // "A foo(B,C,D,...);". The only known exception is with the 18489 // Windows ABI, where any variadic function is implicitly cdecl 18490 // regardless of its normal CC. Therefore we change the parameter 18491 // types to match the types of the arguments. 18492 // 18493 // This is a hack, but it is far superior to moving the 18494 // corresponding target-specific code from IR-gen to Sema/AST. 18495 18496 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 18497 SmallVector<QualType, 8> ArgTypes; 18498 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 18499 ArgTypes.reserve(E->getNumArgs()); 18500 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 18501 Expr *Arg = E->getArg(i); 18502 QualType ArgType = Arg->getType(); 18503 if (E->isLValue()) { 18504 ArgType = S.Context.getLValueReferenceType(ArgType); 18505 } else if (E->isXValue()) { 18506 ArgType = S.Context.getRValueReferenceType(ArgType); 18507 } 18508 ArgTypes.push_back(ArgType); 18509 } 18510 ParamTypes = ArgTypes; 18511 } 18512 DestType = S.Context.getFunctionType(DestType, ParamTypes, 18513 Proto->getExtProtoInfo()); 18514 } else { 18515 DestType = S.Context.getFunctionNoProtoType(DestType, 18516 FnType->getExtInfo()); 18517 } 18518 18519 // Rebuild the appropriate pointer-to-function type. 18520 switch (Kind) { 18521 case FK_MemberFunction: 18522 // Nothing to do. 18523 break; 18524 18525 case FK_FunctionPointer: 18526 DestType = S.Context.getPointerType(DestType); 18527 break; 18528 18529 case FK_BlockPointer: 18530 DestType = S.Context.getBlockPointerType(DestType); 18531 break; 18532 } 18533 18534 // Finally, we can recurse. 18535 ExprResult CalleeResult = Visit(CalleeExpr); 18536 if (!CalleeResult.isUsable()) return ExprError(); 18537 E->setCallee(CalleeResult.get()); 18538 18539 // Bind a temporary if necessary. 18540 return S.MaybeBindToTemporary(E); 18541 } 18542 18543 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 18544 // Verify that this is a legal result type of a call. 18545 if (DestType->isArrayType() || DestType->isFunctionType()) { 18546 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 18547 << DestType->isFunctionType() << DestType; 18548 return ExprError(); 18549 } 18550 18551 // Rewrite the method result type if available. 18552 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 18553 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 18554 Method->setReturnType(DestType); 18555 } 18556 18557 // Change the type of the message. 18558 E->setType(DestType.getNonReferenceType()); 18559 E->setValueKind(Expr::getValueKindForType(DestType)); 18560 18561 return S.MaybeBindToTemporary(E); 18562 } 18563 18564 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 18565 // The only case we should ever see here is a function-to-pointer decay. 18566 if (E->getCastKind() == CK_FunctionToPointerDecay) { 18567 assert(E->getValueKind() == VK_RValue); 18568 assert(E->getObjectKind() == OK_Ordinary); 18569 18570 E->setType(DestType); 18571 18572 // Rebuild the sub-expression as the pointee (function) type. 18573 DestType = DestType->castAs<PointerType>()->getPointeeType(); 18574 18575 ExprResult Result = Visit(E->getSubExpr()); 18576 if (!Result.isUsable()) return ExprError(); 18577 18578 E->setSubExpr(Result.get()); 18579 return E; 18580 } else if (E->getCastKind() == CK_LValueToRValue) { 18581 assert(E->getValueKind() == VK_RValue); 18582 assert(E->getObjectKind() == OK_Ordinary); 18583 18584 assert(isa<BlockPointerType>(E->getType())); 18585 18586 E->setType(DestType); 18587 18588 // The sub-expression has to be a lvalue reference, so rebuild it as such. 18589 DestType = S.Context.getLValueReferenceType(DestType); 18590 18591 ExprResult Result = Visit(E->getSubExpr()); 18592 if (!Result.isUsable()) return ExprError(); 18593 18594 E->setSubExpr(Result.get()); 18595 return E; 18596 } else { 18597 llvm_unreachable("Unhandled cast type!"); 18598 } 18599 } 18600 18601 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 18602 ExprValueKind ValueKind = VK_LValue; 18603 QualType Type = DestType; 18604 18605 // We know how to make this work for certain kinds of decls: 18606 18607 // - functions 18608 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 18609 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 18610 DestType = Ptr->getPointeeType(); 18611 ExprResult Result = resolveDecl(E, VD); 18612 if (Result.isInvalid()) return ExprError(); 18613 return S.ImpCastExprToType(Result.get(), Type, 18614 CK_FunctionToPointerDecay, VK_RValue); 18615 } 18616 18617 if (!Type->isFunctionType()) { 18618 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 18619 << VD << E->getSourceRange(); 18620 return ExprError(); 18621 } 18622 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 18623 // We must match the FunctionDecl's type to the hack introduced in 18624 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 18625 // type. See the lengthy commentary in that routine. 18626 QualType FDT = FD->getType(); 18627 const FunctionType *FnType = FDT->castAs<FunctionType>(); 18628 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 18629 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 18630 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 18631 SourceLocation Loc = FD->getLocation(); 18632 FunctionDecl *NewFD = FunctionDecl::Create( 18633 S.Context, FD->getDeclContext(), Loc, Loc, 18634 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 18635 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 18636 /*ConstexprKind*/ CSK_unspecified); 18637 18638 if (FD->getQualifier()) 18639 NewFD->setQualifierInfo(FD->getQualifierLoc()); 18640 18641 SmallVector<ParmVarDecl*, 16> Params; 18642 for (const auto &AI : FT->param_types()) { 18643 ParmVarDecl *Param = 18644 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 18645 Param->setScopeInfo(0, Params.size()); 18646 Params.push_back(Param); 18647 } 18648 NewFD->setParams(Params); 18649 DRE->setDecl(NewFD); 18650 VD = DRE->getDecl(); 18651 } 18652 } 18653 18654 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 18655 if (MD->isInstance()) { 18656 ValueKind = VK_RValue; 18657 Type = S.Context.BoundMemberTy; 18658 } 18659 18660 // Function references aren't l-values in C. 18661 if (!S.getLangOpts().CPlusPlus) 18662 ValueKind = VK_RValue; 18663 18664 // - variables 18665 } else if (isa<VarDecl>(VD)) { 18666 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 18667 Type = RefTy->getPointeeType(); 18668 } else if (Type->isFunctionType()) { 18669 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 18670 << VD << E->getSourceRange(); 18671 return ExprError(); 18672 } 18673 18674 // - nothing else 18675 } else { 18676 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 18677 << VD << E->getSourceRange(); 18678 return ExprError(); 18679 } 18680 18681 // Modifying the declaration like this is friendly to IR-gen but 18682 // also really dangerous. 18683 VD->setType(DestType); 18684 E->setType(Type); 18685 E->setValueKind(ValueKind); 18686 return E; 18687 } 18688 18689 /// Check a cast of an unknown-any type. We intentionally only 18690 /// trigger this for C-style casts. 18691 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 18692 Expr *CastExpr, CastKind &CastKind, 18693 ExprValueKind &VK, CXXCastPath &Path) { 18694 // The type we're casting to must be either void or complete. 18695 if (!CastType->isVoidType() && 18696 RequireCompleteType(TypeRange.getBegin(), CastType, 18697 diag::err_typecheck_cast_to_incomplete)) 18698 return ExprError(); 18699 18700 // Rewrite the casted expression from scratch. 18701 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 18702 if (!result.isUsable()) return ExprError(); 18703 18704 CastExpr = result.get(); 18705 VK = CastExpr->getValueKind(); 18706 CastKind = CK_NoOp; 18707 18708 return CastExpr; 18709 } 18710 18711 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 18712 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 18713 } 18714 18715 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 18716 Expr *arg, QualType ¶mType) { 18717 // If the syntactic form of the argument is not an explicit cast of 18718 // any sort, just do default argument promotion. 18719 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 18720 if (!castArg) { 18721 ExprResult result = DefaultArgumentPromotion(arg); 18722 if (result.isInvalid()) return ExprError(); 18723 paramType = result.get()->getType(); 18724 return result; 18725 } 18726 18727 // Otherwise, use the type that was written in the explicit cast. 18728 assert(!arg->hasPlaceholderType()); 18729 paramType = castArg->getTypeAsWritten(); 18730 18731 // Copy-initialize a parameter of that type. 18732 InitializedEntity entity = 18733 InitializedEntity::InitializeParameter(Context, paramType, 18734 /*consumed*/ false); 18735 return PerformCopyInitialization(entity, callLoc, arg); 18736 } 18737 18738 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 18739 Expr *orig = E; 18740 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 18741 while (true) { 18742 E = E->IgnoreParenImpCasts(); 18743 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 18744 E = call->getCallee(); 18745 diagID = diag::err_uncasted_call_of_unknown_any; 18746 } else { 18747 break; 18748 } 18749 } 18750 18751 SourceLocation loc; 18752 NamedDecl *d; 18753 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 18754 loc = ref->getLocation(); 18755 d = ref->getDecl(); 18756 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 18757 loc = mem->getMemberLoc(); 18758 d = mem->getMemberDecl(); 18759 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 18760 diagID = diag::err_uncasted_call_of_unknown_any; 18761 loc = msg->getSelectorStartLoc(); 18762 d = msg->getMethodDecl(); 18763 if (!d) { 18764 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 18765 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 18766 << orig->getSourceRange(); 18767 return ExprError(); 18768 } 18769 } else { 18770 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18771 << E->getSourceRange(); 18772 return ExprError(); 18773 } 18774 18775 S.Diag(loc, diagID) << d << orig->getSourceRange(); 18776 18777 // Never recoverable. 18778 return ExprError(); 18779 } 18780 18781 /// Check for operands with placeholder types and complain if found. 18782 /// Returns ExprError() if there was an error and no recovery was possible. 18783 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 18784 if (!getLangOpts().CPlusPlus) { 18785 // C cannot handle TypoExpr nodes on either side of a binop because it 18786 // doesn't handle dependent types properly, so make sure any TypoExprs have 18787 // been dealt with before checking the operands. 18788 ExprResult Result = CorrectDelayedTyposInExpr(E); 18789 if (!Result.isUsable()) return ExprError(); 18790 E = Result.get(); 18791 } 18792 18793 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 18794 if (!placeholderType) return E; 18795 18796 switch (placeholderType->getKind()) { 18797 18798 // Overloaded expressions. 18799 case BuiltinType::Overload: { 18800 // Try to resolve a single function template specialization. 18801 // This is obligatory. 18802 ExprResult Result = E; 18803 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 18804 return Result; 18805 18806 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 18807 // leaves Result unchanged on failure. 18808 Result = E; 18809 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 18810 return Result; 18811 18812 // If that failed, try to recover with a call. 18813 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 18814 /*complain*/ true); 18815 return Result; 18816 } 18817 18818 // Bound member functions. 18819 case BuiltinType::BoundMember: { 18820 ExprResult result = E; 18821 const Expr *BME = E->IgnoreParens(); 18822 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 18823 // Try to give a nicer diagnostic if it is a bound member that we recognize. 18824 if (isa<CXXPseudoDestructorExpr>(BME)) { 18825 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 18826 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 18827 if (ME->getMemberNameInfo().getName().getNameKind() == 18828 DeclarationName::CXXDestructorName) 18829 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 18830 } 18831 tryToRecoverWithCall(result, PD, 18832 /*complain*/ true); 18833 return result; 18834 } 18835 18836 // ARC unbridged casts. 18837 case BuiltinType::ARCUnbridgedCast: { 18838 Expr *realCast = stripARCUnbridgedCast(E); 18839 diagnoseARCUnbridgedCast(realCast); 18840 return realCast; 18841 } 18842 18843 // Expressions of unknown type. 18844 case BuiltinType::UnknownAny: 18845 return diagnoseUnknownAnyExpr(*this, E); 18846 18847 // Pseudo-objects. 18848 case BuiltinType::PseudoObject: 18849 return checkPseudoObjectRValue(E); 18850 18851 case BuiltinType::BuiltinFn: { 18852 // Accept __noop without parens by implicitly converting it to a call expr. 18853 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 18854 if (DRE) { 18855 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 18856 if (FD->getBuiltinID() == Builtin::BI__noop) { 18857 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 18858 CK_BuiltinFnToFnPtr) 18859 .get(); 18860 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 18861 VK_RValue, SourceLocation()); 18862 } 18863 } 18864 18865 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 18866 return ExprError(); 18867 } 18868 18869 // Expressions of unknown type. 18870 case BuiltinType::OMPArraySection: 18871 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 18872 return ExprError(); 18873 18874 // Expressions of unknown type. 18875 case BuiltinType::OMPArrayShaping: 18876 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 18877 18878 case BuiltinType::OMPIterator: 18879 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 18880 18881 // Everything else should be impossible. 18882 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 18883 case BuiltinType::Id: 18884 #include "clang/Basic/OpenCLImageTypes.def" 18885 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 18886 case BuiltinType::Id: 18887 #include "clang/Basic/OpenCLExtensionTypes.def" 18888 #define SVE_TYPE(Name, Id, SingletonId) \ 18889 case BuiltinType::Id: 18890 #include "clang/Basic/AArch64SVEACLETypes.def" 18891 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 18892 #define PLACEHOLDER_TYPE(Id, SingletonId) 18893 #include "clang/AST/BuiltinTypes.def" 18894 break; 18895 } 18896 18897 llvm_unreachable("invalid placeholder type!"); 18898 } 18899 18900 bool Sema::CheckCaseExpression(Expr *E) { 18901 if (E->isTypeDependent()) 18902 return true; 18903 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 18904 return E->getType()->isIntegralOrEnumerationType(); 18905 return false; 18906 } 18907 18908 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 18909 ExprResult 18910 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 18911 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 18912 "Unknown Objective-C Boolean value!"); 18913 QualType BoolT = Context.ObjCBuiltinBoolTy; 18914 if (!Context.getBOOLDecl()) { 18915 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 18916 Sema::LookupOrdinaryName); 18917 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 18918 NamedDecl *ND = Result.getFoundDecl(); 18919 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 18920 Context.setBOOLDecl(TD); 18921 } 18922 } 18923 if (Context.getBOOLDecl()) 18924 BoolT = Context.getBOOLType(); 18925 return new (Context) 18926 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 18927 } 18928 18929 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 18930 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 18931 SourceLocation RParen) { 18932 18933 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 18934 18935 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 18936 return Spec.getPlatform() == Platform; 18937 }); 18938 18939 VersionTuple Version; 18940 if (Spec != AvailSpecs.end()) 18941 Version = Spec->getVersion(); 18942 18943 // The use of `@available` in the enclosing function should be analyzed to 18944 // warn when it's used inappropriately (i.e. not if(@available)). 18945 if (getCurFunctionOrMethodDecl()) 18946 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 18947 else if (getCurBlock() || getCurLambda()) 18948 getCurFunction()->HasPotentialAvailabilityViolations = true; 18949 18950 return new (Context) 18951 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 18952 } 18953 18954 bool Sema::IsDependentFunctionNameExpr(Expr *E) { 18955 assert(E->isTypeDependent()); 18956 return isa<UnresolvedLookupExpr>(E); 18957 } 18958 18959 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 18960 ArrayRef<Expr *> SubExprs) { 18961 // FIXME: enable it for C++, RecoveryExpr is type-dependent to suppress 18962 // bogus diagnostics and this trick does not work in C. 18963 // FIXME: use containsErrors() to suppress unwanted diags in C. 18964 if (!Context.getLangOpts().RecoveryAST) 18965 return ExprError(); 18966 18967 if (isSFINAEContext()) 18968 return ExprError(); 18969 18970 return RecoveryExpr::Create(Context, Begin, End, SubExprs); 18971 } 18972