1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "UsedDeclVisitor.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/OperationKinds.h" 28 #include "clang/AST/ParentMapContext.h" 29 #include "clang/AST/RecursiveASTVisitor.h" 30 #include "clang/AST/TypeLoc.h" 31 #include "clang/Basic/Builtins.h" 32 #include "clang/Basic/DiagnosticSema.h" 33 #include "clang/Basic/PartialDiagnostic.h" 34 #include "clang/Basic/SourceManager.h" 35 #include "clang/Basic/TargetInfo.h" 36 #include "clang/Lex/LiteralSupport.h" 37 #include "clang/Lex/Preprocessor.h" 38 #include "clang/Sema/AnalysisBasedWarnings.h" 39 #include "clang/Sema/DeclSpec.h" 40 #include "clang/Sema/DelayedDiagnostic.h" 41 #include "clang/Sema/Designator.h" 42 #include "clang/Sema/Initialization.h" 43 #include "clang/Sema/Lookup.h" 44 #include "clang/Sema/Overload.h" 45 #include "clang/Sema/ParsedTemplate.h" 46 #include "clang/Sema/Scope.h" 47 #include "clang/Sema/ScopeInfo.h" 48 #include "clang/Sema/SemaFixItUtils.h" 49 #include "clang/Sema/SemaInternal.h" 50 #include "clang/Sema/Template.h" 51 #include "llvm/ADT/STLExtras.h" 52 #include "llvm/ADT/StringExtras.h" 53 #include "llvm/Support/ConvertUTF.h" 54 #include "llvm/Support/SaveAndRestore.h" 55 56 using namespace clang; 57 using namespace sema; 58 using llvm::RoundingMode; 59 60 /// Determine whether the use of this declaration is valid, without 61 /// emitting diagnostics. 62 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 63 // See if this is an auto-typed variable whose initializer we are parsing. 64 if (ParsingInitForAutoVars.count(D)) 65 return false; 66 67 // See if this is a deleted function. 68 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 69 if (FD->isDeleted()) 70 return false; 71 72 // If the function has a deduced return type, and we can't deduce it, 73 // then we can't use it either. 74 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 75 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 76 return false; 77 78 // See if this is an aligned allocation/deallocation function that is 79 // unavailable. 80 if (TreatUnavailableAsInvalid && 81 isUnavailableAlignedAllocationFunction(*FD)) 82 return false; 83 } 84 85 // See if this function is unavailable. 86 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 87 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 88 return false; 89 90 if (isa<UnresolvedUsingIfExistsDecl>(D)) 91 return false; 92 93 return true; 94 } 95 96 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 97 // Warn if this is used but marked unused. 98 if (const auto *A = D->getAttr<UnusedAttr>()) { 99 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 100 // should diagnose them. 101 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 102 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 103 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 104 if (DC && !DC->hasAttr<UnusedAttr>()) 105 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 106 } 107 } 108 } 109 110 /// Emit a note explaining that this function is deleted. 111 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 112 assert(Decl && Decl->isDeleted()); 113 114 if (Decl->isDefaulted()) { 115 // If the method was explicitly defaulted, point at that declaration. 116 if (!Decl->isImplicit()) 117 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 118 119 // Try to diagnose why this special member function was implicitly 120 // deleted. This might fail, if that reason no longer applies. 121 DiagnoseDeletedDefaultedFunction(Decl); 122 return; 123 } 124 125 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 126 if (Ctor && Ctor->isInheritingConstructor()) 127 return NoteDeletedInheritingConstructor(Ctor); 128 129 Diag(Decl->getLocation(), diag::note_availability_specified_here) 130 << Decl << 1; 131 } 132 133 /// Determine whether a FunctionDecl was ever declared with an 134 /// explicit storage class. 135 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 136 for (auto I : D->redecls()) { 137 if (I->getStorageClass() != SC_None) 138 return true; 139 } 140 return false; 141 } 142 143 /// Check whether we're in an extern inline function and referring to a 144 /// variable or function with internal linkage (C11 6.7.4p3). 145 /// 146 /// This is only a warning because we used to silently accept this code, but 147 /// in many cases it will not behave correctly. This is not enabled in C++ mode 148 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 149 /// and so while there may still be user mistakes, most of the time we can't 150 /// prove that there are errors. 151 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 152 const NamedDecl *D, 153 SourceLocation Loc) { 154 // This is disabled under C++; there are too many ways for this to fire in 155 // contexts where the warning is a false positive, or where it is technically 156 // correct but benign. 157 if (S.getLangOpts().CPlusPlus) 158 return; 159 160 // Check if this is an inlined function or method. 161 FunctionDecl *Current = S.getCurFunctionDecl(); 162 if (!Current) 163 return; 164 if (!Current->isInlined()) 165 return; 166 if (!Current->isExternallyVisible()) 167 return; 168 169 // Check if the decl has internal linkage. 170 if (D->getFormalLinkage() != InternalLinkage) 171 return; 172 173 // Downgrade from ExtWarn to Extension if 174 // (1) the supposedly external inline function is in the main file, 175 // and probably won't be included anywhere else. 176 // (2) the thing we're referencing is a pure function. 177 // (3) the thing we're referencing is another inline function. 178 // This last can give us false negatives, but it's better than warning on 179 // wrappers for simple C library functions. 180 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 181 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 182 if (!DowngradeWarning && UsedFn) 183 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 184 185 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 186 : diag::ext_internal_in_extern_inline) 187 << /*IsVar=*/!UsedFn << D; 188 189 S.MaybeSuggestAddingStaticToDecl(Current); 190 191 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 192 << D; 193 } 194 195 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 196 const FunctionDecl *First = Cur->getFirstDecl(); 197 198 // Suggest "static" on the function, if possible. 199 if (!hasAnyExplicitStorageClass(First)) { 200 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 201 Diag(DeclBegin, diag::note_convert_inline_to_static) 202 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 203 } 204 } 205 206 /// Determine whether the use of this declaration is valid, and 207 /// emit any corresponding diagnostics. 208 /// 209 /// This routine diagnoses various problems with referencing 210 /// declarations that can occur when using a declaration. For example, 211 /// it might warn if a deprecated or unavailable declaration is being 212 /// used, or produce an error (and return true) if a C++0x deleted 213 /// function is being used. 214 /// 215 /// \returns true if there was an error (this declaration cannot be 216 /// referenced), false otherwise. 217 /// 218 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 219 const ObjCInterfaceDecl *UnknownObjCClass, 220 bool ObjCPropertyAccess, 221 bool AvoidPartialAvailabilityChecks, 222 ObjCInterfaceDecl *ClassReceiver) { 223 SourceLocation Loc = Locs.front(); 224 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 225 // If there were any diagnostics suppressed by template argument deduction, 226 // emit them now. 227 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 228 if (Pos != SuppressedDiagnostics.end()) { 229 for (const PartialDiagnosticAt &Suppressed : Pos->second) 230 Diag(Suppressed.first, Suppressed.second); 231 232 // Clear out the list of suppressed diagnostics, so that we don't emit 233 // them again for this specialization. However, we don't obsolete this 234 // entry from the table, because we want to avoid ever emitting these 235 // diagnostics again. 236 Pos->second.clear(); 237 } 238 239 // C++ [basic.start.main]p3: 240 // The function 'main' shall not be used within a program. 241 if (cast<FunctionDecl>(D)->isMain()) 242 Diag(Loc, diag::ext_main_used); 243 244 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 245 } 246 247 // See if this is an auto-typed variable whose initializer we are parsing. 248 if (ParsingInitForAutoVars.count(D)) { 249 if (isa<BindingDecl>(D)) { 250 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 251 << D->getDeclName(); 252 } else { 253 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 254 << D->getDeclName() << cast<VarDecl>(D)->getType(); 255 } 256 return true; 257 } 258 259 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 260 // See if this is a deleted function. 261 if (FD->isDeleted()) { 262 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 263 if (Ctor && Ctor->isInheritingConstructor()) 264 Diag(Loc, diag::err_deleted_inherited_ctor_use) 265 << Ctor->getParent() 266 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 267 else 268 Diag(Loc, diag::err_deleted_function_use); 269 NoteDeletedFunction(FD); 270 return true; 271 } 272 273 // [expr.prim.id]p4 274 // A program that refers explicitly or implicitly to a function with a 275 // trailing requires-clause whose constraint-expression is not satisfied, 276 // other than to declare it, is ill-formed. [...] 277 // 278 // See if this is a function with constraints that need to be satisfied. 279 // Check this before deducing the return type, as it might instantiate the 280 // definition. 281 if (FD->getTrailingRequiresClause()) { 282 ConstraintSatisfaction Satisfaction; 283 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 284 // A diagnostic will have already been generated (non-constant 285 // constraint expression, for example) 286 return true; 287 if (!Satisfaction.IsSatisfied) { 288 Diag(Loc, 289 diag::err_reference_to_function_with_unsatisfied_constraints) 290 << D; 291 DiagnoseUnsatisfiedConstraint(Satisfaction); 292 return true; 293 } 294 } 295 296 // If the function has a deduced return type, and we can't deduce it, 297 // then we can't use it either. 298 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 299 DeduceReturnType(FD, Loc)) 300 return true; 301 302 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 303 return true; 304 305 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 306 return true; 307 } 308 309 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 310 // Lambdas are only default-constructible or assignable in C++2a onwards. 311 if (MD->getParent()->isLambda() && 312 ((isa<CXXConstructorDecl>(MD) && 313 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 314 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 315 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 316 << !isa<CXXConstructorDecl>(MD); 317 } 318 } 319 320 auto getReferencedObjCProp = [](const NamedDecl *D) -> 321 const ObjCPropertyDecl * { 322 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 323 return MD->findPropertyDecl(); 324 return nullptr; 325 }; 326 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 327 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 328 return true; 329 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 330 return true; 331 } 332 333 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 334 // Only the variables omp_in and omp_out are allowed in the combiner. 335 // Only the variables omp_priv and omp_orig are allowed in the 336 // initializer-clause. 337 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 338 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 339 isa<VarDecl>(D)) { 340 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 341 << getCurFunction()->HasOMPDeclareReductionCombiner; 342 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 343 return true; 344 } 345 346 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 347 // List-items in map clauses on this construct may only refer to the declared 348 // variable var and entities that could be referenced by a procedure defined 349 // at the same location 350 if (LangOpts.OpenMP && isa<VarDecl>(D) && 351 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 352 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 353 << getOpenMPDeclareMapperVarName(); 354 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 355 return true; 356 } 357 358 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) { 359 Diag(Loc, diag::err_use_of_empty_using_if_exists); 360 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); 361 return true; 362 } 363 364 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 365 AvoidPartialAvailabilityChecks, ClassReceiver); 366 367 DiagnoseUnusedOfDecl(*this, D, Loc); 368 369 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 370 371 if (auto *VD = dyn_cast<ValueDecl>(D)) 372 checkTypeSupport(VD->getType(), Loc, VD); 373 374 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 375 if (!Context.getTargetInfo().isTLSSupported()) 376 if (const auto *VD = dyn_cast<VarDecl>(D)) 377 if (VD->getTLSKind() != VarDecl::TLS_None) 378 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 379 } 380 381 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 382 !isUnevaluatedContext()) { 383 // C++ [expr.prim.req.nested] p3 384 // A local parameter shall only appear as an unevaluated operand 385 // (Clause 8) within the constraint-expression. 386 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 387 << D; 388 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 389 return true; 390 } 391 392 return false; 393 } 394 395 /// DiagnoseSentinelCalls - This routine checks whether a call or 396 /// message-send is to a declaration with the sentinel attribute, and 397 /// if so, it checks that the requirements of the sentinel are 398 /// satisfied. 399 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 400 ArrayRef<Expr *> Args) { 401 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 402 if (!attr) 403 return; 404 405 // The number of formal parameters of the declaration. 406 unsigned numFormalParams; 407 408 // The kind of declaration. This is also an index into a %select in 409 // the diagnostic. 410 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 411 412 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 413 numFormalParams = MD->param_size(); 414 calleeType = CT_Method; 415 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 416 numFormalParams = FD->param_size(); 417 calleeType = CT_Function; 418 } else if (isa<VarDecl>(D)) { 419 QualType type = cast<ValueDecl>(D)->getType(); 420 const FunctionType *fn = nullptr; 421 if (const PointerType *ptr = type->getAs<PointerType>()) { 422 fn = ptr->getPointeeType()->getAs<FunctionType>(); 423 if (!fn) return; 424 calleeType = CT_Function; 425 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 426 fn = ptr->getPointeeType()->castAs<FunctionType>(); 427 calleeType = CT_Block; 428 } else { 429 return; 430 } 431 432 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 433 numFormalParams = proto->getNumParams(); 434 } else { 435 numFormalParams = 0; 436 } 437 } else { 438 return; 439 } 440 441 // "nullPos" is the number of formal parameters at the end which 442 // effectively count as part of the variadic arguments. This is 443 // useful if you would prefer to not have *any* formal parameters, 444 // but the language forces you to have at least one. 445 unsigned nullPos = attr->getNullPos(); 446 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 447 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 448 449 // The number of arguments which should follow the sentinel. 450 unsigned numArgsAfterSentinel = attr->getSentinel(); 451 452 // If there aren't enough arguments for all the formal parameters, 453 // the sentinel, and the args after the sentinel, complain. 454 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 455 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 456 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 457 return; 458 } 459 460 // Otherwise, find the sentinel expression. 461 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 462 if (!sentinelExpr) return; 463 if (sentinelExpr->isValueDependent()) return; 464 if (Context.isSentinelNullExpr(sentinelExpr)) return; 465 466 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 467 // or 'NULL' if those are actually defined in the context. Only use 468 // 'nil' for ObjC methods, where it's much more likely that the 469 // variadic arguments form a list of object pointers. 470 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 471 std::string NullValue; 472 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 473 NullValue = "nil"; 474 else if (getLangOpts().CPlusPlus11) 475 NullValue = "nullptr"; 476 else if (PP.isMacroDefined("NULL")) 477 NullValue = "NULL"; 478 else 479 NullValue = "(void*) 0"; 480 481 if (MissingNilLoc.isInvalid()) 482 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 483 else 484 Diag(MissingNilLoc, diag::warn_missing_sentinel) 485 << int(calleeType) 486 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 487 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 488 } 489 490 SourceRange Sema::getExprRange(Expr *E) const { 491 return E ? E->getSourceRange() : SourceRange(); 492 } 493 494 //===----------------------------------------------------------------------===// 495 // Standard Promotions and Conversions 496 //===----------------------------------------------------------------------===// 497 498 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 499 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 500 // Handle any placeholder expressions which made it here. 501 if (E->getType()->isPlaceholderType()) { 502 ExprResult result = CheckPlaceholderExpr(E); 503 if (result.isInvalid()) return ExprError(); 504 E = result.get(); 505 } 506 507 QualType Ty = E->getType(); 508 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 509 510 if (Ty->isFunctionType()) { 511 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 512 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 513 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 514 return ExprError(); 515 516 E = ImpCastExprToType(E, Context.getPointerType(Ty), 517 CK_FunctionToPointerDecay).get(); 518 } else if (Ty->isArrayType()) { 519 // In C90 mode, arrays only promote to pointers if the array expression is 520 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 521 // type 'array of type' is converted to an expression that has type 'pointer 522 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 523 // that has type 'array of type' ...". The relevant change is "an lvalue" 524 // (C90) to "an expression" (C99). 525 // 526 // C++ 4.2p1: 527 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 528 // T" can be converted to an rvalue of type "pointer to T". 529 // 530 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { 531 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 532 CK_ArrayToPointerDecay); 533 if (Res.isInvalid()) 534 return ExprError(); 535 E = Res.get(); 536 } 537 } 538 return E; 539 } 540 541 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 542 // Check to see if we are dereferencing a null pointer. If so, 543 // and if not volatile-qualified, this is undefined behavior that the 544 // optimizer will delete, so warn about it. People sometimes try to use this 545 // to get a deterministic trap and are surprised by clang's behavior. This 546 // only handles the pattern "*null", which is a very syntactic check. 547 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 548 if (UO && UO->getOpcode() == UO_Deref && 549 UO->getSubExpr()->getType()->isPointerType()) { 550 const LangAS AS = 551 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 552 if ((!isTargetAddressSpace(AS) || 553 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 554 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 555 S.Context, Expr::NPC_ValueDependentIsNotNull) && 556 !UO->getType().isVolatileQualified()) { 557 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 558 S.PDiag(diag::warn_indirection_through_null) 559 << UO->getSubExpr()->getSourceRange()); 560 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 561 S.PDiag(diag::note_indirection_through_null)); 562 } 563 } 564 } 565 566 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 567 SourceLocation AssignLoc, 568 const Expr* RHS) { 569 const ObjCIvarDecl *IV = OIRE->getDecl(); 570 if (!IV) 571 return; 572 573 DeclarationName MemberName = IV->getDeclName(); 574 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 575 if (!Member || !Member->isStr("isa")) 576 return; 577 578 const Expr *Base = OIRE->getBase(); 579 QualType BaseType = Base->getType(); 580 if (OIRE->isArrow()) 581 BaseType = BaseType->getPointeeType(); 582 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 583 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 584 ObjCInterfaceDecl *ClassDeclared = nullptr; 585 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 586 if (!ClassDeclared->getSuperClass() 587 && (*ClassDeclared->ivar_begin()) == IV) { 588 if (RHS) { 589 NamedDecl *ObjectSetClass = 590 S.LookupSingleName(S.TUScope, 591 &S.Context.Idents.get("object_setClass"), 592 SourceLocation(), S.LookupOrdinaryName); 593 if (ObjectSetClass) { 594 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 595 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 596 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 597 "object_setClass(") 598 << FixItHint::CreateReplacement( 599 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 600 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 601 } 602 else 603 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 604 } else { 605 NamedDecl *ObjectGetClass = 606 S.LookupSingleName(S.TUScope, 607 &S.Context.Idents.get("object_getClass"), 608 SourceLocation(), S.LookupOrdinaryName); 609 if (ObjectGetClass) 610 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 611 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 612 "object_getClass(") 613 << FixItHint::CreateReplacement( 614 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 615 else 616 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 617 } 618 S.Diag(IV->getLocation(), diag::note_ivar_decl); 619 } 620 } 621 } 622 623 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 624 // Handle any placeholder expressions which made it here. 625 if (E->getType()->isPlaceholderType()) { 626 ExprResult result = CheckPlaceholderExpr(E); 627 if (result.isInvalid()) return ExprError(); 628 E = result.get(); 629 } 630 631 // C++ [conv.lval]p1: 632 // A glvalue of a non-function, non-array type T can be 633 // converted to a prvalue. 634 if (!E->isGLValue()) return E; 635 636 QualType T = E->getType(); 637 assert(!T.isNull() && "r-value conversion on typeless expression?"); 638 639 // lvalue-to-rvalue conversion cannot be applied to function or array types. 640 if (T->isFunctionType() || T->isArrayType()) 641 return E; 642 643 // We don't want to throw lvalue-to-rvalue casts on top of 644 // expressions of certain types in C++. 645 if (getLangOpts().CPlusPlus && 646 (E->getType() == Context.OverloadTy || 647 T->isDependentType() || 648 T->isRecordType())) 649 return E; 650 651 // The C standard is actually really unclear on this point, and 652 // DR106 tells us what the result should be but not why. It's 653 // generally best to say that void types just doesn't undergo 654 // lvalue-to-rvalue at all. Note that expressions of unqualified 655 // 'void' type are never l-values, but qualified void can be. 656 if (T->isVoidType()) 657 return E; 658 659 // OpenCL usually rejects direct accesses to values of 'half' type. 660 if (getLangOpts().OpenCL && 661 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 662 T->isHalfType()) { 663 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 664 << 0 << T; 665 return ExprError(); 666 } 667 668 CheckForNullPointerDereference(*this, E); 669 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 670 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 671 &Context.Idents.get("object_getClass"), 672 SourceLocation(), LookupOrdinaryName); 673 if (ObjectGetClass) 674 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 675 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 676 << FixItHint::CreateReplacement( 677 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 678 else 679 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 680 } 681 else if (const ObjCIvarRefExpr *OIRE = 682 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 683 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 684 685 // C++ [conv.lval]p1: 686 // [...] If T is a non-class type, the type of the prvalue is the 687 // cv-unqualified version of T. Otherwise, the type of the 688 // rvalue is T. 689 // 690 // C99 6.3.2.1p2: 691 // If the lvalue has qualified type, the value has the unqualified 692 // version of the type of the lvalue; otherwise, the value has the 693 // type of the lvalue. 694 if (T.hasQualifiers()) 695 T = T.getUnqualifiedType(); 696 697 // Under the MS ABI, lock down the inheritance model now. 698 if (T->isMemberPointerType() && 699 Context.getTargetInfo().getCXXABI().isMicrosoft()) 700 (void)isCompleteType(E->getExprLoc(), T); 701 702 ExprResult Res = CheckLValueToRValueConversionOperand(E); 703 if (Res.isInvalid()) 704 return Res; 705 E = Res.get(); 706 707 // Loading a __weak object implicitly retains the value, so we need a cleanup to 708 // balance that. 709 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 710 Cleanup.setExprNeedsCleanups(true); 711 712 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 713 Cleanup.setExprNeedsCleanups(true); 714 715 // C++ [conv.lval]p3: 716 // If T is cv std::nullptr_t, the result is a null pointer constant. 717 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 718 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, 719 CurFPFeatureOverrides()); 720 721 // C11 6.3.2.1p2: 722 // ... if the lvalue has atomic type, the value has the non-atomic version 723 // of the type of the lvalue ... 724 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 725 T = Atomic->getValueType().getUnqualifiedType(); 726 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 727 nullptr, VK_PRValue, FPOptionsOverride()); 728 } 729 730 return Res; 731 } 732 733 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 734 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 735 if (Res.isInvalid()) 736 return ExprError(); 737 Res = DefaultLvalueConversion(Res.get()); 738 if (Res.isInvalid()) 739 return ExprError(); 740 return Res; 741 } 742 743 /// CallExprUnaryConversions - a special case of an unary conversion 744 /// performed on a function designator of a call expression. 745 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 746 QualType Ty = E->getType(); 747 ExprResult Res = E; 748 // Only do implicit cast for a function type, but not for a pointer 749 // to function type. 750 if (Ty->isFunctionType()) { 751 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 752 CK_FunctionToPointerDecay); 753 if (Res.isInvalid()) 754 return ExprError(); 755 } 756 Res = DefaultLvalueConversion(Res.get()); 757 if (Res.isInvalid()) 758 return ExprError(); 759 return Res.get(); 760 } 761 762 /// UsualUnaryConversions - Performs various conversions that are common to most 763 /// operators (C99 6.3). The conversions of array and function types are 764 /// sometimes suppressed. For example, the array->pointer conversion doesn't 765 /// apply if the array is an argument to the sizeof or address (&) operators. 766 /// In these instances, this routine should *not* be called. 767 ExprResult Sema::UsualUnaryConversions(Expr *E) { 768 // First, convert to an r-value. 769 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 770 if (Res.isInvalid()) 771 return ExprError(); 772 E = Res.get(); 773 774 QualType Ty = E->getType(); 775 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 776 777 // Half FP have to be promoted to float unless it is natively supported 778 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 779 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 780 781 // Try to perform integral promotions if the object has a theoretically 782 // promotable type. 783 if (Ty->isIntegralOrUnscopedEnumerationType()) { 784 // C99 6.3.1.1p2: 785 // 786 // The following may be used in an expression wherever an int or 787 // unsigned int may be used: 788 // - an object or expression with an integer type whose integer 789 // conversion rank is less than or equal to the rank of int 790 // and unsigned int. 791 // - A bit-field of type _Bool, int, signed int, or unsigned int. 792 // 793 // If an int can represent all values of the original type, the 794 // value is converted to an int; otherwise, it is converted to an 795 // unsigned int. These are called the integer promotions. All 796 // other types are unchanged by the integer promotions. 797 798 QualType PTy = Context.isPromotableBitField(E); 799 if (!PTy.isNull()) { 800 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 801 return E; 802 } 803 if (Ty->isPromotableIntegerType()) { 804 QualType PT = Context.getPromotedIntegerType(Ty); 805 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 806 return E; 807 } 808 } 809 return E; 810 } 811 812 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 813 /// do not have a prototype. Arguments that have type float or __fp16 814 /// are promoted to double. All other argument types are converted by 815 /// UsualUnaryConversions(). 816 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 817 QualType Ty = E->getType(); 818 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 819 820 ExprResult Res = UsualUnaryConversions(E); 821 if (Res.isInvalid()) 822 return ExprError(); 823 E = Res.get(); 824 825 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 826 // promote to double. 827 // Note that default argument promotion applies only to float (and 828 // half/fp16); it does not apply to _Float16. 829 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 830 if (BTy && (BTy->getKind() == BuiltinType::Half || 831 BTy->getKind() == BuiltinType::Float)) { 832 if (getLangOpts().OpenCL && 833 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 834 if (BTy->getKind() == BuiltinType::Half) { 835 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 836 } 837 } else { 838 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 839 } 840 } 841 if (BTy && 842 getLangOpts().getExtendIntArgs() == 843 LangOptions::ExtendArgsKind::ExtendTo64 && 844 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && 845 Context.getTypeSizeInChars(BTy) < 846 Context.getTypeSizeInChars(Context.LongLongTy)) { 847 E = (Ty->isUnsignedIntegerType()) 848 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) 849 .get() 850 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); 851 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && 852 "Unexpected typesize for LongLongTy"); 853 } 854 855 // C++ performs lvalue-to-rvalue conversion as a default argument 856 // promotion, even on class types, but note: 857 // C++11 [conv.lval]p2: 858 // When an lvalue-to-rvalue conversion occurs in an unevaluated 859 // operand or a subexpression thereof the value contained in the 860 // referenced object is not accessed. Otherwise, if the glvalue 861 // has a class type, the conversion copy-initializes a temporary 862 // of type T from the glvalue and the result of the conversion 863 // is a prvalue for the temporary. 864 // FIXME: add some way to gate this entire thing for correctness in 865 // potentially potentially evaluated contexts. 866 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 867 ExprResult Temp = PerformCopyInitialization( 868 InitializedEntity::InitializeTemporary(E->getType()), 869 E->getExprLoc(), E); 870 if (Temp.isInvalid()) 871 return ExprError(); 872 E = Temp.get(); 873 } 874 875 return E; 876 } 877 878 /// Determine the degree of POD-ness for an expression. 879 /// Incomplete types are considered POD, since this check can be performed 880 /// when we're in an unevaluated context. 881 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 882 if (Ty->isIncompleteType()) { 883 // C++11 [expr.call]p7: 884 // After these conversions, if the argument does not have arithmetic, 885 // enumeration, pointer, pointer to member, or class type, the program 886 // is ill-formed. 887 // 888 // Since we've already performed array-to-pointer and function-to-pointer 889 // decay, the only such type in C++ is cv void. This also handles 890 // initializer lists as variadic arguments. 891 if (Ty->isVoidType()) 892 return VAK_Invalid; 893 894 if (Ty->isObjCObjectType()) 895 return VAK_Invalid; 896 return VAK_Valid; 897 } 898 899 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 900 return VAK_Invalid; 901 902 if (Ty.isCXX98PODType(Context)) 903 return VAK_Valid; 904 905 // C++11 [expr.call]p7: 906 // Passing a potentially-evaluated argument of class type (Clause 9) 907 // having a non-trivial copy constructor, a non-trivial move constructor, 908 // or a non-trivial destructor, with no corresponding parameter, 909 // is conditionally-supported with implementation-defined semantics. 910 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 911 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 912 if (!Record->hasNonTrivialCopyConstructor() && 913 !Record->hasNonTrivialMoveConstructor() && 914 !Record->hasNonTrivialDestructor()) 915 return VAK_ValidInCXX11; 916 917 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 918 return VAK_Valid; 919 920 if (Ty->isObjCObjectType()) 921 return VAK_Invalid; 922 923 if (getLangOpts().MSVCCompat) 924 return VAK_MSVCUndefined; 925 926 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 927 // permitted to reject them. We should consider doing so. 928 return VAK_Undefined; 929 } 930 931 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 932 // Don't allow one to pass an Objective-C interface to a vararg. 933 const QualType &Ty = E->getType(); 934 VarArgKind VAK = isValidVarArgType(Ty); 935 936 // Complain about passing non-POD types through varargs. 937 switch (VAK) { 938 case VAK_ValidInCXX11: 939 DiagRuntimeBehavior( 940 E->getBeginLoc(), nullptr, 941 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 942 LLVM_FALLTHROUGH; 943 case VAK_Valid: 944 if (Ty->isRecordType()) { 945 // This is unlikely to be what the user intended. If the class has a 946 // 'c_str' member function, the user probably meant to call that. 947 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 948 PDiag(diag::warn_pass_class_arg_to_vararg) 949 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 950 } 951 break; 952 953 case VAK_Undefined: 954 case VAK_MSVCUndefined: 955 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 956 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 957 << getLangOpts().CPlusPlus11 << Ty << CT); 958 break; 959 960 case VAK_Invalid: 961 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 962 Diag(E->getBeginLoc(), 963 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 964 << Ty << CT; 965 else if (Ty->isObjCObjectType()) 966 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 967 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 968 << Ty << CT); 969 else 970 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 971 << isa<InitListExpr>(E) << Ty << CT; 972 break; 973 } 974 } 975 976 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 977 /// will create a trap if the resulting type is not a POD type. 978 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 979 FunctionDecl *FDecl) { 980 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 981 // Strip the unbridged-cast placeholder expression off, if applicable. 982 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 983 (CT == VariadicMethod || 984 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 985 E = stripARCUnbridgedCast(E); 986 987 // Otherwise, do normal placeholder checking. 988 } else { 989 ExprResult ExprRes = CheckPlaceholderExpr(E); 990 if (ExprRes.isInvalid()) 991 return ExprError(); 992 E = ExprRes.get(); 993 } 994 } 995 996 ExprResult ExprRes = DefaultArgumentPromotion(E); 997 if (ExprRes.isInvalid()) 998 return ExprError(); 999 1000 // Copy blocks to the heap. 1001 if (ExprRes.get()->getType()->isBlockPointerType()) 1002 maybeExtendBlockObject(ExprRes); 1003 1004 E = ExprRes.get(); 1005 1006 // Diagnostics regarding non-POD argument types are 1007 // emitted along with format string checking in Sema::CheckFunctionCall(). 1008 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 1009 // Turn this into a trap. 1010 CXXScopeSpec SS; 1011 SourceLocation TemplateKWLoc; 1012 UnqualifiedId Name; 1013 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1014 E->getBeginLoc()); 1015 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1016 /*HasTrailingLParen=*/true, 1017 /*IsAddressOfOperand=*/false); 1018 if (TrapFn.isInvalid()) 1019 return ExprError(); 1020 1021 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1022 None, E->getEndLoc()); 1023 if (Call.isInvalid()) 1024 return ExprError(); 1025 1026 ExprResult Comma = 1027 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1028 if (Comma.isInvalid()) 1029 return ExprError(); 1030 return Comma.get(); 1031 } 1032 1033 if (!getLangOpts().CPlusPlus && 1034 RequireCompleteType(E->getExprLoc(), E->getType(), 1035 diag::err_call_incomplete_argument)) 1036 return ExprError(); 1037 1038 return E; 1039 } 1040 1041 /// Converts an integer to complex float type. Helper function of 1042 /// UsualArithmeticConversions() 1043 /// 1044 /// \return false if the integer expression is an integer type and is 1045 /// successfully converted to the complex type. 1046 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1047 ExprResult &ComplexExpr, 1048 QualType IntTy, 1049 QualType ComplexTy, 1050 bool SkipCast) { 1051 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1052 if (SkipCast) return false; 1053 if (IntTy->isIntegerType()) { 1054 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1055 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1056 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1057 CK_FloatingRealToComplex); 1058 } else { 1059 assert(IntTy->isComplexIntegerType()); 1060 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1061 CK_IntegralComplexToFloatingComplex); 1062 } 1063 return false; 1064 } 1065 1066 /// Handle arithmetic conversion with complex types. Helper function of 1067 /// UsualArithmeticConversions() 1068 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1069 ExprResult &RHS, QualType LHSType, 1070 QualType RHSType, 1071 bool IsCompAssign) { 1072 // if we have an integer operand, the result is the complex type. 1073 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1074 /*skipCast*/false)) 1075 return LHSType; 1076 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1077 /*skipCast*/IsCompAssign)) 1078 return RHSType; 1079 1080 // This handles complex/complex, complex/float, or float/complex. 1081 // When both operands are complex, the shorter operand is converted to the 1082 // type of the longer, and that is the type of the result. This corresponds 1083 // to what is done when combining two real floating-point operands. 1084 // The fun begins when size promotion occur across type domains. 1085 // From H&S 6.3.4: When one operand is complex and the other is a real 1086 // floating-point type, the less precise type is converted, within it's 1087 // real or complex domain, to the precision of the other type. For example, 1088 // when combining a "long double" with a "double _Complex", the 1089 // "double _Complex" is promoted to "long double _Complex". 1090 1091 // Compute the rank of the two types, regardless of whether they are complex. 1092 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1093 1094 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1095 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1096 QualType LHSElementType = 1097 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1098 QualType RHSElementType = 1099 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1100 1101 QualType ResultType = S.Context.getComplexType(LHSElementType); 1102 if (Order < 0) { 1103 // Promote the precision of the LHS if not an assignment. 1104 ResultType = S.Context.getComplexType(RHSElementType); 1105 if (!IsCompAssign) { 1106 if (LHSComplexType) 1107 LHS = 1108 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1109 else 1110 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1111 } 1112 } else if (Order > 0) { 1113 // Promote the precision of the RHS. 1114 if (RHSComplexType) 1115 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1116 else 1117 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1118 } 1119 return ResultType; 1120 } 1121 1122 /// Handle arithmetic conversion from integer to float. Helper function 1123 /// of UsualArithmeticConversions() 1124 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1125 ExprResult &IntExpr, 1126 QualType FloatTy, QualType IntTy, 1127 bool ConvertFloat, bool ConvertInt) { 1128 if (IntTy->isIntegerType()) { 1129 if (ConvertInt) 1130 // Convert intExpr to the lhs floating point type. 1131 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1132 CK_IntegralToFloating); 1133 return FloatTy; 1134 } 1135 1136 // Convert both sides to the appropriate complex float. 1137 assert(IntTy->isComplexIntegerType()); 1138 QualType result = S.Context.getComplexType(FloatTy); 1139 1140 // _Complex int -> _Complex float 1141 if (ConvertInt) 1142 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1143 CK_IntegralComplexToFloatingComplex); 1144 1145 // float -> _Complex float 1146 if (ConvertFloat) 1147 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1148 CK_FloatingRealToComplex); 1149 1150 return result; 1151 } 1152 1153 /// Handle arithmethic conversion with floating point types. Helper 1154 /// function of UsualArithmeticConversions() 1155 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1156 ExprResult &RHS, QualType LHSType, 1157 QualType RHSType, bool IsCompAssign) { 1158 bool LHSFloat = LHSType->isRealFloatingType(); 1159 bool RHSFloat = RHSType->isRealFloatingType(); 1160 1161 // N1169 4.1.4: If one of the operands has a floating type and the other 1162 // operand has a fixed-point type, the fixed-point operand 1163 // is converted to the floating type [...] 1164 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1165 if (LHSFloat) 1166 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1167 else if (!IsCompAssign) 1168 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1169 return LHSFloat ? LHSType : RHSType; 1170 } 1171 1172 // If we have two real floating types, convert the smaller operand 1173 // to the bigger result. 1174 if (LHSFloat && RHSFloat) { 1175 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1176 if (order > 0) { 1177 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1178 return LHSType; 1179 } 1180 1181 assert(order < 0 && "illegal float comparison"); 1182 if (!IsCompAssign) 1183 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1184 return RHSType; 1185 } 1186 1187 if (LHSFloat) { 1188 // Half FP has to be promoted to float unless it is natively supported 1189 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1190 LHSType = S.Context.FloatTy; 1191 1192 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1193 /*ConvertFloat=*/!IsCompAssign, 1194 /*ConvertInt=*/ true); 1195 } 1196 assert(RHSFloat); 1197 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1198 /*ConvertFloat=*/ true, 1199 /*ConvertInt=*/!IsCompAssign); 1200 } 1201 1202 /// Diagnose attempts to convert between __float128, __ibm128 and 1203 /// long double if there is no support for such conversion. 1204 /// Helper function of UsualArithmeticConversions(). 1205 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1206 QualType RHSType) { 1207 // No issue if either is not a floating point type. 1208 if (!LHSType->isFloatingType() || !RHSType->isFloatingType()) 1209 return false; 1210 1211 // No issue if both have the same 128-bit float semantics. 1212 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1213 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1214 1215 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType; 1216 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType; 1217 1218 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem); 1219 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem); 1220 1221 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() || 1222 &RHSSem != &llvm::APFloat::IEEEquad()) && 1223 (&LHSSem != &llvm::APFloat::IEEEquad() || 1224 &RHSSem != &llvm::APFloat::PPCDoubleDouble())) 1225 return false; 1226 1227 return true; 1228 } 1229 1230 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1231 1232 namespace { 1233 /// These helper callbacks are placed in an anonymous namespace to 1234 /// permit their use as function template parameters. 1235 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1236 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1237 } 1238 1239 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1240 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1241 CK_IntegralComplexCast); 1242 } 1243 } 1244 1245 /// Handle integer arithmetic conversions. Helper function of 1246 /// UsualArithmeticConversions() 1247 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1248 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1249 ExprResult &RHS, QualType LHSType, 1250 QualType RHSType, bool IsCompAssign) { 1251 // The rules for this case are in C99 6.3.1.8 1252 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1253 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1254 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1255 if (LHSSigned == RHSSigned) { 1256 // Same signedness; use the higher-ranked type 1257 if (order >= 0) { 1258 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1259 return LHSType; 1260 } else if (!IsCompAssign) 1261 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1262 return RHSType; 1263 } else if (order != (LHSSigned ? 1 : -1)) { 1264 // The unsigned type has greater than or equal rank to the 1265 // signed type, so use the unsigned type 1266 if (RHSSigned) { 1267 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1268 return LHSType; 1269 } else if (!IsCompAssign) 1270 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1271 return RHSType; 1272 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1273 // The two types are different widths; if we are here, that 1274 // means the signed type is larger than the unsigned type, so 1275 // use the signed type. 1276 if (LHSSigned) { 1277 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1278 return LHSType; 1279 } else if (!IsCompAssign) 1280 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1281 return RHSType; 1282 } else { 1283 // The signed type is higher-ranked than the unsigned type, 1284 // but isn't actually any bigger (like unsigned int and long 1285 // on most 32-bit systems). Use the unsigned type corresponding 1286 // to the signed type. 1287 QualType result = 1288 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1289 RHS = (*doRHSCast)(S, RHS.get(), result); 1290 if (!IsCompAssign) 1291 LHS = (*doLHSCast)(S, LHS.get(), result); 1292 return result; 1293 } 1294 } 1295 1296 /// Handle conversions with GCC complex int extension. Helper function 1297 /// of UsualArithmeticConversions() 1298 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1299 ExprResult &RHS, QualType LHSType, 1300 QualType RHSType, 1301 bool IsCompAssign) { 1302 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1303 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1304 1305 if (LHSComplexInt && RHSComplexInt) { 1306 QualType LHSEltType = LHSComplexInt->getElementType(); 1307 QualType RHSEltType = RHSComplexInt->getElementType(); 1308 QualType ScalarType = 1309 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1310 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1311 1312 return S.Context.getComplexType(ScalarType); 1313 } 1314 1315 if (LHSComplexInt) { 1316 QualType LHSEltType = LHSComplexInt->getElementType(); 1317 QualType ScalarType = 1318 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1319 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1320 QualType ComplexType = S.Context.getComplexType(ScalarType); 1321 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1322 CK_IntegralRealToComplex); 1323 1324 return ComplexType; 1325 } 1326 1327 assert(RHSComplexInt); 1328 1329 QualType RHSEltType = RHSComplexInt->getElementType(); 1330 QualType ScalarType = 1331 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1332 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1333 QualType ComplexType = S.Context.getComplexType(ScalarType); 1334 1335 if (!IsCompAssign) 1336 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1337 CK_IntegralRealToComplex); 1338 return ComplexType; 1339 } 1340 1341 /// Return the rank of a given fixed point or integer type. The value itself 1342 /// doesn't matter, but the values must be increasing with proper increasing 1343 /// rank as described in N1169 4.1.1. 1344 static unsigned GetFixedPointRank(QualType Ty) { 1345 const auto *BTy = Ty->getAs<BuiltinType>(); 1346 assert(BTy && "Expected a builtin type."); 1347 1348 switch (BTy->getKind()) { 1349 case BuiltinType::ShortFract: 1350 case BuiltinType::UShortFract: 1351 case BuiltinType::SatShortFract: 1352 case BuiltinType::SatUShortFract: 1353 return 1; 1354 case BuiltinType::Fract: 1355 case BuiltinType::UFract: 1356 case BuiltinType::SatFract: 1357 case BuiltinType::SatUFract: 1358 return 2; 1359 case BuiltinType::LongFract: 1360 case BuiltinType::ULongFract: 1361 case BuiltinType::SatLongFract: 1362 case BuiltinType::SatULongFract: 1363 return 3; 1364 case BuiltinType::ShortAccum: 1365 case BuiltinType::UShortAccum: 1366 case BuiltinType::SatShortAccum: 1367 case BuiltinType::SatUShortAccum: 1368 return 4; 1369 case BuiltinType::Accum: 1370 case BuiltinType::UAccum: 1371 case BuiltinType::SatAccum: 1372 case BuiltinType::SatUAccum: 1373 return 5; 1374 case BuiltinType::LongAccum: 1375 case BuiltinType::ULongAccum: 1376 case BuiltinType::SatLongAccum: 1377 case BuiltinType::SatULongAccum: 1378 return 6; 1379 default: 1380 if (BTy->isInteger()) 1381 return 0; 1382 llvm_unreachable("Unexpected fixed point or integer type"); 1383 } 1384 } 1385 1386 /// handleFixedPointConversion - Fixed point operations between fixed 1387 /// point types and integers or other fixed point types do not fall under 1388 /// usual arithmetic conversion since these conversions could result in loss 1389 /// of precsision (N1169 4.1.4). These operations should be calculated with 1390 /// the full precision of their result type (N1169 4.1.6.2.1). 1391 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1392 QualType RHSTy) { 1393 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1394 "Expected at least one of the operands to be a fixed point type"); 1395 assert((LHSTy->isFixedPointOrIntegerType() || 1396 RHSTy->isFixedPointOrIntegerType()) && 1397 "Special fixed point arithmetic operation conversions are only " 1398 "applied to ints or other fixed point types"); 1399 1400 // If one operand has signed fixed-point type and the other operand has 1401 // unsigned fixed-point type, then the unsigned fixed-point operand is 1402 // converted to its corresponding signed fixed-point type and the resulting 1403 // type is the type of the converted operand. 1404 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1405 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1406 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1407 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1408 1409 // The result type is the type with the highest rank, whereby a fixed-point 1410 // conversion rank is always greater than an integer conversion rank; if the 1411 // type of either of the operands is a saturating fixedpoint type, the result 1412 // type shall be the saturating fixed-point type corresponding to the type 1413 // with the highest rank; the resulting value is converted (taking into 1414 // account rounding and overflow) to the precision of the resulting type. 1415 // Same ranks between signed and unsigned types are resolved earlier, so both 1416 // types are either signed or both unsigned at this point. 1417 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1418 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1419 1420 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1421 1422 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1423 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1424 1425 return ResultTy; 1426 } 1427 1428 /// Check that the usual arithmetic conversions can be performed on this pair of 1429 /// expressions that might be of enumeration type. 1430 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1431 SourceLocation Loc, 1432 Sema::ArithConvKind ACK) { 1433 // C++2a [expr.arith.conv]p1: 1434 // If one operand is of enumeration type and the other operand is of a 1435 // different enumeration type or a floating-point type, this behavior is 1436 // deprecated ([depr.arith.conv.enum]). 1437 // 1438 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1439 // Eventually we will presumably reject these cases (in C++23 onwards?). 1440 QualType L = LHS->getType(), R = RHS->getType(); 1441 bool LEnum = L->isUnscopedEnumerationType(), 1442 REnum = R->isUnscopedEnumerationType(); 1443 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1444 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1445 (REnum && L->isFloatingType())) { 1446 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1447 ? diag::warn_arith_conv_enum_float_cxx20 1448 : diag::warn_arith_conv_enum_float) 1449 << LHS->getSourceRange() << RHS->getSourceRange() 1450 << (int)ACK << LEnum << L << R; 1451 } else if (!IsCompAssign && LEnum && REnum && 1452 !S.Context.hasSameUnqualifiedType(L, R)) { 1453 unsigned DiagID; 1454 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1455 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1456 // If either enumeration type is unnamed, it's less likely that the 1457 // user cares about this, but this situation is still deprecated in 1458 // C++2a. Use a different warning group. 1459 DiagID = S.getLangOpts().CPlusPlus20 1460 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1461 : diag::warn_arith_conv_mixed_anon_enum_types; 1462 } else if (ACK == Sema::ACK_Conditional) { 1463 // Conditional expressions are separated out because they have 1464 // historically had a different warning flag. 1465 DiagID = S.getLangOpts().CPlusPlus20 1466 ? diag::warn_conditional_mixed_enum_types_cxx20 1467 : diag::warn_conditional_mixed_enum_types; 1468 } else if (ACK == Sema::ACK_Comparison) { 1469 // Comparison expressions are separated out because they have 1470 // historically had a different warning flag. 1471 DiagID = S.getLangOpts().CPlusPlus20 1472 ? diag::warn_comparison_mixed_enum_types_cxx20 1473 : diag::warn_comparison_mixed_enum_types; 1474 } else { 1475 DiagID = S.getLangOpts().CPlusPlus20 1476 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1477 : diag::warn_arith_conv_mixed_enum_types; 1478 } 1479 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1480 << (int)ACK << L << R; 1481 } 1482 } 1483 1484 /// UsualArithmeticConversions - Performs various conversions that are common to 1485 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1486 /// routine returns the first non-arithmetic type found. The client is 1487 /// responsible for emitting appropriate error diagnostics. 1488 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1489 SourceLocation Loc, 1490 ArithConvKind ACK) { 1491 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1492 1493 if (ACK != ACK_CompAssign) { 1494 LHS = UsualUnaryConversions(LHS.get()); 1495 if (LHS.isInvalid()) 1496 return QualType(); 1497 } 1498 1499 RHS = UsualUnaryConversions(RHS.get()); 1500 if (RHS.isInvalid()) 1501 return QualType(); 1502 1503 // For conversion purposes, we ignore any qualifiers. 1504 // For example, "const float" and "float" are equivalent. 1505 QualType LHSType = 1506 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1507 QualType RHSType = 1508 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1509 1510 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1511 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1512 LHSType = AtomicLHS->getValueType(); 1513 1514 // If both types are identical, no conversion is needed. 1515 if (LHSType == RHSType) 1516 return LHSType; 1517 1518 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1519 // The caller can deal with this (e.g. pointer + int). 1520 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1521 return QualType(); 1522 1523 // Apply unary and bitfield promotions to the LHS's type. 1524 QualType LHSUnpromotedType = LHSType; 1525 if (LHSType->isPromotableIntegerType()) 1526 LHSType = Context.getPromotedIntegerType(LHSType); 1527 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1528 if (!LHSBitfieldPromoteTy.isNull()) 1529 LHSType = LHSBitfieldPromoteTy; 1530 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1531 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1532 1533 // If both types are identical, no conversion is needed. 1534 if (LHSType == RHSType) 1535 return LHSType; 1536 1537 // At this point, we have two different arithmetic types. 1538 1539 // Diagnose attempts to convert between __ibm128, __float128 and long double 1540 // where such conversions currently can't be handled. 1541 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1542 return QualType(); 1543 1544 // Handle complex types first (C99 6.3.1.8p1). 1545 if (LHSType->isComplexType() || RHSType->isComplexType()) 1546 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1547 ACK == ACK_CompAssign); 1548 1549 // Now handle "real" floating types (i.e. float, double, long double). 1550 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1551 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1552 ACK == ACK_CompAssign); 1553 1554 // Handle GCC complex int extension. 1555 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1556 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1557 ACK == ACK_CompAssign); 1558 1559 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1560 return handleFixedPointConversion(*this, LHSType, RHSType); 1561 1562 // Finally, we have two differing integer types. 1563 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1564 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1565 } 1566 1567 //===----------------------------------------------------------------------===// 1568 // Semantic Analysis for various Expression Types 1569 //===----------------------------------------------------------------------===// 1570 1571 1572 ExprResult 1573 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1574 SourceLocation DefaultLoc, 1575 SourceLocation RParenLoc, 1576 Expr *ControllingExpr, 1577 ArrayRef<ParsedType> ArgTypes, 1578 ArrayRef<Expr *> ArgExprs) { 1579 unsigned NumAssocs = ArgTypes.size(); 1580 assert(NumAssocs == ArgExprs.size()); 1581 1582 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1583 for (unsigned i = 0; i < NumAssocs; ++i) { 1584 if (ArgTypes[i]) 1585 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1586 else 1587 Types[i] = nullptr; 1588 } 1589 1590 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1591 ControllingExpr, 1592 llvm::makeArrayRef(Types, NumAssocs), 1593 ArgExprs); 1594 delete [] Types; 1595 return ER; 1596 } 1597 1598 ExprResult 1599 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1600 SourceLocation DefaultLoc, 1601 SourceLocation RParenLoc, 1602 Expr *ControllingExpr, 1603 ArrayRef<TypeSourceInfo *> Types, 1604 ArrayRef<Expr *> Exprs) { 1605 unsigned NumAssocs = Types.size(); 1606 assert(NumAssocs == Exprs.size()); 1607 1608 // Decay and strip qualifiers for the controlling expression type, and handle 1609 // placeholder type replacement. See committee discussion from WG14 DR423. 1610 { 1611 EnterExpressionEvaluationContext Unevaluated( 1612 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1613 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1614 if (R.isInvalid()) 1615 return ExprError(); 1616 ControllingExpr = R.get(); 1617 } 1618 1619 // The controlling expression is an unevaluated operand, so side effects are 1620 // likely unintended. 1621 if (!inTemplateInstantiation() && 1622 ControllingExpr->HasSideEffects(Context, false)) 1623 Diag(ControllingExpr->getExprLoc(), 1624 diag::warn_side_effects_unevaluated_context); 1625 1626 bool TypeErrorFound = false, 1627 IsResultDependent = ControllingExpr->isTypeDependent(), 1628 ContainsUnexpandedParameterPack 1629 = ControllingExpr->containsUnexpandedParameterPack(); 1630 1631 for (unsigned i = 0; i < NumAssocs; ++i) { 1632 if (Exprs[i]->containsUnexpandedParameterPack()) 1633 ContainsUnexpandedParameterPack = true; 1634 1635 if (Types[i]) { 1636 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1637 ContainsUnexpandedParameterPack = true; 1638 1639 if (Types[i]->getType()->isDependentType()) { 1640 IsResultDependent = true; 1641 } else { 1642 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1643 // complete object type other than a variably modified type." 1644 unsigned D = 0; 1645 if (Types[i]->getType()->isIncompleteType()) 1646 D = diag::err_assoc_type_incomplete; 1647 else if (!Types[i]->getType()->isObjectType()) 1648 D = diag::err_assoc_type_nonobject; 1649 else if (Types[i]->getType()->isVariablyModifiedType()) 1650 D = diag::err_assoc_type_variably_modified; 1651 1652 if (D != 0) { 1653 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1654 << Types[i]->getTypeLoc().getSourceRange() 1655 << Types[i]->getType(); 1656 TypeErrorFound = true; 1657 } 1658 1659 // C11 6.5.1.1p2 "No two generic associations in the same generic 1660 // selection shall specify compatible types." 1661 for (unsigned j = i+1; j < NumAssocs; ++j) 1662 if (Types[j] && !Types[j]->getType()->isDependentType() && 1663 Context.typesAreCompatible(Types[i]->getType(), 1664 Types[j]->getType())) { 1665 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1666 diag::err_assoc_compatible_types) 1667 << Types[j]->getTypeLoc().getSourceRange() 1668 << Types[j]->getType() 1669 << Types[i]->getType(); 1670 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1671 diag::note_compat_assoc) 1672 << Types[i]->getTypeLoc().getSourceRange() 1673 << Types[i]->getType(); 1674 TypeErrorFound = true; 1675 } 1676 } 1677 } 1678 } 1679 if (TypeErrorFound) 1680 return ExprError(); 1681 1682 // If we determined that the generic selection is result-dependent, don't 1683 // try to compute the result expression. 1684 if (IsResultDependent) 1685 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1686 Exprs, DefaultLoc, RParenLoc, 1687 ContainsUnexpandedParameterPack); 1688 1689 SmallVector<unsigned, 1> CompatIndices; 1690 unsigned DefaultIndex = -1U; 1691 for (unsigned i = 0; i < NumAssocs; ++i) { 1692 if (!Types[i]) 1693 DefaultIndex = i; 1694 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1695 Types[i]->getType())) 1696 CompatIndices.push_back(i); 1697 } 1698 1699 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1700 // type compatible with at most one of the types named in its generic 1701 // association list." 1702 if (CompatIndices.size() > 1) { 1703 // We strip parens here because the controlling expression is typically 1704 // parenthesized in macro definitions. 1705 ControllingExpr = ControllingExpr->IgnoreParens(); 1706 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1707 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1708 << (unsigned)CompatIndices.size(); 1709 for (unsigned I : CompatIndices) { 1710 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1711 diag::note_compat_assoc) 1712 << Types[I]->getTypeLoc().getSourceRange() 1713 << Types[I]->getType(); 1714 } 1715 return ExprError(); 1716 } 1717 1718 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1719 // its controlling expression shall have type compatible with exactly one of 1720 // the types named in its generic association list." 1721 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1722 // We strip parens here because the controlling expression is typically 1723 // parenthesized in macro definitions. 1724 ControllingExpr = ControllingExpr->IgnoreParens(); 1725 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1726 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1727 return ExprError(); 1728 } 1729 1730 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1731 // type name that is compatible with the type of the controlling expression, 1732 // then the result expression of the generic selection is the expression 1733 // in that generic association. Otherwise, the result expression of the 1734 // generic selection is the expression in the default generic association." 1735 unsigned ResultIndex = 1736 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1737 1738 return GenericSelectionExpr::Create( 1739 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1740 ContainsUnexpandedParameterPack, ResultIndex); 1741 } 1742 1743 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1744 /// location of the token and the offset of the ud-suffix within it. 1745 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1746 unsigned Offset) { 1747 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1748 S.getLangOpts()); 1749 } 1750 1751 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1752 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1753 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1754 IdentifierInfo *UDSuffix, 1755 SourceLocation UDSuffixLoc, 1756 ArrayRef<Expr*> Args, 1757 SourceLocation LitEndLoc) { 1758 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1759 1760 QualType ArgTy[2]; 1761 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1762 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1763 if (ArgTy[ArgIdx]->isArrayType()) 1764 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1765 } 1766 1767 DeclarationName OpName = 1768 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1769 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1770 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1771 1772 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1773 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1774 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1775 /*AllowStringTemplatePack*/ false, 1776 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1777 return ExprError(); 1778 1779 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1780 } 1781 1782 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1783 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1784 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1785 /// multiple tokens. However, the common case is that StringToks points to one 1786 /// string. 1787 /// 1788 ExprResult 1789 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1790 assert(!StringToks.empty() && "Must have at least one string!"); 1791 1792 StringLiteralParser Literal(StringToks, PP); 1793 if (Literal.hadError) 1794 return ExprError(); 1795 1796 SmallVector<SourceLocation, 4> StringTokLocs; 1797 for (const Token &Tok : StringToks) 1798 StringTokLocs.push_back(Tok.getLocation()); 1799 1800 QualType CharTy = Context.CharTy; 1801 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1802 if (Literal.isWide()) { 1803 CharTy = Context.getWideCharType(); 1804 Kind = StringLiteral::Wide; 1805 } else if (Literal.isUTF8()) { 1806 if (getLangOpts().Char8) 1807 CharTy = Context.Char8Ty; 1808 Kind = StringLiteral::UTF8; 1809 } else if (Literal.isUTF16()) { 1810 CharTy = Context.Char16Ty; 1811 Kind = StringLiteral::UTF16; 1812 } else if (Literal.isUTF32()) { 1813 CharTy = Context.Char32Ty; 1814 Kind = StringLiteral::UTF32; 1815 } else if (Literal.isPascal()) { 1816 CharTy = Context.UnsignedCharTy; 1817 } 1818 1819 // Warn on initializing an array of char from a u8 string literal; this 1820 // becomes ill-formed in C++2a. 1821 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1822 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1823 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1824 1825 // Create removals for all 'u8' prefixes in the string literal(s). This 1826 // ensures C++2a compatibility (but may change the program behavior when 1827 // built by non-Clang compilers for which the execution character set is 1828 // not always UTF-8). 1829 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1830 SourceLocation RemovalDiagLoc; 1831 for (const Token &Tok : StringToks) { 1832 if (Tok.getKind() == tok::utf8_string_literal) { 1833 if (RemovalDiagLoc.isInvalid()) 1834 RemovalDiagLoc = Tok.getLocation(); 1835 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1836 Tok.getLocation(), 1837 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1838 getSourceManager(), getLangOpts()))); 1839 } 1840 } 1841 Diag(RemovalDiagLoc, RemovalDiag); 1842 } 1843 1844 QualType StrTy = 1845 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1846 1847 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1848 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1849 Kind, Literal.Pascal, StrTy, 1850 &StringTokLocs[0], 1851 StringTokLocs.size()); 1852 if (Literal.getUDSuffix().empty()) 1853 return Lit; 1854 1855 // We're building a user-defined literal. 1856 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1857 SourceLocation UDSuffixLoc = 1858 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1859 Literal.getUDSuffixOffset()); 1860 1861 // Make sure we're allowed user-defined literals here. 1862 if (!UDLScope) 1863 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1864 1865 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1866 // operator "" X (str, len) 1867 QualType SizeType = Context.getSizeType(); 1868 1869 DeclarationName OpName = 1870 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1871 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1872 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1873 1874 QualType ArgTy[] = { 1875 Context.getArrayDecayedType(StrTy), SizeType 1876 }; 1877 1878 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1879 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1880 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1881 /*AllowStringTemplatePack*/ true, 1882 /*DiagnoseMissing*/ true, Lit)) { 1883 1884 case LOLR_Cooked: { 1885 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1886 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1887 StringTokLocs[0]); 1888 Expr *Args[] = { Lit, LenArg }; 1889 1890 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1891 } 1892 1893 case LOLR_Template: { 1894 TemplateArgumentListInfo ExplicitArgs; 1895 TemplateArgument Arg(Lit); 1896 TemplateArgumentLocInfo ArgInfo(Lit); 1897 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1898 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1899 &ExplicitArgs); 1900 } 1901 1902 case LOLR_StringTemplatePack: { 1903 TemplateArgumentListInfo ExplicitArgs; 1904 1905 unsigned CharBits = Context.getIntWidth(CharTy); 1906 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1907 llvm::APSInt Value(CharBits, CharIsUnsigned); 1908 1909 TemplateArgument TypeArg(CharTy); 1910 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1911 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1912 1913 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1914 Value = Lit->getCodeUnit(I); 1915 TemplateArgument Arg(Context, Value, CharTy); 1916 TemplateArgumentLocInfo ArgInfo; 1917 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1918 } 1919 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1920 &ExplicitArgs); 1921 } 1922 case LOLR_Raw: 1923 case LOLR_ErrorNoDiagnostic: 1924 llvm_unreachable("unexpected literal operator lookup result"); 1925 case LOLR_Error: 1926 return ExprError(); 1927 } 1928 llvm_unreachable("unexpected literal operator lookup result"); 1929 } 1930 1931 DeclRefExpr * 1932 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1933 SourceLocation Loc, 1934 const CXXScopeSpec *SS) { 1935 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1936 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1937 } 1938 1939 DeclRefExpr * 1940 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1941 const DeclarationNameInfo &NameInfo, 1942 const CXXScopeSpec *SS, NamedDecl *FoundD, 1943 SourceLocation TemplateKWLoc, 1944 const TemplateArgumentListInfo *TemplateArgs) { 1945 NestedNameSpecifierLoc NNS = 1946 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1947 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1948 TemplateArgs); 1949 } 1950 1951 // CUDA/HIP: Check whether a captured reference variable is referencing a 1952 // host variable in a device or host device lambda. 1953 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1954 VarDecl *VD) { 1955 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1956 return false; 1957 assert(VD->getType()->isReferenceType()); 1958 1959 // Check whether the reference variable is referencing a host variable. 1960 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1961 if (!DRE) 1962 return false; 1963 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 1964 if (!Referee || !Referee->hasGlobalStorage() || 1965 Referee->hasAttr<CUDADeviceAttr>()) 1966 return false; 1967 1968 // Check whether the current function is a device or host device lambda. 1969 // Check whether the reference variable is a capture by getDeclContext() 1970 // since refersToEnclosingVariableOrCapture() is not ready at this point. 1971 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 1972 if (MD && MD->getParent()->isLambda() && 1973 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 1974 VD->getDeclContext() != MD) 1975 return true; 1976 1977 return false; 1978 } 1979 1980 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1981 // A declaration named in an unevaluated operand never constitutes an odr-use. 1982 if (isUnevaluatedContext()) 1983 return NOUR_Unevaluated; 1984 1985 // C++2a [basic.def.odr]p4: 1986 // A variable x whose name appears as a potentially-evaluated expression e 1987 // is odr-used by e unless [...] x is a reference that is usable in 1988 // constant expressions. 1989 // CUDA/HIP: 1990 // If a reference variable referencing a host variable is captured in a 1991 // device or host device lambda, the value of the referee must be copied 1992 // to the capture and the reference variable must be treated as odr-use 1993 // since the value of the referee is not known at compile time and must 1994 // be loaded from the captured. 1995 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1996 if (VD->getType()->isReferenceType() && 1997 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1998 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 1999 VD->isUsableInConstantExpressions(Context)) 2000 return NOUR_Constant; 2001 } 2002 2003 // All remaining non-variable cases constitute an odr-use. For variables, we 2004 // need to wait and see how the expression is used. 2005 return NOUR_None; 2006 } 2007 2008 /// BuildDeclRefExpr - Build an expression that references a 2009 /// declaration that does not require a closure capture. 2010 DeclRefExpr * 2011 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2012 const DeclarationNameInfo &NameInfo, 2013 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2014 SourceLocation TemplateKWLoc, 2015 const TemplateArgumentListInfo *TemplateArgs) { 2016 bool RefersToCapturedVariable = 2017 isa<VarDecl>(D) && 2018 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2019 2020 DeclRefExpr *E = DeclRefExpr::Create( 2021 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2022 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2023 MarkDeclRefReferenced(E); 2024 2025 // C++ [except.spec]p17: 2026 // An exception-specification is considered to be needed when: 2027 // - in an expression, the function is the unique lookup result or 2028 // the selected member of a set of overloaded functions. 2029 // 2030 // We delay doing this until after we've built the function reference and 2031 // marked it as used so that: 2032 // a) if the function is defaulted, we get errors from defining it before / 2033 // instead of errors from computing its exception specification, and 2034 // b) if the function is a defaulted comparison, we can use the body we 2035 // build when defining it as input to the exception specification 2036 // computation rather than computing a new body. 2037 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2038 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2039 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2040 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2041 } 2042 } 2043 2044 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2045 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2046 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2047 getCurFunction()->recordUseOfWeak(E); 2048 2049 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2050 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2051 FD = IFD->getAnonField(); 2052 if (FD) { 2053 UnusedPrivateFields.remove(FD); 2054 // Just in case we're building an illegal pointer-to-member. 2055 if (FD->isBitField()) 2056 E->setObjectKind(OK_BitField); 2057 } 2058 2059 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2060 // designates a bit-field. 2061 if (auto *BD = dyn_cast<BindingDecl>(D)) 2062 if (auto *BE = BD->getBinding()) 2063 E->setObjectKind(BE->getObjectKind()); 2064 2065 return E; 2066 } 2067 2068 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2069 /// possibly a list of template arguments. 2070 /// 2071 /// If this produces template arguments, it is permitted to call 2072 /// DecomposeTemplateName. 2073 /// 2074 /// This actually loses a lot of source location information for 2075 /// non-standard name kinds; we should consider preserving that in 2076 /// some way. 2077 void 2078 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2079 TemplateArgumentListInfo &Buffer, 2080 DeclarationNameInfo &NameInfo, 2081 const TemplateArgumentListInfo *&TemplateArgs) { 2082 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2083 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2084 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2085 2086 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2087 Id.TemplateId->NumArgs); 2088 translateTemplateArguments(TemplateArgsPtr, Buffer); 2089 2090 TemplateName TName = Id.TemplateId->Template.get(); 2091 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2092 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2093 TemplateArgs = &Buffer; 2094 } else { 2095 NameInfo = GetNameFromUnqualifiedId(Id); 2096 TemplateArgs = nullptr; 2097 } 2098 } 2099 2100 static void emitEmptyLookupTypoDiagnostic( 2101 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2102 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2103 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2104 DeclContext *Ctx = 2105 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2106 if (!TC) { 2107 // Emit a special diagnostic for failed member lookups. 2108 // FIXME: computing the declaration context might fail here (?) 2109 if (Ctx) 2110 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2111 << SS.getRange(); 2112 else 2113 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2114 return; 2115 } 2116 2117 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2118 bool DroppedSpecifier = 2119 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2120 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2121 ? diag::note_implicit_param_decl 2122 : diag::note_previous_decl; 2123 if (!Ctx) 2124 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2125 SemaRef.PDiag(NoteID)); 2126 else 2127 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2128 << Typo << Ctx << DroppedSpecifier 2129 << SS.getRange(), 2130 SemaRef.PDiag(NoteID)); 2131 } 2132 2133 /// Diagnose a lookup that found results in an enclosing class during error 2134 /// recovery. This usually indicates that the results were found in a dependent 2135 /// base class that could not be searched as part of a template definition. 2136 /// Always issues a diagnostic (though this may be only a warning in MS 2137 /// compatibility mode). 2138 /// 2139 /// Return \c true if the error is unrecoverable, or \c false if the caller 2140 /// should attempt to recover using these lookup results. 2141 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2142 // During a default argument instantiation the CurContext points 2143 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2144 // function parameter list, hence add an explicit check. 2145 bool isDefaultArgument = 2146 !CodeSynthesisContexts.empty() && 2147 CodeSynthesisContexts.back().Kind == 2148 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2149 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2150 bool isInstance = CurMethod && CurMethod->isInstance() && 2151 R.getNamingClass() == CurMethod->getParent() && 2152 !isDefaultArgument; 2153 2154 // There are two ways we can find a class-scope declaration during template 2155 // instantiation that we did not find in the template definition: if it is a 2156 // member of a dependent base class, or if it is declared after the point of 2157 // use in the same class. Distinguish these by comparing the class in which 2158 // the member was found to the naming class of the lookup. 2159 unsigned DiagID = diag::err_found_in_dependent_base; 2160 unsigned NoteID = diag::note_member_declared_at; 2161 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2162 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2163 : diag::err_found_later_in_class; 2164 } else if (getLangOpts().MSVCCompat) { 2165 DiagID = diag::ext_found_in_dependent_base; 2166 NoteID = diag::note_dependent_member_use; 2167 } 2168 2169 if (isInstance) { 2170 // Give a code modification hint to insert 'this->'. 2171 Diag(R.getNameLoc(), DiagID) 2172 << R.getLookupName() 2173 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2174 CheckCXXThisCapture(R.getNameLoc()); 2175 } else { 2176 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2177 // they're not shadowed). 2178 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2179 } 2180 2181 for (NamedDecl *D : R) 2182 Diag(D->getLocation(), NoteID); 2183 2184 // Return true if we are inside a default argument instantiation 2185 // and the found name refers to an instance member function, otherwise 2186 // the caller will try to create an implicit member call and this is wrong 2187 // for default arguments. 2188 // 2189 // FIXME: Is this special case necessary? We could allow the caller to 2190 // diagnose this. 2191 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2192 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2193 return true; 2194 } 2195 2196 // Tell the callee to try to recover. 2197 return false; 2198 } 2199 2200 /// Diagnose an empty lookup. 2201 /// 2202 /// \return false if new lookup candidates were found 2203 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2204 CorrectionCandidateCallback &CCC, 2205 TemplateArgumentListInfo *ExplicitTemplateArgs, 2206 ArrayRef<Expr *> Args, TypoExpr **Out) { 2207 DeclarationName Name = R.getLookupName(); 2208 2209 unsigned diagnostic = diag::err_undeclared_var_use; 2210 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2211 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2212 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2213 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2214 diagnostic = diag::err_undeclared_use; 2215 diagnostic_suggest = diag::err_undeclared_use_suggest; 2216 } 2217 2218 // If the original lookup was an unqualified lookup, fake an 2219 // unqualified lookup. This is useful when (for example) the 2220 // original lookup would not have found something because it was a 2221 // dependent name. 2222 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2223 while (DC) { 2224 if (isa<CXXRecordDecl>(DC)) { 2225 LookupQualifiedName(R, DC); 2226 2227 if (!R.empty()) { 2228 // Don't give errors about ambiguities in this lookup. 2229 R.suppressDiagnostics(); 2230 2231 // If there's a best viable function among the results, only mention 2232 // that one in the notes. 2233 OverloadCandidateSet Candidates(R.getNameLoc(), 2234 OverloadCandidateSet::CSK_Normal); 2235 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2236 OverloadCandidateSet::iterator Best; 2237 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2238 OR_Success) { 2239 R.clear(); 2240 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2241 R.resolveKind(); 2242 } 2243 2244 return DiagnoseDependentMemberLookup(R); 2245 } 2246 2247 R.clear(); 2248 } 2249 2250 DC = DC->getLookupParent(); 2251 } 2252 2253 // We didn't find anything, so try to correct for a typo. 2254 TypoCorrection Corrected; 2255 if (S && Out) { 2256 SourceLocation TypoLoc = R.getNameLoc(); 2257 assert(!ExplicitTemplateArgs && 2258 "Diagnosing an empty lookup with explicit template args!"); 2259 *Out = CorrectTypoDelayed( 2260 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2261 [=](const TypoCorrection &TC) { 2262 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2263 diagnostic, diagnostic_suggest); 2264 }, 2265 nullptr, CTK_ErrorRecovery); 2266 if (*Out) 2267 return true; 2268 } else if (S && 2269 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2270 S, &SS, CCC, CTK_ErrorRecovery))) { 2271 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2272 bool DroppedSpecifier = 2273 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2274 R.setLookupName(Corrected.getCorrection()); 2275 2276 bool AcceptableWithRecovery = false; 2277 bool AcceptableWithoutRecovery = false; 2278 NamedDecl *ND = Corrected.getFoundDecl(); 2279 if (ND) { 2280 if (Corrected.isOverloaded()) { 2281 OverloadCandidateSet OCS(R.getNameLoc(), 2282 OverloadCandidateSet::CSK_Normal); 2283 OverloadCandidateSet::iterator Best; 2284 for (NamedDecl *CD : Corrected) { 2285 if (FunctionTemplateDecl *FTD = 2286 dyn_cast<FunctionTemplateDecl>(CD)) 2287 AddTemplateOverloadCandidate( 2288 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2289 Args, OCS); 2290 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2291 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2292 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2293 Args, OCS); 2294 } 2295 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2296 case OR_Success: 2297 ND = Best->FoundDecl; 2298 Corrected.setCorrectionDecl(ND); 2299 break; 2300 default: 2301 // FIXME: Arbitrarily pick the first declaration for the note. 2302 Corrected.setCorrectionDecl(ND); 2303 break; 2304 } 2305 } 2306 R.addDecl(ND); 2307 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2308 CXXRecordDecl *Record = nullptr; 2309 if (Corrected.getCorrectionSpecifier()) { 2310 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2311 Record = Ty->getAsCXXRecordDecl(); 2312 } 2313 if (!Record) 2314 Record = cast<CXXRecordDecl>( 2315 ND->getDeclContext()->getRedeclContext()); 2316 R.setNamingClass(Record); 2317 } 2318 2319 auto *UnderlyingND = ND->getUnderlyingDecl(); 2320 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2321 isa<FunctionTemplateDecl>(UnderlyingND); 2322 // FIXME: If we ended up with a typo for a type name or 2323 // Objective-C class name, we're in trouble because the parser 2324 // is in the wrong place to recover. Suggest the typo 2325 // correction, but don't make it a fix-it since we're not going 2326 // to recover well anyway. 2327 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2328 getAsTypeTemplateDecl(UnderlyingND) || 2329 isa<ObjCInterfaceDecl>(UnderlyingND); 2330 } else { 2331 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2332 // because we aren't able to recover. 2333 AcceptableWithoutRecovery = true; 2334 } 2335 2336 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2337 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2338 ? diag::note_implicit_param_decl 2339 : diag::note_previous_decl; 2340 if (SS.isEmpty()) 2341 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2342 PDiag(NoteID), AcceptableWithRecovery); 2343 else 2344 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2345 << Name << computeDeclContext(SS, false) 2346 << DroppedSpecifier << SS.getRange(), 2347 PDiag(NoteID), AcceptableWithRecovery); 2348 2349 // Tell the callee whether to try to recover. 2350 return !AcceptableWithRecovery; 2351 } 2352 } 2353 R.clear(); 2354 2355 // Emit a special diagnostic for failed member lookups. 2356 // FIXME: computing the declaration context might fail here (?) 2357 if (!SS.isEmpty()) { 2358 Diag(R.getNameLoc(), diag::err_no_member) 2359 << Name << computeDeclContext(SS, false) 2360 << SS.getRange(); 2361 return true; 2362 } 2363 2364 // Give up, we can't recover. 2365 Diag(R.getNameLoc(), diagnostic) << Name; 2366 return true; 2367 } 2368 2369 /// In Microsoft mode, if we are inside a template class whose parent class has 2370 /// dependent base classes, and we can't resolve an unqualified identifier, then 2371 /// assume the identifier is a member of a dependent base class. We can only 2372 /// recover successfully in static methods, instance methods, and other contexts 2373 /// where 'this' is available. This doesn't precisely match MSVC's 2374 /// instantiation model, but it's close enough. 2375 static Expr * 2376 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2377 DeclarationNameInfo &NameInfo, 2378 SourceLocation TemplateKWLoc, 2379 const TemplateArgumentListInfo *TemplateArgs) { 2380 // Only try to recover from lookup into dependent bases in static methods or 2381 // contexts where 'this' is available. 2382 QualType ThisType = S.getCurrentThisType(); 2383 const CXXRecordDecl *RD = nullptr; 2384 if (!ThisType.isNull()) 2385 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2386 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2387 RD = MD->getParent(); 2388 if (!RD || !RD->hasAnyDependentBases()) 2389 return nullptr; 2390 2391 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2392 // is available, suggest inserting 'this->' as a fixit. 2393 SourceLocation Loc = NameInfo.getLoc(); 2394 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2395 DB << NameInfo.getName() << RD; 2396 2397 if (!ThisType.isNull()) { 2398 DB << FixItHint::CreateInsertion(Loc, "this->"); 2399 return CXXDependentScopeMemberExpr::Create( 2400 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2401 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2402 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2403 } 2404 2405 // Synthesize a fake NNS that points to the derived class. This will 2406 // perform name lookup during template instantiation. 2407 CXXScopeSpec SS; 2408 auto *NNS = 2409 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2410 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2411 return DependentScopeDeclRefExpr::Create( 2412 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2413 TemplateArgs); 2414 } 2415 2416 ExprResult 2417 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2418 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2419 bool HasTrailingLParen, bool IsAddressOfOperand, 2420 CorrectionCandidateCallback *CCC, 2421 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2422 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2423 "cannot be direct & operand and have a trailing lparen"); 2424 if (SS.isInvalid()) 2425 return ExprError(); 2426 2427 TemplateArgumentListInfo TemplateArgsBuffer; 2428 2429 // Decompose the UnqualifiedId into the following data. 2430 DeclarationNameInfo NameInfo; 2431 const TemplateArgumentListInfo *TemplateArgs; 2432 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2433 2434 DeclarationName Name = NameInfo.getName(); 2435 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2436 SourceLocation NameLoc = NameInfo.getLoc(); 2437 2438 if (II && II->isEditorPlaceholder()) { 2439 // FIXME: When typed placeholders are supported we can create a typed 2440 // placeholder expression node. 2441 return ExprError(); 2442 } 2443 2444 // C++ [temp.dep.expr]p3: 2445 // An id-expression is type-dependent if it contains: 2446 // -- an identifier that was declared with a dependent type, 2447 // (note: handled after lookup) 2448 // -- a template-id that is dependent, 2449 // (note: handled in BuildTemplateIdExpr) 2450 // -- a conversion-function-id that specifies a dependent type, 2451 // -- a nested-name-specifier that contains a class-name that 2452 // names a dependent type. 2453 // Determine whether this is a member of an unknown specialization; 2454 // we need to handle these differently. 2455 bool DependentID = false; 2456 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2457 Name.getCXXNameType()->isDependentType()) { 2458 DependentID = true; 2459 } else if (SS.isSet()) { 2460 if (DeclContext *DC = computeDeclContext(SS, false)) { 2461 if (RequireCompleteDeclContext(SS, DC)) 2462 return ExprError(); 2463 } else { 2464 DependentID = true; 2465 } 2466 } 2467 2468 if (DependentID) 2469 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2470 IsAddressOfOperand, TemplateArgs); 2471 2472 // Perform the required lookup. 2473 LookupResult R(*this, NameInfo, 2474 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2475 ? LookupObjCImplicitSelfParam 2476 : LookupOrdinaryName); 2477 if (TemplateKWLoc.isValid() || TemplateArgs) { 2478 // Lookup the template name again to correctly establish the context in 2479 // which it was found. This is really unfortunate as we already did the 2480 // lookup to determine that it was a template name in the first place. If 2481 // this becomes a performance hit, we can work harder to preserve those 2482 // results until we get here but it's likely not worth it. 2483 bool MemberOfUnknownSpecialization; 2484 AssumedTemplateKind AssumedTemplate; 2485 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2486 MemberOfUnknownSpecialization, TemplateKWLoc, 2487 &AssumedTemplate)) 2488 return ExprError(); 2489 2490 if (MemberOfUnknownSpecialization || 2491 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2492 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2493 IsAddressOfOperand, TemplateArgs); 2494 } else { 2495 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2496 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2497 2498 // If the result might be in a dependent base class, this is a dependent 2499 // id-expression. 2500 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2501 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2502 IsAddressOfOperand, TemplateArgs); 2503 2504 // If this reference is in an Objective-C method, then we need to do 2505 // some special Objective-C lookup, too. 2506 if (IvarLookupFollowUp) { 2507 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2508 if (E.isInvalid()) 2509 return ExprError(); 2510 2511 if (Expr *Ex = E.getAs<Expr>()) 2512 return Ex; 2513 } 2514 } 2515 2516 if (R.isAmbiguous()) 2517 return ExprError(); 2518 2519 // This could be an implicitly declared function reference (legal in C90, 2520 // extension in C99, forbidden in C++). 2521 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2522 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2523 if (D) R.addDecl(D); 2524 } 2525 2526 // Determine whether this name might be a candidate for 2527 // argument-dependent lookup. 2528 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2529 2530 if (R.empty() && !ADL) { 2531 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2532 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2533 TemplateKWLoc, TemplateArgs)) 2534 return E; 2535 } 2536 2537 // Don't diagnose an empty lookup for inline assembly. 2538 if (IsInlineAsmIdentifier) 2539 return ExprError(); 2540 2541 // If this name wasn't predeclared and if this is not a function 2542 // call, diagnose the problem. 2543 TypoExpr *TE = nullptr; 2544 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2545 : nullptr); 2546 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2547 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2548 "Typo correction callback misconfigured"); 2549 if (CCC) { 2550 // Make sure the callback knows what the typo being diagnosed is. 2551 CCC->setTypoName(II); 2552 if (SS.isValid()) 2553 CCC->setTypoNNS(SS.getScopeRep()); 2554 } 2555 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2556 // a template name, but we happen to have always already looked up the name 2557 // before we get here if it must be a template name. 2558 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2559 None, &TE)) { 2560 if (TE && KeywordReplacement) { 2561 auto &State = getTypoExprState(TE); 2562 auto BestTC = State.Consumer->getNextCorrection(); 2563 if (BestTC.isKeyword()) { 2564 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2565 if (State.DiagHandler) 2566 State.DiagHandler(BestTC); 2567 KeywordReplacement->startToken(); 2568 KeywordReplacement->setKind(II->getTokenID()); 2569 KeywordReplacement->setIdentifierInfo(II); 2570 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2571 // Clean up the state associated with the TypoExpr, since it has 2572 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2573 clearDelayedTypo(TE); 2574 // Signal that a correction to a keyword was performed by returning a 2575 // valid-but-null ExprResult. 2576 return (Expr*)nullptr; 2577 } 2578 State.Consumer->resetCorrectionStream(); 2579 } 2580 return TE ? TE : ExprError(); 2581 } 2582 2583 assert(!R.empty() && 2584 "DiagnoseEmptyLookup returned false but added no results"); 2585 2586 // If we found an Objective-C instance variable, let 2587 // LookupInObjCMethod build the appropriate expression to 2588 // reference the ivar. 2589 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2590 R.clear(); 2591 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2592 // In a hopelessly buggy code, Objective-C instance variable 2593 // lookup fails and no expression will be built to reference it. 2594 if (!E.isInvalid() && !E.get()) 2595 return ExprError(); 2596 return E; 2597 } 2598 } 2599 2600 // This is guaranteed from this point on. 2601 assert(!R.empty() || ADL); 2602 2603 // Check whether this might be a C++ implicit instance member access. 2604 // C++ [class.mfct.non-static]p3: 2605 // When an id-expression that is not part of a class member access 2606 // syntax and not used to form a pointer to member is used in the 2607 // body of a non-static member function of class X, if name lookup 2608 // resolves the name in the id-expression to a non-static non-type 2609 // member of some class C, the id-expression is transformed into a 2610 // class member access expression using (*this) as the 2611 // postfix-expression to the left of the . operator. 2612 // 2613 // But we don't actually need to do this for '&' operands if R 2614 // resolved to a function or overloaded function set, because the 2615 // expression is ill-formed if it actually works out to be a 2616 // non-static member function: 2617 // 2618 // C++ [expr.ref]p4: 2619 // Otherwise, if E1.E2 refers to a non-static member function. . . 2620 // [t]he expression can be used only as the left-hand operand of a 2621 // member function call. 2622 // 2623 // There are other safeguards against such uses, but it's important 2624 // to get this right here so that we don't end up making a 2625 // spuriously dependent expression if we're inside a dependent 2626 // instance method. 2627 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2628 bool MightBeImplicitMember; 2629 if (!IsAddressOfOperand) 2630 MightBeImplicitMember = true; 2631 else if (!SS.isEmpty()) 2632 MightBeImplicitMember = false; 2633 else if (R.isOverloadedResult()) 2634 MightBeImplicitMember = false; 2635 else if (R.isUnresolvableResult()) 2636 MightBeImplicitMember = true; 2637 else 2638 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2639 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2640 isa<MSPropertyDecl>(R.getFoundDecl()); 2641 2642 if (MightBeImplicitMember) 2643 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2644 R, TemplateArgs, S); 2645 } 2646 2647 if (TemplateArgs || TemplateKWLoc.isValid()) { 2648 2649 // In C++1y, if this is a variable template id, then check it 2650 // in BuildTemplateIdExpr(). 2651 // The single lookup result must be a variable template declaration. 2652 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2653 Id.TemplateId->Kind == TNK_Var_template) { 2654 assert(R.getAsSingle<VarTemplateDecl>() && 2655 "There should only be one declaration found."); 2656 } 2657 2658 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2659 } 2660 2661 return BuildDeclarationNameExpr(SS, R, ADL); 2662 } 2663 2664 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2665 /// declaration name, generally during template instantiation. 2666 /// There's a large number of things which don't need to be done along 2667 /// this path. 2668 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2669 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2670 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2671 DeclContext *DC = computeDeclContext(SS, false); 2672 if (!DC) 2673 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2674 NameInfo, /*TemplateArgs=*/nullptr); 2675 2676 if (RequireCompleteDeclContext(SS, DC)) 2677 return ExprError(); 2678 2679 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2680 LookupQualifiedName(R, DC); 2681 2682 if (R.isAmbiguous()) 2683 return ExprError(); 2684 2685 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2686 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2687 NameInfo, /*TemplateArgs=*/nullptr); 2688 2689 if (R.empty()) { 2690 // Don't diagnose problems with invalid record decl, the secondary no_member 2691 // diagnostic during template instantiation is likely bogus, e.g. if a class 2692 // is invalid because it's derived from an invalid base class, then missing 2693 // members were likely supposed to be inherited. 2694 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2695 if (CD->isInvalidDecl()) 2696 return ExprError(); 2697 Diag(NameInfo.getLoc(), diag::err_no_member) 2698 << NameInfo.getName() << DC << SS.getRange(); 2699 return ExprError(); 2700 } 2701 2702 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2703 // Diagnose a missing typename if this resolved unambiguously to a type in 2704 // a dependent context. If we can recover with a type, downgrade this to 2705 // a warning in Microsoft compatibility mode. 2706 unsigned DiagID = diag::err_typename_missing; 2707 if (RecoveryTSI && getLangOpts().MSVCCompat) 2708 DiagID = diag::ext_typename_missing; 2709 SourceLocation Loc = SS.getBeginLoc(); 2710 auto D = Diag(Loc, DiagID); 2711 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2712 << SourceRange(Loc, NameInfo.getEndLoc()); 2713 2714 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2715 // context. 2716 if (!RecoveryTSI) 2717 return ExprError(); 2718 2719 // Only issue the fixit if we're prepared to recover. 2720 D << FixItHint::CreateInsertion(Loc, "typename "); 2721 2722 // Recover by pretending this was an elaborated type. 2723 QualType Ty = Context.getTypeDeclType(TD); 2724 TypeLocBuilder TLB; 2725 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2726 2727 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2728 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2729 QTL.setElaboratedKeywordLoc(SourceLocation()); 2730 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2731 2732 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2733 2734 return ExprEmpty(); 2735 } 2736 2737 // Defend against this resolving to an implicit member access. We usually 2738 // won't get here if this might be a legitimate a class member (we end up in 2739 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2740 // a pointer-to-member or in an unevaluated context in C++11. 2741 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2742 return BuildPossibleImplicitMemberExpr(SS, 2743 /*TemplateKWLoc=*/SourceLocation(), 2744 R, /*TemplateArgs=*/nullptr, S); 2745 2746 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2747 } 2748 2749 /// The parser has read a name in, and Sema has detected that we're currently 2750 /// inside an ObjC method. Perform some additional checks and determine if we 2751 /// should form a reference to an ivar. 2752 /// 2753 /// Ideally, most of this would be done by lookup, but there's 2754 /// actually quite a lot of extra work involved. 2755 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2756 IdentifierInfo *II) { 2757 SourceLocation Loc = Lookup.getNameLoc(); 2758 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2759 2760 // Check for error condition which is already reported. 2761 if (!CurMethod) 2762 return DeclResult(true); 2763 2764 // There are two cases to handle here. 1) scoped lookup could have failed, 2765 // in which case we should look for an ivar. 2) scoped lookup could have 2766 // found a decl, but that decl is outside the current instance method (i.e. 2767 // a global variable). In these two cases, we do a lookup for an ivar with 2768 // this name, if the lookup sucedes, we replace it our current decl. 2769 2770 // If we're in a class method, we don't normally want to look for 2771 // ivars. But if we don't find anything else, and there's an 2772 // ivar, that's an error. 2773 bool IsClassMethod = CurMethod->isClassMethod(); 2774 2775 bool LookForIvars; 2776 if (Lookup.empty()) 2777 LookForIvars = true; 2778 else if (IsClassMethod) 2779 LookForIvars = false; 2780 else 2781 LookForIvars = (Lookup.isSingleResult() && 2782 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2783 ObjCInterfaceDecl *IFace = nullptr; 2784 if (LookForIvars) { 2785 IFace = CurMethod->getClassInterface(); 2786 ObjCInterfaceDecl *ClassDeclared; 2787 ObjCIvarDecl *IV = nullptr; 2788 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2789 // Diagnose using an ivar in a class method. 2790 if (IsClassMethod) { 2791 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2792 return DeclResult(true); 2793 } 2794 2795 // Diagnose the use of an ivar outside of the declaring class. 2796 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2797 !declaresSameEntity(ClassDeclared, IFace) && 2798 !getLangOpts().DebuggerSupport) 2799 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2800 2801 // Success. 2802 return IV; 2803 } 2804 } else if (CurMethod->isInstanceMethod()) { 2805 // We should warn if a local variable hides an ivar. 2806 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2807 ObjCInterfaceDecl *ClassDeclared; 2808 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2809 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2810 declaresSameEntity(IFace, ClassDeclared)) 2811 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2812 } 2813 } 2814 } else if (Lookup.isSingleResult() && 2815 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2816 // If accessing a stand-alone ivar in a class method, this is an error. 2817 if (const ObjCIvarDecl *IV = 2818 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2819 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2820 return DeclResult(true); 2821 } 2822 } 2823 2824 // Didn't encounter an error, didn't find an ivar. 2825 return DeclResult(false); 2826 } 2827 2828 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2829 ObjCIvarDecl *IV) { 2830 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2831 assert(CurMethod && CurMethod->isInstanceMethod() && 2832 "should not reference ivar from this context"); 2833 2834 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2835 assert(IFace && "should not reference ivar from this context"); 2836 2837 // If we're referencing an invalid decl, just return this as a silent 2838 // error node. The error diagnostic was already emitted on the decl. 2839 if (IV->isInvalidDecl()) 2840 return ExprError(); 2841 2842 // Check if referencing a field with __attribute__((deprecated)). 2843 if (DiagnoseUseOfDecl(IV, Loc)) 2844 return ExprError(); 2845 2846 // FIXME: This should use a new expr for a direct reference, don't 2847 // turn this into Self->ivar, just return a BareIVarExpr or something. 2848 IdentifierInfo &II = Context.Idents.get("self"); 2849 UnqualifiedId SelfName; 2850 SelfName.setImplicitSelfParam(&II); 2851 CXXScopeSpec SelfScopeSpec; 2852 SourceLocation TemplateKWLoc; 2853 ExprResult SelfExpr = 2854 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2855 /*HasTrailingLParen=*/false, 2856 /*IsAddressOfOperand=*/false); 2857 if (SelfExpr.isInvalid()) 2858 return ExprError(); 2859 2860 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2861 if (SelfExpr.isInvalid()) 2862 return ExprError(); 2863 2864 MarkAnyDeclReferenced(Loc, IV, true); 2865 2866 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2867 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2868 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2869 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2870 2871 ObjCIvarRefExpr *Result = new (Context) 2872 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2873 IV->getLocation(), SelfExpr.get(), true, true); 2874 2875 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2876 if (!isUnevaluatedContext() && 2877 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2878 getCurFunction()->recordUseOfWeak(Result); 2879 } 2880 if (getLangOpts().ObjCAutoRefCount) 2881 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2882 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2883 2884 return Result; 2885 } 2886 2887 /// The parser has read a name in, and Sema has detected that we're currently 2888 /// inside an ObjC method. Perform some additional checks and determine if we 2889 /// should form a reference to an ivar. If so, build an expression referencing 2890 /// that ivar. 2891 ExprResult 2892 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2893 IdentifierInfo *II, bool AllowBuiltinCreation) { 2894 // FIXME: Integrate this lookup step into LookupParsedName. 2895 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2896 if (Ivar.isInvalid()) 2897 return ExprError(); 2898 if (Ivar.isUsable()) 2899 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2900 cast<ObjCIvarDecl>(Ivar.get())); 2901 2902 if (Lookup.empty() && II && AllowBuiltinCreation) 2903 LookupBuiltin(Lookup); 2904 2905 // Sentinel value saying that we didn't do anything special. 2906 return ExprResult(false); 2907 } 2908 2909 /// Cast a base object to a member's actual type. 2910 /// 2911 /// There are two relevant checks: 2912 /// 2913 /// C++ [class.access.base]p7: 2914 /// 2915 /// If a class member access operator [...] is used to access a non-static 2916 /// data member or non-static member function, the reference is ill-formed if 2917 /// the left operand [...] cannot be implicitly converted to a pointer to the 2918 /// naming class of the right operand. 2919 /// 2920 /// C++ [expr.ref]p7: 2921 /// 2922 /// If E2 is a non-static data member or a non-static member function, the 2923 /// program is ill-formed if the class of which E2 is directly a member is an 2924 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2925 /// 2926 /// Note that the latter check does not consider access; the access of the 2927 /// "real" base class is checked as appropriate when checking the access of the 2928 /// member name. 2929 ExprResult 2930 Sema::PerformObjectMemberConversion(Expr *From, 2931 NestedNameSpecifier *Qualifier, 2932 NamedDecl *FoundDecl, 2933 NamedDecl *Member) { 2934 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2935 if (!RD) 2936 return From; 2937 2938 QualType DestRecordType; 2939 QualType DestType; 2940 QualType FromRecordType; 2941 QualType FromType = From->getType(); 2942 bool PointerConversions = false; 2943 if (isa<FieldDecl>(Member)) { 2944 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2945 auto FromPtrType = FromType->getAs<PointerType>(); 2946 DestRecordType = Context.getAddrSpaceQualType( 2947 DestRecordType, FromPtrType 2948 ? FromType->getPointeeType().getAddressSpace() 2949 : FromType.getAddressSpace()); 2950 2951 if (FromPtrType) { 2952 DestType = Context.getPointerType(DestRecordType); 2953 FromRecordType = FromPtrType->getPointeeType(); 2954 PointerConversions = true; 2955 } else { 2956 DestType = DestRecordType; 2957 FromRecordType = FromType; 2958 } 2959 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2960 if (Method->isStatic()) 2961 return From; 2962 2963 DestType = Method->getThisType(); 2964 DestRecordType = DestType->getPointeeType(); 2965 2966 if (FromType->getAs<PointerType>()) { 2967 FromRecordType = FromType->getPointeeType(); 2968 PointerConversions = true; 2969 } else { 2970 FromRecordType = FromType; 2971 DestType = DestRecordType; 2972 } 2973 2974 LangAS FromAS = FromRecordType.getAddressSpace(); 2975 LangAS DestAS = DestRecordType.getAddressSpace(); 2976 if (FromAS != DestAS) { 2977 QualType FromRecordTypeWithoutAS = 2978 Context.removeAddrSpaceQualType(FromRecordType); 2979 QualType FromTypeWithDestAS = 2980 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2981 if (PointerConversions) 2982 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2983 From = ImpCastExprToType(From, FromTypeWithDestAS, 2984 CK_AddressSpaceConversion, From->getValueKind()) 2985 .get(); 2986 } 2987 } else { 2988 // No conversion necessary. 2989 return From; 2990 } 2991 2992 if (DestType->isDependentType() || FromType->isDependentType()) 2993 return From; 2994 2995 // If the unqualified types are the same, no conversion is necessary. 2996 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2997 return From; 2998 2999 SourceRange FromRange = From->getSourceRange(); 3000 SourceLocation FromLoc = FromRange.getBegin(); 3001 3002 ExprValueKind VK = From->getValueKind(); 3003 3004 // C++ [class.member.lookup]p8: 3005 // [...] Ambiguities can often be resolved by qualifying a name with its 3006 // class name. 3007 // 3008 // If the member was a qualified name and the qualified referred to a 3009 // specific base subobject type, we'll cast to that intermediate type 3010 // first and then to the object in which the member is declared. That allows 3011 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3012 // 3013 // class Base { public: int x; }; 3014 // class Derived1 : public Base { }; 3015 // class Derived2 : public Base { }; 3016 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3017 // 3018 // void VeryDerived::f() { 3019 // x = 17; // error: ambiguous base subobjects 3020 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3021 // } 3022 if (Qualifier && Qualifier->getAsType()) { 3023 QualType QType = QualType(Qualifier->getAsType(), 0); 3024 assert(QType->isRecordType() && "lookup done with non-record type"); 3025 3026 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3027 3028 // In C++98, the qualifier type doesn't actually have to be a base 3029 // type of the object type, in which case we just ignore it. 3030 // Otherwise build the appropriate casts. 3031 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3032 CXXCastPath BasePath; 3033 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3034 FromLoc, FromRange, &BasePath)) 3035 return ExprError(); 3036 3037 if (PointerConversions) 3038 QType = Context.getPointerType(QType); 3039 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3040 VK, &BasePath).get(); 3041 3042 FromType = QType; 3043 FromRecordType = QRecordType; 3044 3045 // If the qualifier type was the same as the destination type, 3046 // we're done. 3047 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3048 return From; 3049 } 3050 } 3051 3052 CXXCastPath BasePath; 3053 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3054 FromLoc, FromRange, &BasePath, 3055 /*IgnoreAccess=*/true)) 3056 return ExprError(); 3057 3058 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3059 VK, &BasePath); 3060 } 3061 3062 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3063 const LookupResult &R, 3064 bool HasTrailingLParen) { 3065 // Only when used directly as the postfix-expression of a call. 3066 if (!HasTrailingLParen) 3067 return false; 3068 3069 // Never if a scope specifier was provided. 3070 if (SS.isSet()) 3071 return false; 3072 3073 // Only in C++ or ObjC++. 3074 if (!getLangOpts().CPlusPlus) 3075 return false; 3076 3077 // Turn off ADL when we find certain kinds of declarations during 3078 // normal lookup: 3079 for (NamedDecl *D : R) { 3080 // C++0x [basic.lookup.argdep]p3: 3081 // -- a declaration of a class member 3082 // Since using decls preserve this property, we check this on the 3083 // original decl. 3084 if (D->isCXXClassMember()) 3085 return false; 3086 3087 // C++0x [basic.lookup.argdep]p3: 3088 // -- a block-scope function declaration that is not a 3089 // using-declaration 3090 // NOTE: we also trigger this for function templates (in fact, we 3091 // don't check the decl type at all, since all other decl types 3092 // turn off ADL anyway). 3093 if (isa<UsingShadowDecl>(D)) 3094 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3095 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3096 return false; 3097 3098 // C++0x [basic.lookup.argdep]p3: 3099 // -- a declaration that is neither a function or a function 3100 // template 3101 // And also for builtin functions. 3102 if (isa<FunctionDecl>(D)) { 3103 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3104 3105 // But also builtin functions. 3106 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3107 return false; 3108 } else if (!isa<FunctionTemplateDecl>(D)) 3109 return false; 3110 } 3111 3112 return true; 3113 } 3114 3115 3116 /// Diagnoses obvious problems with the use of the given declaration 3117 /// as an expression. This is only actually called for lookups that 3118 /// were not overloaded, and it doesn't promise that the declaration 3119 /// will in fact be used. 3120 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3121 if (D->isInvalidDecl()) 3122 return true; 3123 3124 if (isa<TypedefNameDecl>(D)) { 3125 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3126 return true; 3127 } 3128 3129 if (isa<ObjCInterfaceDecl>(D)) { 3130 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3131 return true; 3132 } 3133 3134 if (isa<NamespaceDecl>(D)) { 3135 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3136 return true; 3137 } 3138 3139 return false; 3140 } 3141 3142 // Certain multiversion types should be treated as overloaded even when there is 3143 // only one result. 3144 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3145 assert(R.isSingleResult() && "Expected only a single result"); 3146 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3147 return FD && 3148 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3149 } 3150 3151 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3152 LookupResult &R, bool NeedsADL, 3153 bool AcceptInvalidDecl) { 3154 // If this is a single, fully-resolved result and we don't need ADL, 3155 // just build an ordinary singleton decl ref. 3156 if (!NeedsADL && R.isSingleResult() && 3157 !R.getAsSingle<FunctionTemplateDecl>() && 3158 !ShouldLookupResultBeMultiVersionOverload(R)) 3159 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3160 R.getRepresentativeDecl(), nullptr, 3161 AcceptInvalidDecl); 3162 3163 // We only need to check the declaration if there's exactly one 3164 // result, because in the overloaded case the results can only be 3165 // functions and function templates. 3166 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3167 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3168 return ExprError(); 3169 3170 // Otherwise, just build an unresolved lookup expression. Suppress 3171 // any lookup-related diagnostics; we'll hash these out later, when 3172 // we've picked a target. 3173 R.suppressDiagnostics(); 3174 3175 UnresolvedLookupExpr *ULE 3176 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3177 SS.getWithLocInContext(Context), 3178 R.getLookupNameInfo(), 3179 NeedsADL, R.isOverloadedResult(), 3180 R.begin(), R.end()); 3181 3182 return ULE; 3183 } 3184 3185 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3186 ValueDecl *var); 3187 3188 /// Complete semantic analysis for a reference to the given declaration. 3189 ExprResult Sema::BuildDeclarationNameExpr( 3190 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3191 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3192 bool AcceptInvalidDecl) { 3193 assert(D && "Cannot refer to a NULL declaration"); 3194 assert(!isa<FunctionTemplateDecl>(D) && 3195 "Cannot refer unambiguously to a function template"); 3196 3197 SourceLocation Loc = NameInfo.getLoc(); 3198 if (CheckDeclInExpr(*this, Loc, D)) 3199 return ExprError(); 3200 3201 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3202 // Specifically diagnose references to class templates that are missing 3203 // a template argument list. 3204 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3205 return ExprError(); 3206 } 3207 3208 // Make sure that we're referring to a value. 3209 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { 3210 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange(); 3211 Diag(D->getLocation(), diag::note_declared_at); 3212 return ExprError(); 3213 } 3214 3215 // Check whether this declaration can be used. Note that we suppress 3216 // this check when we're going to perform argument-dependent lookup 3217 // on this function name, because this might not be the function 3218 // that overload resolution actually selects. 3219 if (DiagnoseUseOfDecl(D, Loc)) 3220 return ExprError(); 3221 3222 auto *VD = cast<ValueDecl>(D); 3223 3224 // Only create DeclRefExpr's for valid Decl's. 3225 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3226 return ExprError(); 3227 3228 // Handle members of anonymous structs and unions. If we got here, 3229 // and the reference is to a class member indirect field, then this 3230 // must be the subject of a pointer-to-member expression. 3231 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3232 if (!indirectField->isCXXClassMember()) 3233 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3234 indirectField); 3235 3236 QualType type = VD->getType(); 3237 if (type.isNull()) 3238 return ExprError(); 3239 ExprValueKind valueKind = VK_PRValue; 3240 3241 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3242 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3243 // is expanded by some outer '...' in the context of the use. 3244 type = type.getNonPackExpansionType(); 3245 3246 switch (D->getKind()) { 3247 // Ignore all the non-ValueDecl kinds. 3248 #define ABSTRACT_DECL(kind) 3249 #define VALUE(type, base) 3250 #define DECL(type, base) case Decl::type: 3251 #include "clang/AST/DeclNodes.inc" 3252 llvm_unreachable("invalid value decl kind"); 3253 3254 // These shouldn't make it here. 3255 case Decl::ObjCAtDefsField: 3256 llvm_unreachable("forming non-member reference to ivar?"); 3257 3258 // Enum constants are always r-values and never references. 3259 // Unresolved using declarations are dependent. 3260 case Decl::EnumConstant: 3261 case Decl::UnresolvedUsingValue: 3262 case Decl::OMPDeclareReduction: 3263 case Decl::OMPDeclareMapper: 3264 valueKind = VK_PRValue; 3265 break; 3266 3267 // Fields and indirect fields that got here must be for 3268 // pointer-to-member expressions; we just call them l-values for 3269 // internal consistency, because this subexpression doesn't really 3270 // exist in the high-level semantics. 3271 case Decl::Field: 3272 case Decl::IndirectField: 3273 case Decl::ObjCIvar: 3274 assert(getLangOpts().CPlusPlus && "building reference to field in C?"); 3275 3276 // These can't have reference type in well-formed programs, but 3277 // for internal consistency we do this anyway. 3278 type = type.getNonReferenceType(); 3279 valueKind = VK_LValue; 3280 break; 3281 3282 // Non-type template parameters are either l-values or r-values 3283 // depending on the type. 3284 case Decl::NonTypeTemplateParm: { 3285 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3286 type = reftype->getPointeeType(); 3287 valueKind = VK_LValue; // even if the parameter is an r-value reference 3288 break; 3289 } 3290 3291 // [expr.prim.id.unqual]p2: 3292 // If the entity is a template parameter object for a template 3293 // parameter of type T, the type of the expression is const T. 3294 // [...] The expression is an lvalue if the entity is a [...] template 3295 // parameter object. 3296 if (type->isRecordType()) { 3297 type = type.getUnqualifiedType().withConst(); 3298 valueKind = VK_LValue; 3299 break; 3300 } 3301 3302 // For non-references, we need to strip qualifiers just in case 3303 // the template parameter was declared as 'const int' or whatever. 3304 valueKind = VK_PRValue; 3305 type = type.getUnqualifiedType(); 3306 break; 3307 } 3308 3309 case Decl::Var: 3310 case Decl::VarTemplateSpecialization: 3311 case Decl::VarTemplatePartialSpecialization: 3312 case Decl::Decomposition: 3313 case Decl::OMPCapturedExpr: 3314 // In C, "extern void blah;" is valid and is an r-value. 3315 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && 3316 type->isVoidType()) { 3317 valueKind = VK_PRValue; 3318 break; 3319 } 3320 LLVM_FALLTHROUGH; 3321 3322 case Decl::ImplicitParam: 3323 case Decl::ParmVar: { 3324 // These are always l-values. 3325 valueKind = VK_LValue; 3326 type = type.getNonReferenceType(); 3327 3328 // FIXME: Does the addition of const really only apply in 3329 // potentially-evaluated contexts? Since the variable isn't actually 3330 // captured in an unevaluated context, it seems that the answer is no. 3331 if (!isUnevaluatedContext()) { 3332 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3333 if (!CapturedType.isNull()) 3334 type = CapturedType; 3335 } 3336 3337 break; 3338 } 3339 3340 case Decl::Binding: { 3341 // These are always lvalues. 3342 valueKind = VK_LValue; 3343 type = type.getNonReferenceType(); 3344 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3345 // decides how that's supposed to work. 3346 auto *BD = cast<BindingDecl>(VD); 3347 if (BD->getDeclContext() != CurContext) { 3348 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3349 if (DD && DD->hasLocalStorage()) 3350 diagnoseUncapturableValueReference(*this, Loc, BD); 3351 } 3352 break; 3353 } 3354 3355 case Decl::Function: { 3356 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3357 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3358 type = Context.BuiltinFnTy; 3359 valueKind = VK_PRValue; 3360 break; 3361 } 3362 } 3363 3364 const FunctionType *fty = type->castAs<FunctionType>(); 3365 3366 // If we're referring to a function with an __unknown_anytype 3367 // result type, make the entire expression __unknown_anytype. 3368 if (fty->getReturnType() == Context.UnknownAnyTy) { 3369 type = Context.UnknownAnyTy; 3370 valueKind = VK_PRValue; 3371 break; 3372 } 3373 3374 // Functions are l-values in C++. 3375 if (getLangOpts().CPlusPlus) { 3376 valueKind = VK_LValue; 3377 break; 3378 } 3379 3380 // C99 DR 316 says that, if a function type comes from a 3381 // function definition (without a prototype), that type is only 3382 // used for checking compatibility. Therefore, when referencing 3383 // the function, we pretend that we don't have the full function 3384 // type. 3385 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty)) 3386 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3387 fty->getExtInfo()); 3388 3389 // Functions are r-values in C. 3390 valueKind = VK_PRValue; 3391 break; 3392 } 3393 3394 case Decl::CXXDeductionGuide: 3395 llvm_unreachable("building reference to deduction guide"); 3396 3397 case Decl::MSProperty: 3398 case Decl::MSGuid: 3399 case Decl::TemplateParamObject: 3400 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3401 // capture in OpenMP, or duplicated between host and device? 3402 valueKind = VK_LValue; 3403 break; 3404 3405 case Decl::CXXMethod: 3406 // If we're referring to a method with an __unknown_anytype 3407 // result type, make the entire expression __unknown_anytype. 3408 // This should only be possible with a type written directly. 3409 if (const FunctionProtoType *proto = 3410 dyn_cast<FunctionProtoType>(VD->getType())) 3411 if (proto->getReturnType() == Context.UnknownAnyTy) { 3412 type = Context.UnknownAnyTy; 3413 valueKind = VK_PRValue; 3414 break; 3415 } 3416 3417 // C++ methods are l-values if static, r-values if non-static. 3418 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3419 valueKind = VK_LValue; 3420 break; 3421 } 3422 LLVM_FALLTHROUGH; 3423 3424 case Decl::CXXConversion: 3425 case Decl::CXXDestructor: 3426 case Decl::CXXConstructor: 3427 valueKind = VK_PRValue; 3428 break; 3429 } 3430 3431 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3432 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3433 TemplateArgs); 3434 } 3435 3436 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3437 SmallString<32> &Target) { 3438 Target.resize(CharByteWidth * (Source.size() + 1)); 3439 char *ResultPtr = &Target[0]; 3440 const llvm::UTF8 *ErrorPtr; 3441 bool success = 3442 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3443 (void)success; 3444 assert(success); 3445 Target.resize(ResultPtr - &Target[0]); 3446 } 3447 3448 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3449 PredefinedExpr::IdentKind IK) { 3450 // Pick the current block, lambda, captured statement or function. 3451 Decl *currentDecl = nullptr; 3452 if (const BlockScopeInfo *BSI = getCurBlock()) 3453 currentDecl = BSI->TheDecl; 3454 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3455 currentDecl = LSI->CallOperator; 3456 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3457 currentDecl = CSI->TheCapturedDecl; 3458 else 3459 currentDecl = getCurFunctionOrMethodDecl(); 3460 3461 if (!currentDecl) { 3462 Diag(Loc, diag::ext_predef_outside_function); 3463 currentDecl = Context.getTranslationUnitDecl(); 3464 } 3465 3466 QualType ResTy; 3467 StringLiteral *SL = nullptr; 3468 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3469 ResTy = Context.DependentTy; 3470 else { 3471 // Pre-defined identifiers are of type char[x], where x is the length of 3472 // the string. 3473 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3474 unsigned Length = Str.length(); 3475 3476 llvm::APInt LengthI(32, Length + 1); 3477 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3478 ResTy = 3479 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3480 SmallString<32> RawChars; 3481 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3482 Str, RawChars); 3483 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3484 ArrayType::Normal, 3485 /*IndexTypeQuals*/ 0); 3486 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3487 /*Pascal*/ false, ResTy, Loc); 3488 } else { 3489 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3490 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3491 ArrayType::Normal, 3492 /*IndexTypeQuals*/ 0); 3493 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3494 /*Pascal*/ false, ResTy, Loc); 3495 } 3496 } 3497 3498 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3499 } 3500 3501 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3502 SourceLocation LParen, 3503 SourceLocation RParen, 3504 TypeSourceInfo *TSI) { 3505 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); 3506 } 3507 3508 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3509 SourceLocation LParen, 3510 SourceLocation RParen, 3511 ParsedType ParsedTy) { 3512 TypeSourceInfo *TSI = nullptr; 3513 QualType Ty = GetTypeFromParser(ParsedTy, &TSI); 3514 3515 if (Ty.isNull()) 3516 return ExprError(); 3517 if (!TSI) 3518 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); 3519 3520 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); 3521 } 3522 3523 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3524 PredefinedExpr::IdentKind IK; 3525 3526 switch (Kind) { 3527 default: llvm_unreachable("Unknown simple primary expr!"); 3528 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3529 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3530 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3531 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3532 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3533 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3534 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3535 } 3536 3537 return BuildPredefinedExpr(Loc, IK); 3538 } 3539 3540 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3541 SmallString<16> CharBuffer; 3542 bool Invalid = false; 3543 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3544 if (Invalid) 3545 return ExprError(); 3546 3547 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3548 PP, Tok.getKind()); 3549 if (Literal.hadError()) 3550 return ExprError(); 3551 3552 QualType Ty; 3553 if (Literal.isWide()) 3554 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3555 else if (Literal.isUTF8() && getLangOpts().Char8) 3556 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3557 else if (Literal.isUTF16()) 3558 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3559 else if (Literal.isUTF32()) 3560 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3561 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3562 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3563 else 3564 Ty = Context.CharTy; // 'x' -> char in C++ 3565 3566 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3567 if (Literal.isWide()) 3568 Kind = CharacterLiteral::Wide; 3569 else if (Literal.isUTF16()) 3570 Kind = CharacterLiteral::UTF16; 3571 else if (Literal.isUTF32()) 3572 Kind = CharacterLiteral::UTF32; 3573 else if (Literal.isUTF8()) 3574 Kind = CharacterLiteral::UTF8; 3575 3576 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3577 Tok.getLocation()); 3578 3579 if (Literal.getUDSuffix().empty()) 3580 return Lit; 3581 3582 // We're building a user-defined literal. 3583 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3584 SourceLocation UDSuffixLoc = 3585 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3586 3587 // Make sure we're allowed user-defined literals here. 3588 if (!UDLScope) 3589 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3590 3591 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3592 // operator "" X (ch) 3593 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3594 Lit, Tok.getLocation()); 3595 } 3596 3597 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3598 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3599 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3600 Context.IntTy, Loc); 3601 } 3602 3603 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3604 QualType Ty, SourceLocation Loc) { 3605 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3606 3607 using llvm::APFloat; 3608 APFloat Val(Format); 3609 3610 APFloat::opStatus result = Literal.GetFloatValue(Val); 3611 3612 // Overflow is always an error, but underflow is only an error if 3613 // we underflowed to zero (APFloat reports denormals as underflow). 3614 if ((result & APFloat::opOverflow) || 3615 ((result & APFloat::opUnderflow) && Val.isZero())) { 3616 unsigned diagnostic; 3617 SmallString<20> buffer; 3618 if (result & APFloat::opOverflow) { 3619 diagnostic = diag::warn_float_overflow; 3620 APFloat::getLargest(Format).toString(buffer); 3621 } else { 3622 diagnostic = diag::warn_float_underflow; 3623 APFloat::getSmallest(Format).toString(buffer); 3624 } 3625 3626 S.Diag(Loc, diagnostic) 3627 << Ty 3628 << StringRef(buffer.data(), buffer.size()); 3629 } 3630 3631 bool isExact = (result == APFloat::opOK); 3632 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3633 } 3634 3635 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3636 assert(E && "Invalid expression"); 3637 3638 if (E->isValueDependent()) 3639 return false; 3640 3641 QualType QT = E->getType(); 3642 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3643 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3644 return true; 3645 } 3646 3647 llvm::APSInt ValueAPS; 3648 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3649 3650 if (R.isInvalid()) 3651 return true; 3652 3653 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3654 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3655 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3656 << toString(ValueAPS, 10) << ValueIsPositive; 3657 return true; 3658 } 3659 3660 return false; 3661 } 3662 3663 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3664 // Fast path for a single digit (which is quite common). A single digit 3665 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3666 if (Tok.getLength() == 1) { 3667 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3668 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3669 } 3670 3671 SmallString<128> SpellingBuffer; 3672 // NumericLiteralParser wants to overread by one character. Add padding to 3673 // the buffer in case the token is copied to the buffer. If getSpelling() 3674 // returns a StringRef to the memory buffer, it should have a null char at 3675 // the EOF, so it is also safe. 3676 SpellingBuffer.resize(Tok.getLength() + 1); 3677 3678 // Get the spelling of the token, which eliminates trigraphs, etc. 3679 bool Invalid = false; 3680 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3681 if (Invalid) 3682 return ExprError(); 3683 3684 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3685 PP.getSourceManager(), PP.getLangOpts(), 3686 PP.getTargetInfo(), PP.getDiagnostics()); 3687 if (Literal.hadError) 3688 return ExprError(); 3689 3690 if (Literal.hasUDSuffix()) { 3691 // We're building a user-defined literal. 3692 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3693 SourceLocation UDSuffixLoc = 3694 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3695 3696 // Make sure we're allowed user-defined literals here. 3697 if (!UDLScope) 3698 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3699 3700 QualType CookedTy; 3701 if (Literal.isFloatingLiteral()) { 3702 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3703 // long double, the literal is treated as a call of the form 3704 // operator "" X (f L) 3705 CookedTy = Context.LongDoubleTy; 3706 } else { 3707 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3708 // unsigned long long, the literal is treated as a call of the form 3709 // operator "" X (n ULL) 3710 CookedTy = Context.UnsignedLongLongTy; 3711 } 3712 3713 DeclarationName OpName = 3714 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3715 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3716 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3717 3718 SourceLocation TokLoc = Tok.getLocation(); 3719 3720 // Perform literal operator lookup to determine if we're building a raw 3721 // literal or a cooked one. 3722 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3723 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3724 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3725 /*AllowStringTemplatePack*/ false, 3726 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3727 case LOLR_ErrorNoDiagnostic: 3728 // Lookup failure for imaginary constants isn't fatal, there's still the 3729 // GNU extension producing _Complex types. 3730 break; 3731 case LOLR_Error: 3732 return ExprError(); 3733 case LOLR_Cooked: { 3734 Expr *Lit; 3735 if (Literal.isFloatingLiteral()) { 3736 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3737 } else { 3738 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3739 if (Literal.GetIntegerValue(ResultVal)) 3740 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3741 << /* Unsigned */ 1; 3742 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3743 Tok.getLocation()); 3744 } 3745 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3746 } 3747 3748 case LOLR_Raw: { 3749 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3750 // literal is treated as a call of the form 3751 // operator "" X ("n") 3752 unsigned Length = Literal.getUDSuffixOffset(); 3753 QualType StrTy = Context.getConstantArrayType( 3754 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3755 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3756 Expr *Lit = StringLiteral::Create( 3757 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3758 /*Pascal*/false, StrTy, &TokLoc, 1); 3759 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3760 } 3761 3762 case LOLR_Template: { 3763 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3764 // template), L is treated as a call fo the form 3765 // operator "" X <'c1', 'c2', ... 'ck'>() 3766 // where n is the source character sequence c1 c2 ... ck. 3767 TemplateArgumentListInfo ExplicitArgs; 3768 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3769 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3770 llvm::APSInt Value(CharBits, CharIsUnsigned); 3771 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3772 Value = TokSpelling[I]; 3773 TemplateArgument Arg(Context, Value, Context.CharTy); 3774 TemplateArgumentLocInfo ArgInfo; 3775 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3776 } 3777 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3778 &ExplicitArgs); 3779 } 3780 case LOLR_StringTemplatePack: 3781 llvm_unreachable("unexpected literal operator lookup result"); 3782 } 3783 } 3784 3785 Expr *Res; 3786 3787 if (Literal.isFixedPointLiteral()) { 3788 QualType Ty; 3789 3790 if (Literal.isAccum) { 3791 if (Literal.isHalf) { 3792 Ty = Context.ShortAccumTy; 3793 } else if (Literal.isLong) { 3794 Ty = Context.LongAccumTy; 3795 } else { 3796 Ty = Context.AccumTy; 3797 } 3798 } else if (Literal.isFract) { 3799 if (Literal.isHalf) { 3800 Ty = Context.ShortFractTy; 3801 } else if (Literal.isLong) { 3802 Ty = Context.LongFractTy; 3803 } else { 3804 Ty = Context.FractTy; 3805 } 3806 } 3807 3808 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3809 3810 bool isSigned = !Literal.isUnsigned; 3811 unsigned scale = Context.getFixedPointScale(Ty); 3812 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3813 3814 llvm::APInt Val(bit_width, 0, isSigned); 3815 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3816 bool ValIsZero = Val.isZero() && !Overflowed; 3817 3818 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3819 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3820 // Clause 6.4.4 - The value of a constant shall be in the range of 3821 // representable values for its type, with exception for constants of a 3822 // fract type with a value of exactly 1; such a constant shall denote 3823 // the maximal value for the type. 3824 --Val; 3825 else if (Val.ugt(MaxVal) || Overflowed) 3826 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3827 3828 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3829 Tok.getLocation(), scale); 3830 } else if (Literal.isFloatingLiteral()) { 3831 QualType Ty; 3832 if (Literal.isHalf){ 3833 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3834 Ty = Context.HalfTy; 3835 else { 3836 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3837 return ExprError(); 3838 } 3839 } else if (Literal.isFloat) 3840 Ty = Context.FloatTy; 3841 else if (Literal.isLong) 3842 Ty = Context.LongDoubleTy; 3843 else if (Literal.isFloat16) 3844 Ty = Context.Float16Ty; 3845 else if (Literal.isFloat128) 3846 Ty = Context.Float128Ty; 3847 else 3848 Ty = Context.DoubleTy; 3849 3850 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3851 3852 if (Ty == Context.DoubleTy) { 3853 if (getLangOpts().SinglePrecisionConstants) { 3854 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3855 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3856 } 3857 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3858 "cl_khr_fp64", getLangOpts())) { 3859 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3860 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) 3861 << (getLangOpts().getOpenCLCompatibleVersion() >= 300); 3862 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3863 } 3864 } 3865 } else if (!Literal.isIntegerLiteral()) { 3866 return ExprError(); 3867 } else { 3868 QualType Ty; 3869 3870 // 'long long' is a C99 or C++11 feature. 3871 if (!getLangOpts().C99 && Literal.isLongLong) { 3872 if (getLangOpts().CPlusPlus) 3873 Diag(Tok.getLocation(), 3874 getLangOpts().CPlusPlus11 ? 3875 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3876 else 3877 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3878 } 3879 3880 // 'z/uz' literals are a C++2b feature. 3881 if (Literal.isSizeT) 3882 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3883 ? getLangOpts().CPlusPlus2b 3884 ? diag::warn_cxx20_compat_size_t_suffix 3885 : diag::ext_cxx2b_size_t_suffix 3886 : diag::err_cxx2b_size_t_suffix); 3887 3888 // Get the value in the widest-possible width. 3889 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3890 llvm::APInt ResultVal(MaxWidth, 0); 3891 3892 if (Literal.GetIntegerValue(ResultVal)) { 3893 // If this value didn't fit into uintmax_t, error and force to ull. 3894 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3895 << /* Unsigned */ 1; 3896 Ty = Context.UnsignedLongLongTy; 3897 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3898 "long long is not intmax_t?"); 3899 } else { 3900 // If this value fits into a ULL, try to figure out what else it fits into 3901 // according to the rules of C99 6.4.4.1p5. 3902 3903 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3904 // be an unsigned int. 3905 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3906 3907 // Check from smallest to largest, picking the smallest type we can. 3908 unsigned Width = 0; 3909 3910 // Microsoft specific integer suffixes are explicitly sized. 3911 if (Literal.MicrosoftInteger) { 3912 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3913 Width = 8; 3914 Ty = Context.CharTy; 3915 } else { 3916 Width = Literal.MicrosoftInteger; 3917 Ty = Context.getIntTypeForBitwidth(Width, 3918 /*Signed=*/!Literal.isUnsigned); 3919 } 3920 } 3921 3922 // Check C++2b size_t literals. 3923 if (Literal.isSizeT) { 3924 assert(!Literal.MicrosoftInteger && 3925 "size_t literals can't be Microsoft literals"); 3926 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 3927 Context.getTargetInfo().getSizeType()); 3928 3929 // Does it fit in size_t? 3930 if (ResultVal.isIntN(SizeTSize)) { 3931 // Does it fit in ssize_t? 3932 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 3933 Ty = Context.getSignedSizeType(); 3934 else if (AllowUnsigned) 3935 Ty = Context.getSizeType(); 3936 Width = SizeTSize; 3937 } 3938 } 3939 3940 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 3941 !Literal.isSizeT) { 3942 // Are int/unsigned possibilities? 3943 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3944 3945 // Does it fit in a unsigned int? 3946 if (ResultVal.isIntN(IntSize)) { 3947 // Does it fit in a signed int? 3948 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3949 Ty = Context.IntTy; 3950 else if (AllowUnsigned) 3951 Ty = Context.UnsignedIntTy; 3952 Width = IntSize; 3953 } 3954 } 3955 3956 // Are long/unsigned long possibilities? 3957 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 3958 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3959 3960 // Does it fit in a unsigned long? 3961 if (ResultVal.isIntN(LongSize)) { 3962 // Does it fit in a signed long? 3963 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3964 Ty = Context.LongTy; 3965 else if (AllowUnsigned) 3966 Ty = Context.UnsignedLongTy; 3967 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3968 // is compatible. 3969 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3970 const unsigned LongLongSize = 3971 Context.getTargetInfo().getLongLongWidth(); 3972 Diag(Tok.getLocation(), 3973 getLangOpts().CPlusPlus 3974 ? Literal.isLong 3975 ? diag::warn_old_implicitly_unsigned_long_cxx 3976 : /*C++98 UB*/ diag:: 3977 ext_old_implicitly_unsigned_long_cxx 3978 : diag::warn_old_implicitly_unsigned_long) 3979 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3980 : /*will be ill-formed*/ 1); 3981 Ty = Context.UnsignedLongTy; 3982 } 3983 Width = LongSize; 3984 } 3985 } 3986 3987 // Check long long if needed. 3988 if (Ty.isNull() && !Literal.isSizeT) { 3989 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3990 3991 // Does it fit in a unsigned long long? 3992 if (ResultVal.isIntN(LongLongSize)) { 3993 // Does it fit in a signed long long? 3994 // To be compatible with MSVC, hex integer literals ending with the 3995 // LL or i64 suffix are always signed in Microsoft mode. 3996 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3997 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3998 Ty = Context.LongLongTy; 3999 else if (AllowUnsigned) 4000 Ty = Context.UnsignedLongLongTy; 4001 Width = LongLongSize; 4002 } 4003 } 4004 4005 // If we still couldn't decide a type, we either have 'size_t' literal 4006 // that is out of range, or a decimal literal that does not fit in a 4007 // signed long long and has no U suffix. 4008 if (Ty.isNull()) { 4009 if (Literal.isSizeT) 4010 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 4011 << Literal.isUnsigned; 4012 else 4013 Diag(Tok.getLocation(), 4014 diag::ext_integer_literal_too_large_for_signed); 4015 Ty = Context.UnsignedLongLongTy; 4016 Width = Context.getTargetInfo().getLongLongWidth(); 4017 } 4018 4019 if (ResultVal.getBitWidth() != Width) 4020 ResultVal = ResultVal.trunc(Width); 4021 } 4022 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 4023 } 4024 4025 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 4026 if (Literal.isImaginary) { 4027 Res = new (Context) ImaginaryLiteral(Res, 4028 Context.getComplexType(Res->getType())); 4029 4030 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4031 } 4032 return Res; 4033 } 4034 4035 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4036 assert(E && "ActOnParenExpr() missing expr"); 4037 QualType ExprTy = E->getType(); 4038 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && 4039 !E->isLValue() && ExprTy->hasFloatingRepresentation()) 4040 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); 4041 return new (Context) ParenExpr(L, R, E); 4042 } 4043 4044 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4045 SourceLocation Loc, 4046 SourceRange ArgRange) { 4047 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4048 // scalar or vector data type argument..." 4049 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4050 // type (C99 6.2.5p18) or void. 4051 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4052 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4053 << T << ArgRange; 4054 return true; 4055 } 4056 4057 assert((T->isVoidType() || !T->isIncompleteType()) && 4058 "Scalar types should always be complete"); 4059 return false; 4060 } 4061 4062 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4063 SourceLocation Loc, 4064 SourceRange ArgRange, 4065 UnaryExprOrTypeTrait TraitKind) { 4066 // Invalid types must be hard errors for SFINAE in C++. 4067 if (S.LangOpts.CPlusPlus) 4068 return true; 4069 4070 // C99 6.5.3.4p1: 4071 if (T->isFunctionType() && 4072 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4073 TraitKind == UETT_PreferredAlignOf)) { 4074 // sizeof(function)/alignof(function) is allowed as an extension. 4075 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4076 << getTraitSpelling(TraitKind) << ArgRange; 4077 return false; 4078 } 4079 4080 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4081 // this is an error (OpenCL v1.1 s6.3.k) 4082 if (T->isVoidType()) { 4083 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4084 : diag::ext_sizeof_alignof_void_type; 4085 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4086 return false; 4087 } 4088 4089 return true; 4090 } 4091 4092 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4093 SourceLocation Loc, 4094 SourceRange ArgRange, 4095 UnaryExprOrTypeTrait TraitKind) { 4096 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4097 // runtime doesn't allow it. 4098 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4099 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4100 << T << (TraitKind == UETT_SizeOf) 4101 << ArgRange; 4102 return true; 4103 } 4104 4105 return false; 4106 } 4107 4108 /// Check whether E is a pointer from a decayed array type (the decayed 4109 /// pointer type is equal to T) and emit a warning if it is. 4110 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4111 Expr *E) { 4112 // Don't warn if the operation changed the type. 4113 if (T != E->getType()) 4114 return; 4115 4116 // Now look for array decays. 4117 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4118 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4119 return; 4120 4121 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4122 << ICE->getType() 4123 << ICE->getSubExpr()->getType(); 4124 } 4125 4126 /// Check the constraints on expression operands to unary type expression 4127 /// and type traits. 4128 /// 4129 /// Completes any types necessary and validates the constraints on the operand 4130 /// expression. The logic mostly mirrors the type-based overload, but may modify 4131 /// the expression as it completes the type for that expression through template 4132 /// instantiation, etc. 4133 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4134 UnaryExprOrTypeTrait ExprKind) { 4135 QualType ExprTy = E->getType(); 4136 assert(!ExprTy->isReferenceType()); 4137 4138 bool IsUnevaluatedOperand = 4139 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4140 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4141 if (IsUnevaluatedOperand) { 4142 ExprResult Result = CheckUnevaluatedOperand(E); 4143 if (Result.isInvalid()) 4144 return true; 4145 E = Result.get(); 4146 } 4147 4148 // The operand for sizeof and alignof is in an unevaluated expression context, 4149 // so side effects could result in unintended consequences. 4150 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4151 // used to build SFINAE gadgets. 4152 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4153 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4154 !E->isInstantiationDependent() && 4155 E->HasSideEffects(Context, false)) 4156 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4157 4158 if (ExprKind == UETT_VecStep) 4159 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4160 E->getSourceRange()); 4161 4162 // Explicitly list some types as extensions. 4163 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4164 E->getSourceRange(), ExprKind)) 4165 return false; 4166 4167 // 'alignof' applied to an expression only requires the base element type of 4168 // the expression to be complete. 'sizeof' requires the expression's type to 4169 // be complete (and will attempt to complete it if it's an array of unknown 4170 // bound). 4171 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4172 if (RequireCompleteSizedType( 4173 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4174 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4175 getTraitSpelling(ExprKind), E->getSourceRange())) 4176 return true; 4177 } else { 4178 if (RequireCompleteSizedExprType( 4179 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4180 getTraitSpelling(ExprKind), E->getSourceRange())) 4181 return true; 4182 } 4183 4184 // Completing the expression's type may have changed it. 4185 ExprTy = E->getType(); 4186 assert(!ExprTy->isReferenceType()); 4187 4188 if (ExprTy->isFunctionType()) { 4189 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4190 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4191 return true; 4192 } 4193 4194 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4195 E->getSourceRange(), ExprKind)) 4196 return true; 4197 4198 if (ExprKind == UETT_SizeOf) { 4199 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4200 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4201 QualType OType = PVD->getOriginalType(); 4202 QualType Type = PVD->getType(); 4203 if (Type->isPointerType() && OType->isArrayType()) { 4204 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4205 << Type << OType; 4206 Diag(PVD->getLocation(), diag::note_declared_at); 4207 } 4208 } 4209 } 4210 4211 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4212 // decays into a pointer and returns an unintended result. This is most 4213 // likely a typo for "sizeof(array) op x". 4214 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4215 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4216 BO->getLHS()); 4217 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4218 BO->getRHS()); 4219 } 4220 } 4221 4222 return false; 4223 } 4224 4225 /// Check the constraints on operands to unary expression and type 4226 /// traits. 4227 /// 4228 /// This will complete any types necessary, and validate the various constraints 4229 /// on those operands. 4230 /// 4231 /// The UsualUnaryConversions() function is *not* called by this routine. 4232 /// C99 6.3.2.1p[2-4] all state: 4233 /// Except when it is the operand of the sizeof operator ... 4234 /// 4235 /// C++ [expr.sizeof]p4 4236 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4237 /// standard conversions are not applied to the operand of sizeof. 4238 /// 4239 /// This policy is followed for all of the unary trait expressions. 4240 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4241 SourceLocation OpLoc, 4242 SourceRange ExprRange, 4243 UnaryExprOrTypeTrait ExprKind) { 4244 if (ExprType->isDependentType()) 4245 return false; 4246 4247 // C++ [expr.sizeof]p2: 4248 // When applied to a reference or a reference type, the result 4249 // is the size of the referenced type. 4250 // C++11 [expr.alignof]p3: 4251 // When alignof is applied to a reference type, the result 4252 // shall be the alignment of the referenced type. 4253 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4254 ExprType = Ref->getPointeeType(); 4255 4256 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4257 // When alignof or _Alignof is applied to an array type, the result 4258 // is the alignment of the element type. 4259 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4260 ExprKind == UETT_OpenMPRequiredSimdAlign) 4261 ExprType = Context.getBaseElementType(ExprType); 4262 4263 if (ExprKind == UETT_VecStep) 4264 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4265 4266 // Explicitly list some types as extensions. 4267 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4268 ExprKind)) 4269 return false; 4270 4271 if (RequireCompleteSizedType( 4272 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4273 getTraitSpelling(ExprKind), ExprRange)) 4274 return true; 4275 4276 if (ExprType->isFunctionType()) { 4277 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4278 << getTraitSpelling(ExprKind) << ExprRange; 4279 return true; 4280 } 4281 4282 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4283 ExprKind)) 4284 return true; 4285 4286 return false; 4287 } 4288 4289 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4290 // Cannot know anything else if the expression is dependent. 4291 if (E->isTypeDependent()) 4292 return false; 4293 4294 if (E->getObjectKind() == OK_BitField) { 4295 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4296 << 1 << E->getSourceRange(); 4297 return true; 4298 } 4299 4300 ValueDecl *D = nullptr; 4301 Expr *Inner = E->IgnoreParens(); 4302 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4303 D = DRE->getDecl(); 4304 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4305 D = ME->getMemberDecl(); 4306 } 4307 4308 // If it's a field, require the containing struct to have a 4309 // complete definition so that we can compute the layout. 4310 // 4311 // This can happen in C++11 onwards, either by naming the member 4312 // in a way that is not transformed into a member access expression 4313 // (in an unevaluated operand, for instance), or by naming the member 4314 // in a trailing-return-type. 4315 // 4316 // For the record, since __alignof__ on expressions is a GCC 4317 // extension, GCC seems to permit this but always gives the 4318 // nonsensical answer 0. 4319 // 4320 // We don't really need the layout here --- we could instead just 4321 // directly check for all the appropriate alignment-lowing 4322 // attributes --- but that would require duplicating a lot of 4323 // logic that just isn't worth duplicating for such a marginal 4324 // use-case. 4325 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4326 // Fast path this check, since we at least know the record has a 4327 // definition if we can find a member of it. 4328 if (!FD->getParent()->isCompleteDefinition()) { 4329 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4330 << E->getSourceRange(); 4331 return true; 4332 } 4333 4334 // Otherwise, if it's a field, and the field doesn't have 4335 // reference type, then it must have a complete type (or be a 4336 // flexible array member, which we explicitly want to 4337 // white-list anyway), which makes the following checks trivial. 4338 if (!FD->getType()->isReferenceType()) 4339 return false; 4340 } 4341 4342 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4343 } 4344 4345 bool Sema::CheckVecStepExpr(Expr *E) { 4346 E = E->IgnoreParens(); 4347 4348 // Cannot know anything else if the expression is dependent. 4349 if (E->isTypeDependent()) 4350 return false; 4351 4352 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4353 } 4354 4355 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4356 CapturingScopeInfo *CSI) { 4357 assert(T->isVariablyModifiedType()); 4358 assert(CSI != nullptr); 4359 4360 // We're going to walk down into the type and look for VLA expressions. 4361 do { 4362 const Type *Ty = T.getTypePtr(); 4363 switch (Ty->getTypeClass()) { 4364 #define TYPE(Class, Base) 4365 #define ABSTRACT_TYPE(Class, Base) 4366 #define NON_CANONICAL_TYPE(Class, Base) 4367 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4368 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4369 #include "clang/AST/TypeNodes.inc" 4370 T = QualType(); 4371 break; 4372 // These types are never variably-modified. 4373 case Type::Builtin: 4374 case Type::Complex: 4375 case Type::Vector: 4376 case Type::ExtVector: 4377 case Type::ConstantMatrix: 4378 case Type::Record: 4379 case Type::Enum: 4380 case Type::Elaborated: 4381 case Type::TemplateSpecialization: 4382 case Type::ObjCObject: 4383 case Type::ObjCInterface: 4384 case Type::ObjCObjectPointer: 4385 case Type::ObjCTypeParam: 4386 case Type::Pipe: 4387 case Type::ExtInt: 4388 llvm_unreachable("type class is never variably-modified!"); 4389 case Type::Adjusted: 4390 T = cast<AdjustedType>(Ty)->getOriginalType(); 4391 break; 4392 case Type::Decayed: 4393 T = cast<DecayedType>(Ty)->getPointeeType(); 4394 break; 4395 case Type::Pointer: 4396 T = cast<PointerType>(Ty)->getPointeeType(); 4397 break; 4398 case Type::BlockPointer: 4399 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4400 break; 4401 case Type::LValueReference: 4402 case Type::RValueReference: 4403 T = cast<ReferenceType>(Ty)->getPointeeType(); 4404 break; 4405 case Type::MemberPointer: 4406 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4407 break; 4408 case Type::ConstantArray: 4409 case Type::IncompleteArray: 4410 // Losing element qualification here is fine. 4411 T = cast<ArrayType>(Ty)->getElementType(); 4412 break; 4413 case Type::VariableArray: { 4414 // Losing element qualification here is fine. 4415 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4416 4417 // Unknown size indication requires no size computation. 4418 // Otherwise, evaluate and record it. 4419 auto Size = VAT->getSizeExpr(); 4420 if (Size && !CSI->isVLATypeCaptured(VAT) && 4421 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4422 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4423 4424 T = VAT->getElementType(); 4425 break; 4426 } 4427 case Type::FunctionProto: 4428 case Type::FunctionNoProto: 4429 T = cast<FunctionType>(Ty)->getReturnType(); 4430 break; 4431 case Type::Paren: 4432 case Type::TypeOf: 4433 case Type::UnaryTransform: 4434 case Type::Attributed: 4435 case Type::SubstTemplateTypeParm: 4436 case Type::MacroQualified: 4437 // Keep walking after single level desugaring. 4438 T = T.getSingleStepDesugaredType(Context); 4439 break; 4440 case Type::Typedef: 4441 T = cast<TypedefType>(Ty)->desugar(); 4442 break; 4443 case Type::Decltype: 4444 T = cast<DecltypeType>(Ty)->desugar(); 4445 break; 4446 case Type::Auto: 4447 case Type::DeducedTemplateSpecialization: 4448 T = cast<DeducedType>(Ty)->getDeducedType(); 4449 break; 4450 case Type::TypeOfExpr: 4451 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4452 break; 4453 case Type::Atomic: 4454 T = cast<AtomicType>(Ty)->getValueType(); 4455 break; 4456 } 4457 } while (!T.isNull() && T->isVariablyModifiedType()); 4458 } 4459 4460 /// Build a sizeof or alignof expression given a type operand. 4461 ExprResult 4462 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4463 SourceLocation OpLoc, 4464 UnaryExprOrTypeTrait ExprKind, 4465 SourceRange R) { 4466 if (!TInfo) 4467 return ExprError(); 4468 4469 QualType T = TInfo->getType(); 4470 4471 if (!T->isDependentType() && 4472 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4473 return ExprError(); 4474 4475 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4476 if (auto *TT = T->getAs<TypedefType>()) { 4477 for (auto I = FunctionScopes.rbegin(), 4478 E = std::prev(FunctionScopes.rend()); 4479 I != E; ++I) { 4480 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4481 if (CSI == nullptr) 4482 break; 4483 DeclContext *DC = nullptr; 4484 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4485 DC = LSI->CallOperator; 4486 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4487 DC = CRSI->TheCapturedDecl; 4488 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4489 DC = BSI->TheDecl; 4490 if (DC) { 4491 if (DC->containsDecl(TT->getDecl())) 4492 break; 4493 captureVariablyModifiedType(Context, T, CSI); 4494 } 4495 } 4496 } 4497 } 4498 4499 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4500 return new (Context) UnaryExprOrTypeTraitExpr( 4501 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4502 } 4503 4504 /// Build a sizeof or alignof expression given an expression 4505 /// operand. 4506 ExprResult 4507 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4508 UnaryExprOrTypeTrait ExprKind) { 4509 ExprResult PE = CheckPlaceholderExpr(E); 4510 if (PE.isInvalid()) 4511 return ExprError(); 4512 4513 E = PE.get(); 4514 4515 // Verify that the operand is valid. 4516 bool isInvalid = false; 4517 if (E->isTypeDependent()) { 4518 // Delay type-checking for type-dependent expressions. 4519 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4520 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4521 } else if (ExprKind == UETT_VecStep) { 4522 isInvalid = CheckVecStepExpr(E); 4523 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4524 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4525 isInvalid = true; 4526 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4527 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4528 isInvalid = true; 4529 } else { 4530 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4531 } 4532 4533 if (isInvalid) 4534 return ExprError(); 4535 4536 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4537 PE = TransformToPotentiallyEvaluated(E); 4538 if (PE.isInvalid()) return ExprError(); 4539 E = PE.get(); 4540 } 4541 4542 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4543 return new (Context) UnaryExprOrTypeTraitExpr( 4544 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4545 } 4546 4547 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4548 /// expr and the same for @c alignof and @c __alignof 4549 /// Note that the ArgRange is invalid if isType is false. 4550 ExprResult 4551 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4552 UnaryExprOrTypeTrait ExprKind, bool IsType, 4553 void *TyOrEx, SourceRange ArgRange) { 4554 // If error parsing type, ignore. 4555 if (!TyOrEx) return ExprError(); 4556 4557 if (IsType) { 4558 TypeSourceInfo *TInfo; 4559 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4560 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4561 } 4562 4563 Expr *ArgEx = (Expr *)TyOrEx; 4564 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4565 return Result; 4566 } 4567 4568 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4569 bool IsReal) { 4570 if (V.get()->isTypeDependent()) 4571 return S.Context.DependentTy; 4572 4573 // _Real and _Imag are only l-values for normal l-values. 4574 if (V.get()->getObjectKind() != OK_Ordinary) { 4575 V = S.DefaultLvalueConversion(V.get()); 4576 if (V.isInvalid()) 4577 return QualType(); 4578 } 4579 4580 // These operators return the element type of a complex type. 4581 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4582 return CT->getElementType(); 4583 4584 // Otherwise they pass through real integer and floating point types here. 4585 if (V.get()->getType()->isArithmeticType()) 4586 return V.get()->getType(); 4587 4588 // Test for placeholders. 4589 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4590 if (PR.isInvalid()) return QualType(); 4591 if (PR.get() != V.get()) { 4592 V = PR; 4593 return CheckRealImagOperand(S, V, Loc, IsReal); 4594 } 4595 4596 // Reject anything else. 4597 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4598 << (IsReal ? "__real" : "__imag"); 4599 return QualType(); 4600 } 4601 4602 4603 4604 ExprResult 4605 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4606 tok::TokenKind Kind, Expr *Input) { 4607 UnaryOperatorKind Opc; 4608 switch (Kind) { 4609 default: llvm_unreachable("Unknown unary op!"); 4610 case tok::plusplus: Opc = UO_PostInc; break; 4611 case tok::minusminus: Opc = UO_PostDec; break; 4612 } 4613 4614 // Since this might is a postfix expression, get rid of ParenListExprs. 4615 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4616 if (Result.isInvalid()) return ExprError(); 4617 Input = Result.get(); 4618 4619 return BuildUnaryOp(S, OpLoc, Opc, Input); 4620 } 4621 4622 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4623 /// 4624 /// \return true on error 4625 static bool checkArithmeticOnObjCPointer(Sema &S, 4626 SourceLocation opLoc, 4627 Expr *op) { 4628 assert(op->getType()->isObjCObjectPointerType()); 4629 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4630 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4631 return false; 4632 4633 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4634 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4635 << op->getSourceRange(); 4636 return true; 4637 } 4638 4639 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4640 auto *BaseNoParens = Base->IgnoreParens(); 4641 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4642 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4643 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4644 } 4645 4646 ExprResult 4647 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4648 Expr *idx, SourceLocation rbLoc) { 4649 if (base && !base->getType().isNull() && 4650 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4651 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4652 SourceLocation(), /*Length*/ nullptr, 4653 /*Stride=*/nullptr, rbLoc); 4654 4655 // Since this might be a postfix expression, get rid of ParenListExprs. 4656 if (isa<ParenListExpr>(base)) { 4657 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4658 if (result.isInvalid()) return ExprError(); 4659 base = result.get(); 4660 } 4661 4662 // Check if base and idx form a MatrixSubscriptExpr. 4663 // 4664 // Helper to check for comma expressions, which are not allowed as indices for 4665 // matrix subscript expressions. 4666 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4667 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4668 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4669 << SourceRange(base->getBeginLoc(), rbLoc); 4670 return true; 4671 } 4672 return false; 4673 }; 4674 // The matrix subscript operator ([][])is considered a single operator. 4675 // Separating the index expressions by parenthesis is not allowed. 4676 if (base->getType()->isSpecificPlaceholderType( 4677 BuiltinType::IncompleteMatrixIdx) && 4678 !isa<MatrixSubscriptExpr>(base)) { 4679 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4680 << SourceRange(base->getBeginLoc(), rbLoc); 4681 return ExprError(); 4682 } 4683 // If the base is a MatrixSubscriptExpr, try to create a new 4684 // MatrixSubscriptExpr. 4685 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4686 if (matSubscriptE) { 4687 if (CheckAndReportCommaError(idx)) 4688 return ExprError(); 4689 4690 assert(matSubscriptE->isIncomplete() && 4691 "base has to be an incomplete matrix subscript"); 4692 return CreateBuiltinMatrixSubscriptExpr( 4693 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4694 } 4695 4696 // Handle any non-overload placeholder types in the base and index 4697 // expressions. We can't handle overloads here because the other 4698 // operand might be an overloadable type, in which case the overload 4699 // resolution for the operator overload should get the first crack 4700 // at the overload. 4701 bool IsMSPropertySubscript = false; 4702 if (base->getType()->isNonOverloadPlaceholderType()) { 4703 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4704 if (!IsMSPropertySubscript) { 4705 ExprResult result = CheckPlaceholderExpr(base); 4706 if (result.isInvalid()) 4707 return ExprError(); 4708 base = result.get(); 4709 } 4710 } 4711 4712 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4713 if (base->getType()->isMatrixType()) { 4714 if (CheckAndReportCommaError(idx)) 4715 return ExprError(); 4716 4717 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4718 } 4719 4720 // A comma-expression as the index is deprecated in C++2a onwards. 4721 if (getLangOpts().CPlusPlus20 && 4722 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4723 (isa<CXXOperatorCallExpr>(idx) && 4724 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4725 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4726 << SourceRange(base->getBeginLoc(), rbLoc); 4727 } 4728 4729 if (idx->getType()->isNonOverloadPlaceholderType()) { 4730 ExprResult result = CheckPlaceholderExpr(idx); 4731 if (result.isInvalid()) return ExprError(); 4732 idx = result.get(); 4733 } 4734 4735 // Build an unanalyzed expression if either operand is type-dependent. 4736 if (getLangOpts().CPlusPlus && 4737 (base->isTypeDependent() || idx->isTypeDependent())) { 4738 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4739 VK_LValue, OK_Ordinary, rbLoc); 4740 } 4741 4742 // MSDN, property (C++) 4743 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4744 // This attribute can also be used in the declaration of an empty array in a 4745 // class or structure definition. For example: 4746 // __declspec(property(get=GetX, put=PutX)) int x[]; 4747 // The above statement indicates that x[] can be used with one or more array 4748 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4749 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4750 if (IsMSPropertySubscript) { 4751 // Build MS property subscript expression if base is MS property reference 4752 // or MS property subscript. 4753 return new (Context) MSPropertySubscriptExpr( 4754 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4755 } 4756 4757 // Use C++ overloaded-operator rules if either operand has record 4758 // type. The spec says to do this if either type is *overloadable*, 4759 // but enum types can't declare subscript operators or conversion 4760 // operators, so there's nothing interesting for overload resolution 4761 // to do if there aren't any record types involved. 4762 // 4763 // ObjC pointers have their own subscripting logic that is not tied 4764 // to overload resolution and so should not take this path. 4765 if (getLangOpts().CPlusPlus && 4766 (base->getType()->isRecordType() || 4767 (!base->getType()->isObjCObjectPointerType() && 4768 idx->getType()->isRecordType()))) { 4769 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4770 } 4771 4772 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4773 4774 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4775 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4776 4777 return Res; 4778 } 4779 4780 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4781 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4782 InitializationKind Kind = 4783 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4784 InitializationSequence InitSeq(*this, Entity, Kind, E); 4785 return InitSeq.Perform(*this, Entity, Kind, E); 4786 } 4787 4788 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4789 Expr *ColumnIdx, 4790 SourceLocation RBLoc) { 4791 ExprResult BaseR = CheckPlaceholderExpr(Base); 4792 if (BaseR.isInvalid()) 4793 return BaseR; 4794 Base = BaseR.get(); 4795 4796 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4797 if (RowR.isInvalid()) 4798 return RowR; 4799 RowIdx = RowR.get(); 4800 4801 if (!ColumnIdx) 4802 return new (Context) MatrixSubscriptExpr( 4803 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4804 4805 // Build an unanalyzed expression if any of the operands is type-dependent. 4806 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4807 ColumnIdx->isTypeDependent()) 4808 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4809 Context.DependentTy, RBLoc); 4810 4811 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4812 if (ColumnR.isInvalid()) 4813 return ColumnR; 4814 ColumnIdx = ColumnR.get(); 4815 4816 // Check that IndexExpr is an integer expression. If it is a constant 4817 // expression, check that it is less than Dim (= the number of elements in the 4818 // corresponding dimension). 4819 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4820 bool IsColumnIdx) -> Expr * { 4821 if (!IndexExpr->getType()->isIntegerType() && 4822 !IndexExpr->isTypeDependent()) { 4823 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4824 << IsColumnIdx; 4825 return nullptr; 4826 } 4827 4828 if (Optional<llvm::APSInt> Idx = 4829 IndexExpr->getIntegerConstantExpr(Context)) { 4830 if ((*Idx < 0 || *Idx >= Dim)) { 4831 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4832 << IsColumnIdx << Dim; 4833 return nullptr; 4834 } 4835 } 4836 4837 ExprResult ConvExpr = 4838 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4839 assert(!ConvExpr.isInvalid() && 4840 "should be able to convert any integer type to size type"); 4841 return ConvExpr.get(); 4842 }; 4843 4844 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4845 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4846 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4847 if (!RowIdx || !ColumnIdx) 4848 return ExprError(); 4849 4850 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4851 MTy->getElementType(), RBLoc); 4852 } 4853 4854 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4855 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4856 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4857 4858 // For expressions like `&(*s).b`, the base is recorded and what should be 4859 // checked. 4860 const MemberExpr *Member = nullptr; 4861 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4862 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4863 4864 LastRecord.PossibleDerefs.erase(StrippedExpr); 4865 } 4866 4867 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4868 if (isUnevaluatedContext()) 4869 return; 4870 4871 QualType ResultTy = E->getType(); 4872 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4873 4874 // Bail if the element is an array since it is not memory access. 4875 if (isa<ArrayType>(ResultTy)) 4876 return; 4877 4878 if (ResultTy->hasAttr(attr::NoDeref)) { 4879 LastRecord.PossibleDerefs.insert(E); 4880 return; 4881 } 4882 4883 // Check if the base type is a pointer to a member access of a struct 4884 // marked with noderef. 4885 const Expr *Base = E->getBase(); 4886 QualType BaseTy = Base->getType(); 4887 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4888 // Not a pointer access 4889 return; 4890 4891 const MemberExpr *Member = nullptr; 4892 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4893 Member->isArrow()) 4894 Base = Member->getBase(); 4895 4896 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4897 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4898 LastRecord.PossibleDerefs.insert(E); 4899 } 4900 } 4901 4902 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4903 Expr *LowerBound, 4904 SourceLocation ColonLocFirst, 4905 SourceLocation ColonLocSecond, 4906 Expr *Length, Expr *Stride, 4907 SourceLocation RBLoc) { 4908 if (Base->getType()->isPlaceholderType() && 4909 !Base->getType()->isSpecificPlaceholderType( 4910 BuiltinType::OMPArraySection)) { 4911 ExprResult Result = CheckPlaceholderExpr(Base); 4912 if (Result.isInvalid()) 4913 return ExprError(); 4914 Base = Result.get(); 4915 } 4916 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4917 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4918 if (Result.isInvalid()) 4919 return ExprError(); 4920 Result = DefaultLvalueConversion(Result.get()); 4921 if (Result.isInvalid()) 4922 return ExprError(); 4923 LowerBound = Result.get(); 4924 } 4925 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4926 ExprResult Result = CheckPlaceholderExpr(Length); 4927 if (Result.isInvalid()) 4928 return ExprError(); 4929 Result = DefaultLvalueConversion(Result.get()); 4930 if (Result.isInvalid()) 4931 return ExprError(); 4932 Length = Result.get(); 4933 } 4934 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4935 ExprResult Result = CheckPlaceholderExpr(Stride); 4936 if (Result.isInvalid()) 4937 return ExprError(); 4938 Result = DefaultLvalueConversion(Result.get()); 4939 if (Result.isInvalid()) 4940 return ExprError(); 4941 Stride = Result.get(); 4942 } 4943 4944 // Build an unanalyzed expression if either operand is type-dependent. 4945 if (Base->isTypeDependent() || 4946 (LowerBound && 4947 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4948 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4949 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4950 return new (Context) OMPArraySectionExpr( 4951 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4952 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4953 } 4954 4955 // Perform default conversions. 4956 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4957 QualType ResultTy; 4958 if (OriginalTy->isAnyPointerType()) { 4959 ResultTy = OriginalTy->getPointeeType(); 4960 } else if (OriginalTy->isArrayType()) { 4961 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4962 } else { 4963 return ExprError( 4964 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4965 << Base->getSourceRange()); 4966 } 4967 // C99 6.5.2.1p1 4968 if (LowerBound) { 4969 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4970 LowerBound); 4971 if (Res.isInvalid()) 4972 return ExprError(Diag(LowerBound->getExprLoc(), 4973 diag::err_omp_typecheck_section_not_integer) 4974 << 0 << LowerBound->getSourceRange()); 4975 LowerBound = Res.get(); 4976 4977 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4978 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4979 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4980 << 0 << LowerBound->getSourceRange(); 4981 } 4982 if (Length) { 4983 auto Res = 4984 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4985 if (Res.isInvalid()) 4986 return ExprError(Diag(Length->getExprLoc(), 4987 diag::err_omp_typecheck_section_not_integer) 4988 << 1 << Length->getSourceRange()); 4989 Length = Res.get(); 4990 4991 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4992 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4993 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4994 << 1 << Length->getSourceRange(); 4995 } 4996 if (Stride) { 4997 ExprResult Res = 4998 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 4999 if (Res.isInvalid()) 5000 return ExprError(Diag(Stride->getExprLoc(), 5001 diag::err_omp_typecheck_section_not_integer) 5002 << 1 << Stride->getSourceRange()); 5003 Stride = Res.get(); 5004 5005 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5006 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5007 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5008 << 1 << Stride->getSourceRange(); 5009 } 5010 5011 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5012 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5013 // type. Note that functions are not objects, and that (in C99 parlance) 5014 // incomplete types are not object types. 5015 if (ResultTy->isFunctionType()) { 5016 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5017 << ResultTy << Base->getSourceRange(); 5018 return ExprError(); 5019 } 5020 5021 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5022 diag::err_omp_section_incomplete_type, Base)) 5023 return ExprError(); 5024 5025 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5026 Expr::EvalResult Result; 5027 if (LowerBound->EvaluateAsInt(Result, Context)) { 5028 // OpenMP 5.0, [2.1.5 Array Sections] 5029 // The array section must be a subset of the original array. 5030 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5031 if (LowerBoundValue.isNegative()) { 5032 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5033 << LowerBound->getSourceRange(); 5034 return ExprError(); 5035 } 5036 } 5037 } 5038 5039 if (Length) { 5040 Expr::EvalResult Result; 5041 if (Length->EvaluateAsInt(Result, Context)) { 5042 // OpenMP 5.0, [2.1.5 Array Sections] 5043 // The length must evaluate to non-negative integers. 5044 llvm::APSInt LengthValue = Result.Val.getInt(); 5045 if (LengthValue.isNegative()) { 5046 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5047 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5048 << Length->getSourceRange(); 5049 return ExprError(); 5050 } 5051 } 5052 } else if (ColonLocFirst.isValid() && 5053 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5054 !OriginalTy->isVariableArrayType()))) { 5055 // OpenMP 5.0, [2.1.5 Array Sections] 5056 // When the size of the array dimension is not known, the length must be 5057 // specified explicitly. 5058 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5059 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5060 return ExprError(); 5061 } 5062 5063 if (Stride) { 5064 Expr::EvalResult Result; 5065 if (Stride->EvaluateAsInt(Result, Context)) { 5066 // OpenMP 5.0, [2.1.5 Array Sections] 5067 // The stride must evaluate to a positive integer. 5068 llvm::APSInt StrideValue = Result.Val.getInt(); 5069 if (!StrideValue.isStrictlyPositive()) { 5070 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5071 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5072 << Stride->getSourceRange(); 5073 return ExprError(); 5074 } 5075 } 5076 } 5077 5078 if (!Base->getType()->isSpecificPlaceholderType( 5079 BuiltinType::OMPArraySection)) { 5080 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5081 if (Result.isInvalid()) 5082 return ExprError(); 5083 Base = Result.get(); 5084 } 5085 return new (Context) OMPArraySectionExpr( 5086 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5087 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5088 } 5089 5090 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5091 SourceLocation RParenLoc, 5092 ArrayRef<Expr *> Dims, 5093 ArrayRef<SourceRange> Brackets) { 5094 if (Base->getType()->isPlaceholderType()) { 5095 ExprResult Result = CheckPlaceholderExpr(Base); 5096 if (Result.isInvalid()) 5097 return ExprError(); 5098 Result = DefaultLvalueConversion(Result.get()); 5099 if (Result.isInvalid()) 5100 return ExprError(); 5101 Base = Result.get(); 5102 } 5103 QualType BaseTy = Base->getType(); 5104 // Delay analysis of the types/expressions if instantiation/specialization is 5105 // required. 5106 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5107 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5108 LParenLoc, RParenLoc, Dims, Brackets); 5109 if (!BaseTy->isPointerType() || 5110 (!Base->isTypeDependent() && 5111 BaseTy->getPointeeType()->isIncompleteType())) 5112 return ExprError(Diag(Base->getExprLoc(), 5113 diag::err_omp_non_pointer_type_array_shaping_base) 5114 << Base->getSourceRange()); 5115 5116 SmallVector<Expr *, 4> NewDims; 5117 bool ErrorFound = false; 5118 for (Expr *Dim : Dims) { 5119 if (Dim->getType()->isPlaceholderType()) { 5120 ExprResult Result = CheckPlaceholderExpr(Dim); 5121 if (Result.isInvalid()) { 5122 ErrorFound = true; 5123 continue; 5124 } 5125 Result = DefaultLvalueConversion(Result.get()); 5126 if (Result.isInvalid()) { 5127 ErrorFound = true; 5128 continue; 5129 } 5130 Dim = Result.get(); 5131 } 5132 if (!Dim->isTypeDependent()) { 5133 ExprResult Result = 5134 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5135 if (Result.isInvalid()) { 5136 ErrorFound = true; 5137 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5138 << Dim->getSourceRange(); 5139 continue; 5140 } 5141 Dim = Result.get(); 5142 Expr::EvalResult EvResult; 5143 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5144 // OpenMP 5.0, [2.1.4 Array Shaping] 5145 // Each si is an integral type expression that must evaluate to a 5146 // positive integer. 5147 llvm::APSInt Value = EvResult.Val.getInt(); 5148 if (!Value.isStrictlyPositive()) { 5149 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5150 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5151 << Dim->getSourceRange(); 5152 ErrorFound = true; 5153 continue; 5154 } 5155 } 5156 } 5157 NewDims.push_back(Dim); 5158 } 5159 if (ErrorFound) 5160 return ExprError(); 5161 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5162 LParenLoc, RParenLoc, NewDims, Brackets); 5163 } 5164 5165 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5166 SourceLocation LLoc, SourceLocation RLoc, 5167 ArrayRef<OMPIteratorData> Data) { 5168 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5169 bool IsCorrect = true; 5170 for (const OMPIteratorData &D : Data) { 5171 TypeSourceInfo *TInfo = nullptr; 5172 SourceLocation StartLoc; 5173 QualType DeclTy; 5174 if (!D.Type.getAsOpaquePtr()) { 5175 // OpenMP 5.0, 2.1.6 Iterators 5176 // In an iterator-specifier, if the iterator-type is not specified then 5177 // the type of that iterator is of int type. 5178 DeclTy = Context.IntTy; 5179 StartLoc = D.DeclIdentLoc; 5180 } else { 5181 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5182 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5183 } 5184 5185 bool IsDeclTyDependent = DeclTy->isDependentType() || 5186 DeclTy->containsUnexpandedParameterPack() || 5187 DeclTy->isInstantiationDependentType(); 5188 if (!IsDeclTyDependent) { 5189 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5190 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5191 // The iterator-type must be an integral or pointer type. 5192 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5193 << DeclTy; 5194 IsCorrect = false; 5195 continue; 5196 } 5197 if (DeclTy.isConstant(Context)) { 5198 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5199 // The iterator-type must not be const qualified. 5200 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5201 << DeclTy; 5202 IsCorrect = false; 5203 continue; 5204 } 5205 } 5206 5207 // Iterator declaration. 5208 assert(D.DeclIdent && "Identifier expected."); 5209 // Always try to create iterator declarator to avoid extra error messages 5210 // about unknown declarations use. 5211 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5212 D.DeclIdent, DeclTy, TInfo, SC_None); 5213 VD->setImplicit(); 5214 if (S) { 5215 // Check for conflicting previous declaration. 5216 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5217 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5218 ForVisibleRedeclaration); 5219 Previous.suppressDiagnostics(); 5220 LookupName(Previous, S); 5221 5222 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5223 /*AllowInlineNamespace=*/false); 5224 if (!Previous.empty()) { 5225 NamedDecl *Old = Previous.getRepresentativeDecl(); 5226 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5227 Diag(Old->getLocation(), diag::note_previous_definition); 5228 } else { 5229 PushOnScopeChains(VD, S); 5230 } 5231 } else { 5232 CurContext->addDecl(VD); 5233 } 5234 Expr *Begin = D.Range.Begin; 5235 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5236 ExprResult BeginRes = 5237 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5238 Begin = BeginRes.get(); 5239 } 5240 Expr *End = D.Range.End; 5241 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5242 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5243 End = EndRes.get(); 5244 } 5245 Expr *Step = D.Range.Step; 5246 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5247 if (!Step->getType()->isIntegralType(Context)) { 5248 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5249 << Step << Step->getSourceRange(); 5250 IsCorrect = false; 5251 continue; 5252 } 5253 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5254 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5255 // If the step expression of a range-specification equals zero, the 5256 // behavior is unspecified. 5257 if (Result && Result->isZero()) { 5258 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5259 << Step << Step->getSourceRange(); 5260 IsCorrect = false; 5261 continue; 5262 } 5263 } 5264 if (!Begin || !End || !IsCorrect) { 5265 IsCorrect = false; 5266 continue; 5267 } 5268 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5269 IDElem.IteratorDecl = VD; 5270 IDElem.AssignmentLoc = D.AssignLoc; 5271 IDElem.Range.Begin = Begin; 5272 IDElem.Range.End = End; 5273 IDElem.Range.Step = Step; 5274 IDElem.ColonLoc = D.ColonLoc; 5275 IDElem.SecondColonLoc = D.SecColonLoc; 5276 } 5277 if (!IsCorrect) { 5278 // Invalidate all created iterator declarations if error is found. 5279 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5280 if (Decl *ID = D.IteratorDecl) 5281 ID->setInvalidDecl(); 5282 } 5283 return ExprError(); 5284 } 5285 SmallVector<OMPIteratorHelperData, 4> Helpers; 5286 if (!CurContext->isDependentContext()) { 5287 // Build number of ityeration for each iteration range. 5288 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5289 // ((Begini-Stepi-1-Endi) / -Stepi); 5290 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5291 // (Endi - Begini) 5292 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5293 D.Range.Begin); 5294 if(!Res.isUsable()) { 5295 IsCorrect = false; 5296 continue; 5297 } 5298 ExprResult St, St1; 5299 if (D.Range.Step) { 5300 St = D.Range.Step; 5301 // (Endi - Begini) + Stepi 5302 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5303 if (!Res.isUsable()) { 5304 IsCorrect = false; 5305 continue; 5306 } 5307 // (Endi - Begini) + Stepi - 1 5308 Res = 5309 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5310 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5311 if (!Res.isUsable()) { 5312 IsCorrect = false; 5313 continue; 5314 } 5315 // ((Endi - Begini) + Stepi - 1) / Stepi 5316 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5317 if (!Res.isUsable()) { 5318 IsCorrect = false; 5319 continue; 5320 } 5321 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5322 // (Begini - Endi) 5323 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5324 D.Range.Begin, D.Range.End); 5325 if (!Res1.isUsable()) { 5326 IsCorrect = false; 5327 continue; 5328 } 5329 // (Begini - Endi) - Stepi 5330 Res1 = 5331 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5332 if (!Res1.isUsable()) { 5333 IsCorrect = false; 5334 continue; 5335 } 5336 // (Begini - Endi) - Stepi - 1 5337 Res1 = 5338 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5339 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5340 if (!Res1.isUsable()) { 5341 IsCorrect = false; 5342 continue; 5343 } 5344 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5345 Res1 = 5346 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5347 if (!Res1.isUsable()) { 5348 IsCorrect = false; 5349 continue; 5350 } 5351 // Stepi > 0. 5352 ExprResult CmpRes = 5353 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5354 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5355 if (!CmpRes.isUsable()) { 5356 IsCorrect = false; 5357 continue; 5358 } 5359 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5360 Res.get(), Res1.get()); 5361 if (!Res.isUsable()) { 5362 IsCorrect = false; 5363 continue; 5364 } 5365 } 5366 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5367 if (!Res.isUsable()) { 5368 IsCorrect = false; 5369 continue; 5370 } 5371 5372 // Build counter update. 5373 // Build counter. 5374 auto *CounterVD = 5375 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5376 D.IteratorDecl->getBeginLoc(), nullptr, 5377 Res.get()->getType(), nullptr, SC_None); 5378 CounterVD->setImplicit(); 5379 ExprResult RefRes = 5380 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5381 D.IteratorDecl->getBeginLoc()); 5382 // Build counter update. 5383 // I = Begini + counter * Stepi; 5384 ExprResult UpdateRes; 5385 if (D.Range.Step) { 5386 UpdateRes = CreateBuiltinBinOp( 5387 D.AssignmentLoc, BO_Mul, 5388 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5389 } else { 5390 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5391 } 5392 if (!UpdateRes.isUsable()) { 5393 IsCorrect = false; 5394 continue; 5395 } 5396 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5397 UpdateRes.get()); 5398 if (!UpdateRes.isUsable()) { 5399 IsCorrect = false; 5400 continue; 5401 } 5402 ExprResult VDRes = 5403 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5404 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5405 D.IteratorDecl->getBeginLoc()); 5406 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5407 UpdateRes.get()); 5408 if (!UpdateRes.isUsable()) { 5409 IsCorrect = false; 5410 continue; 5411 } 5412 UpdateRes = 5413 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5414 if (!UpdateRes.isUsable()) { 5415 IsCorrect = false; 5416 continue; 5417 } 5418 ExprResult CounterUpdateRes = 5419 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5420 if (!CounterUpdateRes.isUsable()) { 5421 IsCorrect = false; 5422 continue; 5423 } 5424 CounterUpdateRes = 5425 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5426 if (!CounterUpdateRes.isUsable()) { 5427 IsCorrect = false; 5428 continue; 5429 } 5430 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5431 HD.CounterVD = CounterVD; 5432 HD.Upper = Res.get(); 5433 HD.Update = UpdateRes.get(); 5434 HD.CounterUpdate = CounterUpdateRes.get(); 5435 } 5436 } else { 5437 Helpers.assign(ID.size(), {}); 5438 } 5439 if (!IsCorrect) { 5440 // Invalidate all created iterator declarations if error is found. 5441 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5442 if (Decl *ID = D.IteratorDecl) 5443 ID->setInvalidDecl(); 5444 } 5445 return ExprError(); 5446 } 5447 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5448 LLoc, RLoc, ID, Helpers); 5449 } 5450 5451 ExprResult 5452 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5453 Expr *Idx, SourceLocation RLoc) { 5454 Expr *LHSExp = Base; 5455 Expr *RHSExp = Idx; 5456 5457 ExprValueKind VK = VK_LValue; 5458 ExprObjectKind OK = OK_Ordinary; 5459 5460 // Per C++ core issue 1213, the result is an xvalue if either operand is 5461 // a non-lvalue array, and an lvalue otherwise. 5462 if (getLangOpts().CPlusPlus11) { 5463 for (auto *Op : {LHSExp, RHSExp}) { 5464 Op = Op->IgnoreImplicit(); 5465 if (Op->getType()->isArrayType() && !Op->isLValue()) 5466 VK = VK_XValue; 5467 } 5468 } 5469 5470 // Perform default conversions. 5471 if (!LHSExp->getType()->getAs<VectorType>()) { 5472 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5473 if (Result.isInvalid()) 5474 return ExprError(); 5475 LHSExp = Result.get(); 5476 } 5477 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5478 if (Result.isInvalid()) 5479 return ExprError(); 5480 RHSExp = Result.get(); 5481 5482 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5483 5484 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5485 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5486 // in the subscript position. As a result, we need to derive the array base 5487 // and index from the expression types. 5488 Expr *BaseExpr, *IndexExpr; 5489 QualType ResultType; 5490 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5491 BaseExpr = LHSExp; 5492 IndexExpr = RHSExp; 5493 ResultType = Context.DependentTy; 5494 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5495 BaseExpr = LHSExp; 5496 IndexExpr = RHSExp; 5497 ResultType = PTy->getPointeeType(); 5498 } else if (const ObjCObjectPointerType *PTy = 5499 LHSTy->getAs<ObjCObjectPointerType>()) { 5500 BaseExpr = LHSExp; 5501 IndexExpr = RHSExp; 5502 5503 // Use custom logic if this should be the pseudo-object subscript 5504 // expression. 5505 if (!LangOpts.isSubscriptPointerArithmetic()) 5506 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5507 nullptr); 5508 5509 ResultType = PTy->getPointeeType(); 5510 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5511 // Handle the uncommon case of "123[Ptr]". 5512 BaseExpr = RHSExp; 5513 IndexExpr = LHSExp; 5514 ResultType = PTy->getPointeeType(); 5515 } else if (const ObjCObjectPointerType *PTy = 5516 RHSTy->getAs<ObjCObjectPointerType>()) { 5517 // Handle the uncommon case of "123[Ptr]". 5518 BaseExpr = RHSExp; 5519 IndexExpr = LHSExp; 5520 ResultType = PTy->getPointeeType(); 5521 if (!LangOpts.isSubscriptPointerArithmetic()) { 5522 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5523 << ResultType << BaseExpr->getSourceRange(); 5524 return ExprError(); 5525 } 5526 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5527 BaseExpr = LHSExp; // vectors: V[123] 5528 IndexExpr = RHSExp; 5529 // We apply C++ DR1213 to vector subscripting too. 5530 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5531 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5532 if (Materialized.isInvalid()) 5533 return ExprError(); 5534 LHSExp = Materialized.get(); 5535 } 5536 VK = LHSExp->getValueKind(); 5537 if (VK != VK_PRValue) 5538 OK = OK_VectorComponent; 5539 5540 ResultType = VTy->getElementType(); 5541 QualType BaseType = BaseExpr->getType(); 5542 Qualifiers BaseQuals = BaseType.getQualifiers(); 5543 Qualifiers MemberQuals = ResultType.getQualifiers(); 5544 Qualifiers Combined = BaseQuals + MemberQuals; 5545 if (Combined != MemberQuals) 5546 ResultType = Context.getQualifiedType(ResultType, Combined); 5547 } else if (LHSTy->isArrayType()) { 5548 // If we see an array that wasn't promoted by 5549 // DefaultFunctionArrayLvalueConversion, it must be an array that 5550 // wasn't promoted because of the C90 rule that doesn't 5551 // allow promoting non-lvalue arrays. Warn, then 5552 // force the promotion here. 5553 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5554 << LHSExp->getSourceRange(); 5555 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5556 CK_ArrayToPointerDecay).get(); 5557 LHSTy = LHSExp->getType(); 5558 5559 BaseExpr = LHSExp; 5560 IndexExpr = RHSExp; 5561 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5562 } else if (RHSTy->isArrayType()) { 5563 // Same as previous, except for 123[f().a] case 5564 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5565 << RHSExp->getSourceRange(); 5566 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5567 CK_ArrayToPointerDecay).get(); 5568 RHSTy = RHSExp->getType(); 5569 5570 BaseExpr = RHSExp; 5571 IndexExpr = LHSExp; 5572 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5573 } else { 5574 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5575 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5576 } 5577 // C99 6.5.2.1p1 5578 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5579 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5580 << IndexExpr->getSourceRange()); 5581 5582 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5583 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5584 && !IndexExpr->isTypeDependent()) 5585 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5586 5587 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5588 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5589 // type. Note that Functions are not objects, and that (in C99 parlance) 5590 // incomplete types are not object types. 5591 if (ResultType->isFunctionType()) { 5592 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5593 << ResultType << BaseExpr->getSourceRange(); 5594 return ExprError(); 5595 } 5596 5597 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5598 // GNU extension: subscripting on pointer to void 5599 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5600 << BaseExpr->getSourceRange(); 5601 5602 // C forbids expressions of unqualified void type from being l-values. 5603 // See IsCForbiddenLValueType. 5604 if (!ResultType.hasQualifiers()) 5605 VK = VK_PRValue; 5606 } else if (!ResultType->isDependentType() && 5607 RequireCompleteSizedType( 5608 LLoc, ResultType, 5609 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5610 return ExprError(); 5611 5612 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 5613 !ResultType.isCForbiddenLValueType()); 5614 5615 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5616 FunctionScopes.size() > 1) { 5617 if (auto *TT = 5618 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5619 for (auto I = FunctionScopes.rbegin(), 5620 E = std::prev(FunctionScopes.rend()); 5621 I != E; ++I) { 5622 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5623 if (CSI == nullptr) 5624 break; 5625 DeclContext *DC = nullptr; 5626 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5627 DC = LSI->CallOperator; 5628 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5629 DC = CRSI->TheCapturedDecl; 5630 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5631 DC = BSI->TheDecl; 5632 if (DC) { 5633 if (DC->containsDecl(TT->getDecl())) 5634 break; 5635 captureVariablyModifiedType( 5636 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5637 } 5638 } 5639 } 5640 } 5641 5642 return new (Context) 5643 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5644 } 5645 5646 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5647 ParmVarDecl *Param) { 5648 if (Param->hasUnparsedDefaultArg()) { 5649 // If we've already cleared out the location for the default argument, 5650 // that means we're parsing it right now. 5651 if (!UnparsedDefaultArgLocs.count(Param)) { 5652 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5653 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5654 Param->setInvalidDecl(); 5655 return true; 5656 } 5657 5658 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5659 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5660 Diag(UnparsedDefaultArgLocs[Param], 5661 diag::note_default_argument_declared_here); 5662 return true; 5663 } 5664 5665 if (Param->hasUninstantiatedDefaultArg() && 5666 InstantiateDefaultArgument(CallLoc, FD, Param)) 5667 return true; 5668 5669 assert(Param->hasInit() && "default argument but no initializer?"); 5670 5671 // If the default expression creates temporaries, we need to 5672 // push them to the current stack of expression temporaries so they'll 5673 // be properly destroyed. 5674 // FIXME: We should really be rebuilding the default argument with new 5675 // bound temporaries; see the comment in PR5810. 5676 // We don't need to do that with block decls, though, because 5677 // blocks in default argument expression can never capture anything. 5678 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5679 // Set the "needs cleanups" bit regardless of whether there are 5680 // any explicit objects. 5681 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5682 5683 // Append all the objects to the cleanup list. Right now, this 5684 // should always be a no-op, because blocks in default argument 5685 // expressions should never be able to capture anything. 5686 assert(!Init->getNumObjects() && 5687 "default argument expression has capturing blocks?"); 5688 } 5689 5690 // We already type-checked the argument, so we know it works. 5691 // Just mark all of the declarations in this potentially-evaluated expression 5692 // as being "referenced". 5693 EnterExpressionEvaluationContext EvalContext( 5694 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5695 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5696 /*SkipLocalVariables=*/true); 5697 return false; 5698 } 5699 5700 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5701 FunctionDecl *FD, ParmVarDecl *Param) { 5702 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5703 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5704 return ExprError(); 5705 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5706 } 5707 5708 Sema::VariadicCallType 5709 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5710 Expr *Fn) { 5711 if (Proto && Proto->isVariadic()) { 5712 if (isa_and_nonnull<CXXConstructorDecl>(FDecl)) 5713 return VariadicConstructor; 5714 else if (Fn && Fn->getType()->isBlockPointerType()) 5715 return VariadicBlock; 5716 else if (FDecl) { 5717 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5718 if (Method->isInstance()) 5719 return VariadicMethod; 5720 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5721 return VariadicMethod; 5722 return VariadicFunction; 5723 } 5724 return VariadicDoesNotApply; 5725 } 5726 5727 namespace { 5728 class FunctionCallCCC final : public FunctionCallFilterCCC { 5729 public: 5730 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5731 unsigned NumArgs, MemberExpr *ME) 5732 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5733 FunctionName(FuncName) {} 5734 5735 bool ValidateCandidate(const TypoCorrection &candidate) override { 5736 if (!candidate.getCorrectionSpecifier() || 5737 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5738 return false; 5739 } 5740 5741 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5742 } 5743 5744 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5745 return std::make_unique<FunctionCallCCC>(*this); 5746 } 5747 5748 private: 5749 const IdentifierInfo *const FunctionName; 5750 }; 5751 } 5752 5753 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5754 FunctionDecl *FDecl, 5755 ArrayRef<Expr *> Args) { 5756 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5757 DeclarationName FuncName = FDecl->getDeclName(); 5758 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5759 5760 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5761 if (TypoCorrection Corrected = S.CorrectTypo( 5762 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5763 S.getScopeForContext(S.CurContext), nullptr, CCC, 5764 Sema::CTK_ErrorRecovery)) { 5765 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5766 if (Corrected.isOverloaded()) { 5767 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5768 OverloadCandidateSet::iterator Best; 5769 for (NamedDecl *CD : Corrected) { 5770 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5771 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5772 OCS); 5773 } 5774 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5775 case OR_Success: 5776 ND = Best->FoundDecl; 5777 Corrected.setCorrectionDecl(ND); 5778 break; 5779 default: 5780 break; 5781 } 5782 } 5783 ND = ND->getUnderlyingDecl(); 5784 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5785 return Corrected; 5786 } 5787 } 5788 return TypoCorrection(); 5789 } 5790 5791 /// ConvertArgumentsForCall - Converts the arguments specified in 5792 /// Args/NumArgs to the parameter types of the function FDecl with 5793 /// function prototype Proto. Call is the call expression itself, and 5794 /// Fn is the function expression. For a C++ member function, this 5795 /// routine does not attempt to convert the object argument. Returns 5796 /// true if the call is ill-formed. 5797 bool 5798 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5799 FunctionDecl *FDecl, 5800 const FunctionProtoType *Proto, 5801 ArrayRef<Expr *> Args, 5802 SourceLocation RParenLoc, 5803 bool IsExecConfig) { 5804 // Bail out early if calling a builtin with custom typechecking. 5805 if (FDecl) 5806 if (unsigned ID = FDecl->getBuiltinID()) 5807 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5808 return false; 5809 5810 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5811 // assignment, to the types of the corresponding parameter, ... 5812 unsigned NumParams = Proto->getNumParams(); 5813 bool Invalid = false; 5814 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5815 unsigned FnKind = Fn->getType()->isBlockPointerType() 5816 ? 1 /* block */ 5817 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5818 : 0 /* function */); 5819 5820 // If too few arguments are available (and we don't have default 5821 // arguments for the remaining parameters), don't make the call. 5822 if (Args.size() < NumParams) { 5823 if (Args.size() < MinArgs) { 5824 TypoCorrection TC; 5825 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5826 unsigned diag_id = 5827 MinArgs == NumParams && !Proto->isVariadic() 5828 ? diag::err_typecheck_call_too_few_args_suggest 5829 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5830 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5831 << static_cast<unsigned>(Args.size()) 5832 << TC.getCorrectionRange()); 5833 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5834 Diag(RParenLoc, 5835 MinArgs == NumParams && !Proto->isVariadic() 5836 ? diag::err_typecheck_call_too_few_args_one 5837 : diag::err_typecheck_call_too_few_args_at_least_one) 5838 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5839 else 5840 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5841 ? diag::err_typecheck_call_too_few_args 5842 : diag::err_typecheck_call_too_few_args_at_least) 5843 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5844 << Fn->getSourceRange(); 5845 5846 // Emit the location of the prototype. 5847 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5848 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5849 5850 return true; 5851 } 5852 // We reserve space for the default arguments when we create 5853 // the call expression, before calling ConvertArgumentsForCall. 5854 assert((Call->getNumArgs() == NumParams) && 5855 "We should have reserved space for the default arguments before!"); 5856 } 5857 5858 // If too many are passed and not variadic, error on the extras and drop 5859 // them. 5860 if (Args.size() > NumParams) { 5861 if (!Proto->isVariadic()) { 5862 TypoCorrection TC; 5863 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5864 unsigned diag_id = 5865 MinArgs == NumParams && !Proto->isVariadic() 5866 ? diag::err_typecheck_call_too_many_args_suggest 5867 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5868 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5869 << static_cast<unsigned>(Args.size()) 5870 << TC.getCorrectionRange()); 5871 } else if (NumParams == 1 && FDecl && 5872 FDecl->getParamDecl(0)->getDeclName()) 5873 Diag(Args[NumParams]->getBeginLoc(), 5874 MinArgs == NumParams 5875 ? diag::err_typecheck_call_too_many_args_one 5876 : diag::err_typecheck_call_too_many_args_at_most_one) 5877 << FnKind << FDecl->getParamDecl(0) 5878 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5879 << SourceRange(Args[NumParams]->getBeginLoc(), 5880 Args.back()->getEndLoc()); 5881 else 5882 Diag(Args[NumParams]->getBeginLoc(), 5883 MinArgs == NumParams 5884 ? diag::err_typecheck_call_too_many_args 5885 : diag::err_typecheck_call_too_many_args_at_most) 5886 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5887 << Fn->getSourceRange() 5888 << SourceRange(Args[NumParams]->getBeginLoc(), 5889 Args.back()->getEndLoc()); 5890 5891 // Emit the location of the prototype. 5892 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5893 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5894 5895 // This deletes the extra arguments. 5896 Call->shrinkNumArgs(NumParams); 5897 return true; 5898 } 5899 } 5900 SmallVector<Expr *, 8> AllArgs; 5901 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5902 5903 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5904 AllArgs, CallType); 5905 if (Invalid) 5906 return true; 5907 unsigned TotalNumArgs = AllArgs.size(); 5908 for (unsigned i = 0; i < TotalNumArgs; ++i) 5909 Call->setArg(i, AllArgs[i]); 5910 5911 Call->computeDependence(); 5912 return false; 5913 } 5914 5915 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5916 const FunctionProtoType *Proto, 5917 unsigned FirstParam, ArrayRef<Expr *> Args, 5918 SmallVectorImpl<Expr *> &AllArgs, 5919 VariadicCallType CallType, bool AllowExplicit, 5920 bool IsListInitialization) { 5921 unsigned NumParams = Proto->getNumParams(); 5922 bool Invalid = false; 5923 size_t ArgIx = 0; 5924 // Continue to check argument types (even if we have too few/many args). 5925 for (unsigned i = FirstParam; i < NumParams; i++) { 5926 QualType ProtoArgType = Proto->getParamType(i); 5927 5928 Expr *Arg; 5929 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5930 if (ArgIx < Args.size()) { 5931 Arg = Args[ArgIx++]; 5932 5933 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5934 diag::err_call_incomplete_argument, Arg)) 5935 return true; 5936 5937 // Strip the unbridged-cast placeholder expression off, if applicable. 5938 bool CFAudited = false; 5939 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5940 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5941 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5942 Arg = stripARCUnbridgedCast(Arg); 5943 else if (getLangOpts().ObjCAutoRefCount && 5944 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5945 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5946 CFAudited = true; 5947 5948 if (Proto->getExtParameterInfo(i).isNoEscape() && 5949 ProtoArgType->isBlockPointerType()) 5950 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5951 BE->getBlockDecl()->setDoesNotEscape(); 5952 5953 InitializedEntity Entity = 5954 Param ? InitializedEntity::InitializeParameter(Context, Param, 5955 ProtoArgType) 5956 : InitializedEntity::InitializeParameter( 5957 Context, ProtoArgType, Proto->isParamConsumed(i)); 5958 5959 // Remember that parameter belongs to a CF audited API. 5960 if (CFAudited) 5961 Entity.setParameterCFAudited(); 5962 5963 ExprResult ArgE = PerformCopyInitialization( 5964 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5965 if (ArgE.isInvalid()) 5966 return true; 5967 5968 Arg = ArgE.getAs<Expr>(); 5969 } else { 5970 assert(Param && "can't use default arguments without a known callee"); 5971 5972 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5973 if (ArgExpr.isInvalid()) 5974 return true; 5975 5976 Arg = ArgExpr.getAs<Expr>(); 5977 } 5978 5979 // Check for array bounds violations for each argument to the call. This 5980 // check only triggers warnings when the argument isn't a more complex Expr 5981 // with its own checking, such as a BinaryOperator. 5982 CheckArrayAccess(Arg); 5983 5984 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5985 CheckStaticArrayArgument(CallLoc, Param, Arg); 5986 5987 AllArgs.push_back(Arg); 5988 } 5989 5990 // If this is a variadic call, handle args passed through "...". 5991 if (CallType != VariadicDoesNotApply) { 5992 // Assume that extern "C" functions with variadic arguments that 5993 // return __unknown_anytype aren't *really* variadic. 5994 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5995 FDecl->isExternC()) { 5996 for (Expr *A : Args.slice(ArgIx)) { 5997 QualType paramType; // ignored 5998 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5999 Invalid |= arg.isInvalid(); 6000 AllArgs.push_back(arg.get()); 6001 } 6002 6003 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6004 } else { 6005 for (Expr *A : Args.slice(ArgIx)) { 6006 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6007 Invalid |= Arg.isInvalid(); 6008 AllArgs.push_back(Arg.get()); 6009 } 6010 } 6011 6012 // Check for array bounds violations. 6013 for (Expr *A : Args.slice(ArgIx)) 6014 CheckArrayAccess(A); 6015 } 6016 return Invalid; 6017 } 6018 6019 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6020 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6021 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6022 TL = DTL.getOriginalLoc(); 6023 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6024 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6025 << ATL.getLocalSourceRange(); 6026 } 6027 6028 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6029 /// array parameter, check that it is non-null, and that if it is formed by 6030 /// array-to-pointer decay, the underlying array is sufficiently large. 6031 /// 6032 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6033 /// array type derivation, then for each call to the function, the value of the 6034 /// corresponding actual argument shall provide access to the first element of 6035 /// an array with at least as many elements as specified by the size expression. 6036 void 6037 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6038 ParmVarDecl *Param, 6039 const Expr *ArgExpr) { 6040 // Static array parameters are not supported in C++. 6041 if (!Param || getLangOpts().CPlusPlus) 6042 return; 6043 6044 QualType OrigTy = Param->getOriginalType(); 6045 6046 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6047 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6048 return; 6049 6050 if (ArgExpr->isNullPointerConstant(Context, 6051 Expr::NPC_NeverValueDependent)) { 6052 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6053 DiagnoseCalleeStaticArrayParam(*this, Param); 6054 return; 6055 } 6056 6057 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6058 if (!CAT) 6059 return; 6060 6061 const ConstantArrayType *ArgCAT = 6062 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6063 if (!ArgCAT) 6064 return; 6065 6066 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6067 ArgCAT->getElementType())) { 6068 if (ArgCAT->getSize().ult(CAT->getSize())) { 6069 Diag(CallLoc, diag::warn_static_array_too_small) 6070 << ArgExpr->getSourceRange() 6071 << (unsigned)ArgCAT->getSize().getZExtValue() 6072 << (unsigned)CAT->getSize().getZExtValue() << 0; 6073 DiagnoseCalleeStaticArrayParam(*this, Param); 6074 } 6075 return; 6076 } 6077 6078 Optional<CharUnits> ArgSize = 6079 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6080 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6081 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6082 Diag(CallLoc, diag::warn_static_array_too_small) 6083 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6084 << (unsigned)ParmSize->getQuantity() << 1; 6085 DiagnoseCalleeStaticArrayParam(*this, Param); 6086 } 6087 } 6088 6089 /// Given a function expression of unknown-any type, try to rebuild it 6090 /// to have a function type. 6091 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6092 6093 /// Is the given type a placeholder that we need to lower out 6094 /// immediately during argument processing? 6095 static bool isPlaceholderToRemoveAsArg(QualType type) { 6096 // Placeholders are never sugared. 6097 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6098 if (!placeholder) return false; 6099 6100 switch (placeholder->getKind()) { 6101 // Ignore all the non-placeholder types. 6102 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6103 case BuiltinType::Id: 6104 #include "clang/Basic/OpenCLImageTypes.def" 6105 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6106 case BuiltinType::Id: 6107 #include "clang/Basic/OpenCLExtensionTypes.def" 6108 // In practice we'll never use this, since all SVE types are sugared 6109 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6110 #define SVE_TYPE(Name, Id, SingletonId) \ 6111 case BuiltinType::Id: 6112 #include "clang/Basic/AArch64SVEACLETypes.def" 6113 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6114 case BuiltinType::Id: 6115 #include "clang/Basic/PPCTypes.def" 6116 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6117 #include "clang/Basic/RISCVVTypes.def" 6118 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6119 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6120 #include "clang/AST/BuiltinTypes.def" 6121 return false; 6122 6123 // We cannot lower out overload sets; they might validly be resolved 6124 // by the call machinery. 6125 case BuiltinType::Overload: 6126 return false; 6127 6128 // Unbridged casts in ARC can be handled in some call positions and 6129 // should be left in place. 6130 case BuiltinType::ARCUnbridgedCast: 6131 return false; 6132 6133 // Pseudo-objects should be converted as soon as possible. 6134 case BuiltinType::PseudoObject: 6135 return true; 6136 6137 // The debugger mode could theoretically but currently does not try 6138 // to resolve unknown-typed arguments based on known parameter types. 6139 case BuiltinType::UnknownAny: 6140 return true; 6141 6142 // These are always invalid as call arguments and should be reported. 6143 case BuiltinType::BoundMember: 6144 case BuiltinType::BuiltinFn: 6145 case BuiltinType::IncompleteMatrixIdx: 6146 case BuiltinType::OMPArraySection: 6147 case BuiltinType::OMPArrayShaping: 6148 case BuiltinType::OMPIterator: 6149 return true; 6150 6151 } 6152 llvm_unreachable("bad builtin type kind"); 6153 } 6154 6155 /// Check an argument list for placeholders that we won't try to 6156 /// handle later. 6157 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6158 // Apply this processing to all the arguments at once instead of 6159 // dying at the first failure. 6160 bool hasInvalid = false; 6161 for (size_t i = 0, e = args.size(); i != e; i++) { 6162 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6163 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6164 if (result.isInvalid()) hasInvalid = true; 6165 else args[i] = result.get(); 6166 } 6167 } 6168 return hasInvalid; 6169 } 6170 6171 /// If a builtin function has a pointer argument with no explicit address 6172 /// space, then it should be able to accept a pointer to any address 6173 /// space as input. In order to do this, we need to replace the 6174 /// standard builtin declaration with one that uses the same address space 6175 /// as the call. 6176 /// 6177 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6178 /// it does not contain any pointer arguments without 6179 /// an address space qualifer. Otherwise the rewritten 6180 /// FunctionDecl is returned. 6181 /// TODO: Handle pointer return types. 6182 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6183 FunctionDecl *FDecl, 6184 MultiExprArg ArgExprs) { 6185 6186 QualType DeclType = FDecl->getType(); 6187 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6188 6189 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6190 ArgExprs.size() < FT->getNumParams()) 6191 return nullptr; 6192 6193 bool NeedsNewDecl = false; 6194 unsigned i = 0; 6195 SmallVector<QualType, 8> OverloadParams; 6196 6197 for (QualType ParamType : FT->param_types()) { 6198 6199 // Convert array arguments to pointer to simplify type lookup. 6200 ExprResult ArgRes = 6201 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6202 if (ArgRes.isInvalid()) 6203 return nullptr; 6204 Expr *Arg = ArgRes.get(); 6205 QualType ArgType = Arg->getType(); 6206 if (!ParamType->isPointerType() || 6207 ParamType.hasAddressSpace() || 6208 !ArgType->isPointerType() || 6209 !ArgType->getPointeeType().hasAddressSpace()) { 6210 OverloadParams.push_back(ParamType); 6211 continue; 6212 } 6213 6214 QualType PointeeType = ParamType->getPointeeType(); 6215 if (PointeeType.hasAddressSpace()) 6216 continue; 6217 6218 NeedsNewDecl = true; 6219 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6220 6221 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6222 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6223 } 6224 6225 if (!NeedsNewDecl) 6226 return nullptr; 6227 6228 FunctionProtoType::ExtProtoInfo EPI; 6229 EPI.Variadic = FT->isVariadic(); 6230 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6231 OverloadParams, EPI); 6232 DeclContext *Parent = FDecl->getParent(); 6233 FunctionDecl *OverloadDecl = FunctionDecl::Create( 6234 Context, Parent, FDecl->getLocation(), FDecl->getLocation(), 6235 FDecl->getIdentifier(), OverloadTy, 6236 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), 6237 false, 6238 /*hasPrototype=*/true); 6239 SmallVector<ParmVarDecl*, 16> Params; 6240 FT = cast<FunctionProtoType>(OverloadTy); 6241 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6242 QualType ParamType = FT->getParamType(i); 6243 ParmVarDecl *Parm = 6244 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6245 SourceLocation(), nullptr, ParamType, 6246 /*TInfo=*/nullptr, SC_None, nullptr); 6247 Parm->setScopeInfo(0, i); 6248 Params.push_back(Parm); 6249 } 6250 OverloadDecl->setParams(Params); 6251 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6252 return OverloadDecl; 6253 } 6254 6255 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6256 FunctionDecl *Callee, 6257 MultiExprArg ArgExprs) { 6258 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6259 // similar attributes) really don't like it when functions are called with an 6260 // invalid number of args. 6261 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6262 /*PartialOverloading=*/false) && 6263 !Callee->isVariadic()) 6264 return; 6265 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6266 return; 6267 6268 if (const EnableIfAttr *Attr = 6269 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6270 S.Diag(Fn->getBeginLoc(), 6271 isa<CXXMethodDecl>(Callee) 6272 ? diag::err_ovl_no_viable_member_function_in_call 6273 : diag::err_ovl_no_viable_function_in_call) 6274 << Callee << Callee->getSourceRange(); 6275 S.Diag(Callee->getLocation(), 6276 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6277 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6278 return; 6279 } 6280 } 6281 6282 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6283 const UnresolvedMemberExpr *const UME, Sema &S) { 6284 6285 const auto GetFunctionLevelDCIfCXXClass = 6286 [](Sema &S) -> const CXXRecordDecl * { 6287 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6288 if (!DC || !DC->getParent()) 6289 return nullptr; 6290 6291 // If the call to some member function was made from within a member 6292 // function body 'M' return return 'M's parent. 6293 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6294 return MD->getParent()->getCanonicalDecl(); 6295 // else the call was made from within a default member initializer of a 6296 // class, so return the class. 6297 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6298 return RD->getCanonicalDecl(); 6299 return nullptr; 6300 }; 6301 // If our DeclContext is neither a member function nor a class (in the 6302 // case of a lambda in a default member initializer), we can't have an 6303 // enclosing 'this'. 6304 6305 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6306 if (!CurParentClass) 6307 return false; 6308 6309 // The naming class for implicit member functions call is the class in which 6310 // name lookup starts. 6311 const CXXRecordDecl *const NamingClass = 6312 UME->getNamingClass()->getCanonicalDecl(); 6313 assert(NamingClass && "Must have naming class even for implicit access"); 6314 6315 // If the unresolved member functions were found in a 'naming class' that is 6316 // related (either the same or derived from) to the class that contains the 6317 // member function that itself contained the implicit member access. 6318 6319 return CurParentClass == NamingClass || 6320 CurParentClass->isDerivedFrom(NamingClass); 6321 } 6322 6323 static void 6324 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6325 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6326 6327 if (!UME) 6328 return; 6329 6330 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6331 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6332 // already been captured, or if this is an implicit member function call (if 6333 // it isn't, an attempt to capture 'this' should already have been made). 6334 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6335 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6336 return; 6337 6338 // Check if the naming class in which the unresolved members were found is 6339 // related (same as or is a base of) to the enclosing class. 6340 6341 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6342 return; 6343 6344 6345 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6346 // If the enclosing function is not dependent, then this lambda is 6347 // capture ready, so if we can capture this, do so. 6348 if (!EnclosingFunctionCtx->isDependentContext()) { 6349 // If the current lambda and all enclosing lambdas can capture 'this' - 6350 // then go ahead and capture 'this' (since our unresolved overload set 6351 // contains at least one non-static member function). 6352 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6353 S.CheckCXXThisCapture(CallLoc); 6354 } else if (S.CurContext->isDependentContext()) { 6355 // ... since this is an implicit member reference, that might potentially 6356 // involve a 'this' capture, mark 'this' for potential capture in 6357 // enclosing lambdas. 6358 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6359 CurLSI->addPotentialThisCapture(CallLoc); 6360 } 6361 } 6362 6363 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6364 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6365 Expr *ExecConfig) { 6366 ExprResult Call = 6367 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6368 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6369 if (Call.isInvalid()) 6370 return Call; 6371 6372 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6373 // language modes. 6374 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6375 if (ULE->hasExplicitTemplateArgs() && 6376 ULE->decls_begin() == ULE->decls_end()) { 6377 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6378 ? diag::warn_cxx17_compat_adl_only_template_id 6379 : diag::ext_adl_only_template_id) 6380 << ULE->getName(); 6381 } 6382 } 6383 6384 if (LangOpts.OpenMP) 6385 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6386 ExecConfig); 6387 6388 return Call; 6389 } 6390 6391 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6392 /// This provides the location of the left/right parens and a list of comma 6393 /// locations. 6394 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6395 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6396 Expr *ExecConfig, bool IsExecConfig, 6397 bool AllowRecovery) { 6398 // Since this might be a postfix expression, get rid of ParenListExprs. 6399 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6400 if (Result.isInvalid()) return ExprError(); 6401 Fn = Result.get(); 6402 6403 if (checkArgsForPlaceholders(*this, ArgExprs)) 6404 return ExprError(); 6405 6406 if (getLangOpts().CPlusPlus) { 6407 // If this is a pseudo-destructor expression, build the call immediately. 6408 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6409 if (!ArgExprs.empty()) { 6410 // Pseudo-destructor calls should not have any arguments. 6411 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6412 << FixItHint::CreateRemoval( 6413 SourceRange(ArgExprs.front()->getBeginLoc(), 6414 ArgExprs.back()->getEndLoc())); 6415 } 6416 6417 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6418 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6419 } 6420 if (Fn->getType() == Context.PseudoObjectTy) { 6421 ExprResult result = CheckPlaceholderExpr(Fn); 6422 if (result.isInvalid()) return ExprError(); 6423 Fn = result.get(); 6424 } 6425 6426 // Determine whether this is a dependent call inside a C++ template, 6427 // in which case we won't do any semantic analysis now. 6428 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6429 if (ExecConfig) { 6430 return CUDAKernelCallExpr::Create(Context, Fn, 6431 cast<CallExpr>(ExecConfig), ArgExprs, 6432 Context.DependentTy, VK_PRValue, 6433 RParenLoc, CurFPFeatureOverrides()); 6434 } else { 6435 6436 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6437 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6438 Fn->getBeginLoc()); 6439 6440 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6441 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6442 } 6443 } 6444 6445 // Determine whether this is a call to an object (C++ [over.call.object]). 6446 if (Fn->getType()->isRecordType()) 6447 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6448 RParenLoc); 6449 6450 if (Fn->getType() == Context.UnknownAnyTy) { 6451 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6452 if (result.isInvalid()) return ExprError(); 6453 Fn = result.get(); 6454 } 6455 6456 if (Fn->getType() == Context.BoundMemberTy) { 6457 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6458 RParenLoc, ExecConfig, IsExecConfig, 6459 AllowRecovery); 6460 } 6461 } 6462 6463 // Check for overloaded calls. This can happen even in C due to extensions. 6464 if (Fn->getType() == Context.OverloadTy) { 6465 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6466 6467 // We aren't supposed to apply this logic if there's an '&' involved. 6468 if (!find.HasFormOfMemberPointer) { 6469 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6470 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6471 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6472 OverloadExpr *ovl = find.Expression; 6473 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6474 return BuildOverloadedCallExpr( 6475 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6476 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6477 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6478 RParenLoc, ExecConfig, IsExecConfig, 6479 AllowRecovery); 6480 } 6481 } 6482 6483 // If we're directly calling a function, get the appropriate declaration. 6484 if (Fn->getType() == Context.UnknownAnyTy) { 6485 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6486 if (result.isInvalid()) return ExprError(); 6487 Fn = result.get(); 6488 } 6489 6490 Expr *NakedFn = Fn->IgnoreParens(); 6491 6492 bool CallingNDeclIndirectly = false; 6493 NamedDecl *NDecl = nullptr; 6494 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6495 if (UnOp->getOpcode() == UO_AddrOf) { 6496 CallingNDeclIndirectly = true; 6497 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6498 } 6499 } 6500 6501 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6502 NDecl = DRE->getDecl(); 6503 6504 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6505 if (FDecl && FDecl->getBuiltinID()) { 6506 // Rewrite the function decl for this builtin by replacing parameters 6507 // with no explicit address space with the address space of the arguments 6508 // in ArgExprs. 6509 if ((FDecl = 6510 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6511 NDecl = FDecl; 6512 Fn = DeclRefExpr::Create( 6513 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6514 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6515 nullptr, DRE->isNonOdrUse()); 6516 } 6517 } 6518 } else if (isa<MemberExpr>(NakedFn)) 6519 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6520 6521 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6522 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6523 FD, /*Complain=*/true, Fn->getBeginLoc())) 6524 return ExprError(); 6525 6526 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6527 6528 // If this expression is a call to a builtin function in HIP device 6529 // compilation, allow a pointer-type argument to default address space to be 6530 // passed as a pointer-type parameter to a non-default address space. 6531 // If Arg is declared in the default address space and Param is declared 6532 // in a non-default address space, perform an implicit address space cast to 6533 // the parameter type. 6534 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && 6535 FD->getBuiltinID()) { 6536 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) { 6537 ParmVarDecl *Param = FD->getParamDecl(Idx); 6538 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || 6539 !ArgExprs[Idx]->getType()->isPointerType()) 6540 continue; 6541 6542 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); 6543 auto ArgTy = ArgExprs[Idx]->getType(); 6544 auto ArgPtTy = ArgTy->getPointeeType(); 6545 auto ArgAS = ArgPtTy.getAddressSpace(); 6546 6547 // Add address space cast if target address spaces are different 6548 bool NeedImplicitASC = 6549 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling. 6550 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS 6551 // or from specific AS which has target AS matching that of Param. 6552 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS)); 6553 if (!NeedImplicitASC) 6554 continue; 6555 6556 // First, ensure that the Arg is an RValue. 6557 if (ArgExprs[Idx]->isGLValue()) { 6558 ArgExprs[Idx] = ImplicitCastExpr::Create( 6559 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx], 6560 nullptr, VK_PRValue, FPOptionsOverride()); 6561 } 6562 6563 // Construct a new arg type with address space of Param 6564 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); 6565 ArgPtQuals.setAddressSpace(ParamAS); 6566 auto NewArgPtTy = 6567 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); 6568 auto NewArgTy = 6569 Context.getQualifiedType(Context.getPointerType(NewArgPtTy), 6570 ArgTy.getQualifiers()); 6571 6572 // Finally perform an implicit address space cast 6573 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, 6574 CK_AddressSpaceConversion) 6575 .get(); 6576 } 6577 } 6578 } 6579 6580 if (Context.isDependenceAllowed() && 6581 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6582 assert(!getLangOpts().CPlusPlus); 6583 assert((Fn->containsErrors() || 6584 llvm::any_of(ArgExprs, 6585 [](clang::Expr *E) { return E->containsErrors(); })) && 6586 "should only occur in error-recovery path."); 6587 QualType ReturnType = 6588 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6589 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6590 : Context.DependentTy; 6591 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6592 Expr::getValueKindForType(ReturnType), RParenLoc, 6593 CurFPFeatureOverrides()); 6594 } 6595 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6596 ExecConfig, IsExecConfig); 6597 } 6598 6599 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id 6600 // with the specified CallArgs 6601 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 6602 MultiExprArg CallArgs) { 6603 StringRef Name = Context.BuiltinInfo.getName(Id); 6604 LookupResult R(*this, &Context.Idents.get(Name), Loc, 6605 Sema::LookupOrdinaryName); 6606 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); 6607 6608 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); 6609 assert(BuiltInDecl && "failed to find builtin declaration"); 6610 6611 ExprResult DeclRef = 6612 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); 6613 assert(DeclRef.isUsable() && "Builtin reference cannot fail"); 6614 6615 ExprResult Call = 6616 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); 6617 6618 assert(!Call.isInvalid() && "Call to builtin cannot fail!"); 6619 return Call.get(); 6620 } 6621 6622 /// Parse a __builtin_astype expression. 6623 /// 6624 /// __builtin_astype( value, dst type ) 6625 /// 6626 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6627 SourceLocation BuiltinLoc, 6628 SourceLocation RParenLoc) { 6629 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6630 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6631 } 6632 6633 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6634 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6635 SourceLocation BuiltinLoc, 6636 SourceLocation RParenLoc) { 6637 ExprValueKind VK = VK_PRValue; 6638 ExprObjectKind OK = OK_Ordinary; 6639 QualType SrcTy = E->getType(); 6640 if (!SrcTy->isDependentType() && 6641 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6642 return ExprError( 6643 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6644 << DestTy << SrcTy << E->getSourceRange()); 6645 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6646 } 6647 6648 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6649 /// provided arguments. 6650 /// 6651 /// __builtin_convertvector( value, dst type ) 6652 /// 6653 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6654 SourceLocation BuiltinLoc, 6655 SourceLocation RParenLoc) { 6656 TypeSourceInfo *TInfo; 6657 GetTypeFromParser(ParsedDestTy, &TInfo); 6658 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6659 } 6660 6661 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6662 /// i.e. an expression not of \p OverloadTy. The expression should 6663 /// unary-convert to an expression of function-pointer or 6664 /// block-pointer type. 6665 /// 6666 /// \param NDecl the declaration being called, if available 6667 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6668 SourceLocation LParenLoc, 6669 ArrayRef<Expr *> Args, 6670 SourceLocation RParenLoc, Expr *Config, 6671 bool IsExecConfig, ADLCallKind UsesADL) { 6672 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6673 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6674 6675 // Functions with 'interrupt' attribute cannot be called directly. 6676 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6677 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6678 return ExprError(); 6679 } 6680 6681 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6682 // so there's some risk when calling out to non-interrupt handler functions 6683 // that the callee might not preserve them. This is easy to diagnose here, 6684 // but can be very challenging to debug. 6685 // Likewise, X86 interrupt handlers may only call routines with attribute 6686 // no_caller_saved_registers since there is no efficient way to 6687 // save and restore the non-GPR state. 6688 if (auto *Caller = getCurFunctionDecl()) { 6689 if (Caller->hasAttr<ARMInterruptAttr>()) { 6690 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6691 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6692 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6693 if (FDecl) 6694 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6695 } 6696 } 6697 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6698 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6699 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6700 if (FDecl) 6701 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6702 } 6703 } 6704 6705 // Promote the function operand. 6706 // We special-case function promotion here because we only allow promoting 6707 // builtin functions to function pointers in the callee of a call. 6708 ExprResult Result; 6709 QualType ResultTy; 6710 if (BuiltinID && 6711 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6712 // Extract the return type from the (builtin) function pointer type. 6713 // FIXME Several builtins still have setType in 6714 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6715 // Builtins.def to ensure they are correct before removing setType calls. 6716 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6717 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6718 ResultTy = FDecl->getCallResultType(); 6719 } else { 6720 Result = CallExprUnaryConversions(Fn); 6721 ResultTy = Context.BoolTy; 6722 } 6723 if (Result.isInvalid()) 6724 return ExprError(); 6725 Fn = Result.get(); 6726 6727 // Check for a valid function type, but only if it is not a builtin which 6728 // requires custom type checking. These will be handled by 6729 // CheckBuiltinFunctionCall below just after creation of the call expression. 6730 const FunctionType *FuncT = nullptr; 6731 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6732 retry: 6733 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6734 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6735 // have type pointer to function". 6736 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6737 if (!FuncT) 6738 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6739 << Fn->getType() << Fn->getSourceRange()); 6740 } else if (const BlockPointerType *BPT = 6741 Fn->getType()->getAs<BlockPointerType>()) { 6742 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6743 } else { 6744 // Handle calls to expressions of unknown-any type. 6745 if (Fn->getType() == Context.UnknownAnyTy) { 6746 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6747 if (rewrite.isInvalid()) 6748 return ExprError(); 6749 Fn = rewrite.get(); 6750 goto retry; 6751 } 6752 6753 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6754 << Fn->getType() << Fn->getSourceRange()); 6755 } 6756 } 6757 6758 // Get the number of parameters in the function prototype, if any. 6759 // We will allocate space for max(Args.size(), NumParams) arguments 6760 // in the call expression. 6761 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6762 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6763 6764 CallExpr *TheCall; 6765 if (Config) { 6766 assert(UsesADL == ADLCallKind::NotADL && 6767 "CUDAKernelCallExpr should not use ADL"); 6768 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6769 Args, ResultTy, VK_PRValue, RParenLoc, 6770 CurFPFeatureOverrides(), NumParams); 6771 } else { 6772 TheCall = 6773 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6774 CurFPFeatureOverrides(), NumParams, UsesADL); 6775 } 6776 6777 if (!Context.isDependenceAllowed()) { 6778 // Forget about the nulled arguments since typo correction 6779 // do not handle them well. 6780 TheCall->shrinkNumArgs(Args.size()); 6781 // C cannot always handle TypoExpr nodes in builtin calls and direct 6782 // function calls as their argument checking don't necessarily handle 6783 // dependent types properly, so make sure any TypoExprs have been 6784 // dealt with. 6785 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6786 if (!Result.isUsable()) return ExprError(); 6787 CallExpr *TheOldCall = TheCall; 6788 TheCall = dyn_cast<CallExpr>(Result.get()); 6789 bool CorrectedTypos = TheCall != TheOldCall; 6790 if (!TheCall) return Result; 6791 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6792 6793 // A new call expression node was created if some typos were corrected. 6794 // However it may not have been constructed with enough storage. In this 6795 // case, rebuild the node with enough storage. The waste of space is 6796 // immaterial since this only happens when some typos were corrected. 6797 if (CorrectedTypos && Args.size() < NumParams) { 6798 if (Config) 6799 TheCall = CUDAKernelCallExpr::Create( 6800 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 6801 RParenLoc, CurFPFeatureOverrides(), NumParams); 6802 else 6803 TheCall = 6804 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6805 CurFPFeatureOverrides(), NumParams, UsesADL); 6806 } 6807 // We can now handle the nulled arguments for the default arguments. 6808 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6809 } 6810 6811 // Bail out early if calling a builtin with custom type checking. 6812 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6813 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6814 6815 if (getLangOpts().CUDA) { 6816 if (Config) { 6817 // CUDA: Kernel calls must be to global functions 6818 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6819 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6820 << FDecl << Fn->getSourceRange()); 6821 6822 // CUDA: Kernel function must have 'void' return type 6823 if (!FuncT->getReturnType()->isVoidType() && 6824 !FuncT->getReturnType()->getAs<AutoType>() && 6825 !FuncT->getReturnType()->isInstantiationDependentType()) 6826 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6827 << Fn->getType() << Fn->getSourceRange()); 6828 } else { 6829 // CUDA: Calls to global functions must be configured 6830 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6831 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6832 << FDecl << Fn->getSourceRange()); 6833 } 6834 } 6835 6836 // Check for a valid return type 6837 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6838 FDecl)) 6839 return ExprError(); 6840 6841 // We know the result type of the call, set it. 6842 TheCall->setType(FuncT->getCallResultType(Context)); 6843 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6844 6845 if (Proto) { 6846 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6847 IsExecConfig)) 6848 return ExprError(); 6849 } else { 6850 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6851 6852 if (FDecl) { 6853 // Check if we have too few/too many template arguments, based 6854 // on our knowledge of the function definition. 6855 const FunctionDecl *Def = nullptr; 6856 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6857 Proto = Def->getType()->getAs<FunctionProtoType>(); 6858 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6859 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6860 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6861 } 6862 6863 // If the function we're calling isn't a function prototype, but we have 6864 // a function prototype from a prior declaratiom, use that prototype. 6865 if (!FDecl->hasPrototype()) 6866 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6867 } 6868 6869 // Promote the arguments (C99 6.5.2.2p6). 6870 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6871 Expr *Arg = Args[i]; 6872 6873 if (Proto && i < Proto->getNumParams()) { 6874 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6875 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6876 ExprResult ArgE = 6877 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6878 if (ArgE.isInvalid()) 6879 return true; 6880 6881 Arg = ArgE.getAs<Expr>(); 6882 6883 } else { 6884 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6885 6886 if (ArgE.isInvalid()) 6887 return true; 6888 6889 Arg = ArgE.getAs<Expr>(); 6890 } 6891 6892 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6893 diag::err_call_incomplete_argument, Arg)) 6894 return ExprError(); 6895 6896 TheCall->setArg(i, Arg); 6897 } 6898 TheCall->computeDependence(); 6899 } 6900 6901 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6902 if (!Method->isStatic()) 6903 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6904 << Fn->getSourceRange()); 6905 6906 // Check for sentinels 6907 if (NDecl) 6908 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6909 6910 // Warn for unions passing across security boundary (CMSE). 6911 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6912 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6913 if (const auto *RT = 6914 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6915 if (RT->getDecl()->isOrContainsUnion()) 6916 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6917 << 0 << i; 6918 } 6919 } 6920 } 6921 6922 // Do special checking on direct calls to functions. 6923 if (FDecl) { 6924 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6925 return ExprError(); 6926 6927 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6928 6929 if (BuiltinID) 6930 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6931 } else if (NDecl) { 6932 if (CheckPointerCall(NDecl, TheCall, Proto)) 6933 return ExprError(); 6934 } else { 6935 if (CheckOtherCall(TheCall, Proto)) 6936 return ExprError(); 6937 } 6938 6939 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6940 } 6941 6942 ExprResult 6943 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6944 SourceLocation RParenLoc, Expr *InitExpr) { 6945 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6946 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6947 6948 TypeSourceInfo *TInfo; 6949 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6950 if (!TInfo) 6951 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6952 6953 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6954 } 6955 6956 ExprResult 6957 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6958 SourceLocation RParenLoc, Expr *LiteralExpr) { 6959 QualType literalType = TInfo->getType(); 6960 6961 if (literalType->isArrayType()) { 6962 if (RequireCompleteSizedType( 6963 LParenLoc, Context.getBaseElementType(literalType), 6964 diag::err_array_incomplete_or_sizeless_type, 6965 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6966 return ExprError(); 6967 if (literalType->isVariableArrayType()) { 6968 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 6969 diag::err_variable_object_no_init)) { 6970 return ExprError(); 6971 } 6972 } 6973 } else if (!literalType->isDependentType() && 6974 RequireCompleteType(LParenLoc, literalType, 6975 diag::err_typecheck_decl_incomplete_type, 6976 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6977 return ExprError(); 6978 6979 InitializedEntity Entity 6980 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6981 InitializationKind Kind 6982 = InitializationKind::CreateCStyleCast(LParenLoc, 6983 SourceRange(LParenLoc, RParenLoc), 6984 /*InitList=*/true); 6985 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6986 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6987 &literalType); 6988 if (Result.isInvalid()) 6989 return ExprError(); 6990 LiteralExpr = Result.get(); 6991 6992 bool isFileScope = !CurContext->isFunctionOrMethod(); 6993 6994 // In C, compound literals are l-values for some reason. 6995 // For GCC compatibility, in C++, file-scope array compound literals with 6996 // constant initializers are also l-values, and compound literals are 6997 // otherwise prvalues. 6998 // 6999 // (GCC also treats C++ list-initialized file-scope array prvalues with 7000 // constant initializers as l-values, but that's non-conforming, so we don't 7001 // follow it there.) 7002 // 7003 // FIXME: It would be better to handle the lvalue cases as materializing and 7004 // lifetime-extending a temporary object, but our materialized temporaries 7005 // representation only supports lifetime extension from a variable, not "out 7006 // of thin air". 7007 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 7008 // is bound to the result of applying array-to-pointer decay to the compound 7009 // literal. 7010 // FIXME: GCC supports compound literals of reference type, which should 7011 // obviously have a value kind derived from the kind of reference involved. 7012 ExprValueKind VK = 7013 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 7014 ? VK_PRValue 7015 : VK_LValue; 7016 7017 if (isFileScope) 7018 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 7019 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 7020 Expr *Init = ILE->getInit(i); 7021 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 7022 } 7023 7024 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 7025 VK, LiteralExpr, isFileScope); 7026 if (isFileScope) { 7027 if (!LiteralExpr->isTypeDependent() && 7028 !LiteralExpr->isValueDependent() && 7029 !literalType->isDependentType()) // C99 6.5.2.5p3 7030 if (CheckForConstantInitializer(LiteralExpr, literalType)) 7031 return ExprError(); 7032 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 7033 literalType.getAddressSpace() != LangAS::Default) { 7034 // Embedded-C extensions to C99 6.5.2.5: 7035 // "If the compound literal occurs inside the body of a function, the 7036 // type name shall not be qualified by an address-space qualifier." 7037 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 7038 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 7039 return ExprError(); 7040 } 7041 7042 if (!isFileScope && !getLangOpts().CPlusPlus) { 7043 // Compound literals that have automatic storage duration are destroyed at 7044 // the end of the scope in C; in C++, they're just temporaries. 7045 7046 // Emit diagnostics if it is or contains a C union type that is non-trivial 7047 // to destruct. 7048 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 7049 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 7050 NTCUC_CompoundLiteral, NTCUK_Destruct); 7051 7052 // Diagnose jumps that enter or exit the lifetime of the compound literal. 7053 if (literalType.isDestructedType()) { 7054 Cleanup.setExprNeedsCleanups(true); 7055 ExprCleanupObjects.push_back(E); 7056 getCurFunction()->setHasBranchProtectedScope(); 7057 } 7058 } 7059 7060 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7061 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7062 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7063 E->getInitializer()->getExprLoc()); 7064 7065 return MaybeBindToTemporary(E); 7066 } 7067 7068 ExprResult 7069 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7070 SourceLocation RBraceLoc) { 7071 // Only produce each kind of designated initialization diagnostic once. 7072 SourceLocation FirstDesignator; 7073 bool DiagnosedArrayDesignator = false; 7074 bool DiagnosedNestedDesignator = false; 7075 bool DiagnosedMixedDesignator = false; 7076 7077 // Check that any designated initializers are syntactically valid in the 7078 // current language mode. 7079 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7080 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7081 if (FirstDesignator.isInvalid()) 7082 FirstDesignator = DIE->getBeginLoc(); 7083 7084 if (!getLangOpts().CPlusPlus) 7085 break; 7086 7087 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7088 DiagnosedNestedDesignator = true; 7089 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7090 << DIE->getDesignatorsSourceRange(); 7091 } 7092 7093 for (auto &Desig : DIE->designators()) { 7094 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7095 DiagnosedArrayDesignator = true; 7096 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7097 << Desig.getSourceRange(); 7098 } 7099 } 7100 7101 if (!DiagnosedMixedDesignator && 7102 !isa<DesignatedInitExpr>(InitArgList[0])) { 7103 DiagnosedMixedDesignator = true; 7104 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7105 << DIE->getSourceRange(); 7106 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7107 << InitArgList[0]->getSourceRange(); 7108 } 7109 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7110 isa<DesignatedInitExpr>(InitArgList[0])) { 7111 DiagnosedMixedDesignator = true; 7112 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7113 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7114 << DIE->getSourceRange(); 7115 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7116 << InitArgList[I]->getSourceRange(); 7117 } 7118 } 7119 7120 if (FirstDesignator.isValid()) { 7121 // Only diagnose designated initiaization as a C++20 extension if we didn't 7122 // already diagnose use of (non-C++20) C99 designator syntax. 7123 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7124 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7125 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7126 ? diag::warn_cxx17_compat_designated_init 7127 : diag::ext_cxx_designated_init); 7128 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7129 Diag(FirstDesignator, diag::ext_designated_init); 7130 } 7131 } 7132 7133 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7134 } 7135 7136 ExprResult 7137 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7138 SourceLocation RBraceLoc) { 7139 // Semantic analysis for initializers is done by ActOnDeclarator() and 7140 // CheckInitializer() - it requires knowledge of the object being initialized. 7141 7142 // Immediately handle non-overload placeholders. Overloads can be 7143 // resolved contextually, but everything else here can't. 7144 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7145 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7146 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7147 7148 // Ignore failures; dropping the entire initializer list because 7149 // of one failure would be terrible for indexing/etc. 7150 if (result.isInvalid()) continue; 7151 7152 InitArgList[I] = result.get(); 7153 } 7154 } 7155 7156 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7157 RBraceLoc); 7158 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7159 return E; 7160 } 7161 7162 /// Do an explicit extend of the given block pointer if we're in ARC. 7163 void Sema::maybeExtendBlockObject(ExprResult &E) { 7164 assert(E.get()->getType()->isBlockPointerType()); 7165 assert(E.get()->isPRValue()); 7166 7167 // Only do this in an r-value context. 7168 if (!getLangOpts().ObjCAutoRefCount) return; 7169 7170 E = ImplicitCastExpr::Create( 7171 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7172 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 7173 Cleanup.setExprNeedsCleanups(true); 7174 } 7175 7176 /// Prepare a conversion of the given expression to an ObjC object 7177 /// pointer type. 7178 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7179 QualType type = E.get()->getType(); 7180 if (type->isObjCObjectPointerType()) { 7181 return CK_BitCast; 7182 } else if (type->isBlockPointerType()) { 7183 maybeExtendBlockObject(E); 7184 return CK_BlockPointerToObjCPointerCast; 7185 } else { 7186 assert(type->isPointerType()); 7187 return CK_CPointerToObjCPointerCast; 7188 } 7189 } 7190 7191 /// Prepares for a scalar cast, performing all the necessary stages 7192 /// except the final cast and returning the kind required. 7193 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7194 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7195 // Also, callers should have filtered out the invalid cases with 7196 // pointers. Everything else should be possible. 7197 7198 QualType SrcTy = Src.get()->getType(); 7199 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7200 return CK_NoOp; 7201 7202 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7203 case Type::STK_MemberPointer: 7204 llvm_unreachable("member pointer type in C"); 7205 7206 case Type::STK_CPointer: 7207 case Type::STK_BlockPointer: 7208 case Type::STK_ObjCObjectPointer: 7209 switch (DestTy->getScalarTypeKind()) { 7210 case Type::STK_CPointer: { 7211 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7212 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7213 if (SrcAS != DestAS) 7214 return CK_AddressSpaceConversion; 7215 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7216 return CK_NoOp; 7217 return CK_BitCast; 7218 } 7219 case Type::STK_BlockPointer: 7220 return (SrcKind == Type::STK_BlockPointer 7221 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7222 case Type::STK_ObjCObjectPointer: 7223 if (SrcKind == Type::STK_ObjCObjectPointer) 7224 return CK_BitCast; 7225 if (SrcKind == Type::STK_CPointer) 7226 return CK_CPointerToObjCPointerCast; 7227 maybeExtendBlockObject(Src); 7228 return CK_BlockPointerToObjCPointerCast; 7229 case Type::STK_Bool: 7230 return CK_PointerToBoolean; 7231 case Type::STK_Integral: 7232 return CK_PointerToIntegral; 7233 case Type::STK_Floating: 7234 case Type::STK_FloatingComplex: 7235 case Type::STK_IntegralComplex: 7236 case Type::STK_MemberPointer: 7237 case Type::STK_FixedPoint: 7238 llvm_unreachable("illegal cast from pointer"); 7239 } 7240 llvm_unreachable("Should have returned before this"); 7241 7242 case Type::STK_FixedPoint: 7243 switch (DestTy->getScalarTypeKind()) { 7244 case Type::STK_FixedPoint: 7245 return CK_FixedPointCast; 7246 case Type::STK_Bool: 7247 return CK_FixedPointToBoolean; 7248 case Type::STK_Integral: 7249 return CK_FixedPointToIntegral; 7250 case Type::STK_Floating: 7251 return CK_FixedPointToFloating; 7252 case Type::STK_IntegralComplex: 7253 case Type::STK_FloatingComplex: 7254 Diag(Src.get()->getExprLoc(), 7255 diag::err_unimplemented_conversion_with_fixed_point_type) 7256 << DestTy; 7257 return CK_IntegralCast; 7258 case Type::STK_CPointer: 7259 case Type::STK_ObjCObjectPointer: 7260 case Type::STK_BlockPointer: 7261 case Type::STK_MemberPointer: 7262 llvm_unreachable("illegal cast to pointer type"); 7263 } 7264 llvm_unreachable("Should have returned before this"); 7265 7266 case Type::STK_Bool: // casting from bool is like casting from an integer 7267 case Type::STK_Integral: 7268 switch (DestTy->getScalarTypeKind()) { 7269 case Type::STK_CPointer: 7270 case Type::STK_ObjCObjectPointer: 7271 case Type::STK_BlockPointer: 7272 if (Src.get()->isNullPointerConstant(Context, 7273 Expr::NPC_ValueDependentIsNull)) 7274 return CK_NullToPointer; 7275 return CK_IntegralToPointer; 7276 case Type::STK_Bool: 7277 return CK_IntegralToBoolean; 7278 case Type::STK_Integral: 7279 return CK_IntegralCast; 7280 case Type::STK_Floating: 7281 return CK_IntegralToFloating; 7282 case Type::STK_IntegralComplex: 7283 Src = ImpCastExprToType(Src.get(), 7284 DestTy->castAs<ComplexType>()->getElementType(), 7285 CK_IntegralCast); 7286 return CK_IntegralRealToComplex; 7287 case Type::STK_FloatingComplex: 7288 Src = ImpCastExprToType(Src.get(), 7289 DestTy->castAs<ComplexType>()->getElementType(), 7290 CK_IntegralToFloating); 7291 return CK_FloatingRealToComplex; 7292 case Type::STK_MemberPointer: 7293 llvm_unreachable("member pointer type in C"); 7294 case Type::STK_FixedPoint: 7295 return CK_IntegralToFixedPoint; 7296 } 7297 llvm_unreachable("Should have returned before this"); 7298 7299 case Type::STK_Floating: 7300 switch (DestTy->getScalarTypeKind()) { 7301 case Type::STK_Floating: 7302 return CK_FloatingCast; 7303 case Type::STK_Bool: 7304 return CK_FloatingToBoolean; 7305 case Type::STK_Integral: 7306 return CK_FloatingToIntegral; 7307 case Type::STK_FloatingComplex: 7308 Src = ImpCastExprToType(Src.get(), 7309 DestTy->castAs<ComplexType>()->getElementType(), 7310 CK_FloatingCast); 7311 return CK_FloatingRealToComplex; 7312 case Type::STK_IntegralComplex: 7313 Src = ImpCastExprToType(Src.get(), 7314 DestTy->castAs<ComplexType>()->getElementType(), 7315 CK_FloatingToIntegral); 7316 return CK_IntegralRealToComplex; 7317 case Type::STK_CPointer: 7318 case Type::STK_ObjCObjectPointer: 7319 case Type::STK_BlockPointer: 7320 llvm_unreachable("valid float->pointer cast?"); 7321 case Type::STK_MemberPointer: 7322 llvm_unreachable("member pointer type in C"); 7323 case Type::STK_FixedPoint: 7324 return CK_FloatingToFixedPoint; 7325 } 7326 llvm_unreachable("Should have returned before this"); 7327 7328 case Type::STK_FloatingComplex: 7329 switch (DestTy->getScalarTypeKind()) { 7330 case Type::STK_FloatingComplex: 7331 return CK_FloatingComplexCast; 7332 case Type::STK_IntegralComplex: 7333 return CK_FloatingComplexToIntegralComplex; 7334 case Type::STK_Floating: { 7335 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7336 if (Context.hasSameType(ET, DestTy)) 7337 return CK_FloatingComplexToReal; 7338 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7339 return CK_FloatingCast; 7340 } 7341 case Type::STK_Bool: 7342 return CK_FloatingComplexToBoolean; 7343 case Type::STK_Integral: 7344 Src = ImpCastExprToType(Src.get(), 7345 SrcTy->castAs<ComplexType>()->getElementType(), 7346 CK_FloatingComplexToReal); 7347 return CK_FloatingToIntegral; 7348 case Type::STK_CPointer: 7349 case Type::STK_ObjCObjectPointer: 7350 case Type::STK_BlockPointer: 7351 llvm_unreachable("valid complex float->pointer cast?"); 7352 case Type::STK_MemberPointer: 7353 llvm_unreachable("member pointer type in C"); 7354 case Type::STK_FixedPoint: 7355 Diag(Src.get()->getExprLoc(), 7356 diag::err_unimplemented_conversion_with_fixed_point_type) 7357 << SrcTy; 7358 return CK_IntegralCast; 7359 } 7360 llvm_unreachable("Should have returned before this"); 7361 7362 case Type::STK_IntegralComplex: 7363 switch (DestTy->getScalarTypeKind()) { 7364 case Type::STK_FloatingComplex: 7365 return CK_IntegralComplexToFloatingComplex; 7366 case Type::STK_IntegralComplex: 7367 return CK_IntegralComplexCast; 7368 case Type::STK_Integral: { 7369 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7370 if (Context.hasSameType(ET, DestTy)) 7371 return CK_IntegralComplexToReal; 7372 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7373 return CK_IntegralCast; 7374 } 7375 case Type::STK_Bool: 7376 return CK_IntegralComplexToBoolean; 7377 case Type::STK_Floating: 7378 Src = ImpCastExprToType(Src.get(), 7379 SrcTy->castAs<ComplexType>()->getElementType(), 7380 CK_IntegralComplexToReal); 7381 return CK_IntegralToFloating; 7382 case Type::STK_CPointer: 7383 case Type::STK_ObjCObjectPointer: 7384 case Type::STK_BlockPointer: 7385 llvm_unreachable("valid complex int->pointer cast?"); 7386 case Type::STK_MemberPointer: 7387 llvm_unreachable("member pointer type in C"); 7388 case Type::STK_FixedPoint: 7389 Diag(Src.get()->getExprLoc(), 7390 diag::err_unimplemented_conversion_with_fixed_point_type) 7391 << SrcTy; 7392 return CK_IntegralCast; 7393 } 7394 llvm_unreachable("Should have returned before this"); 7395 } 7396 7397 llvm_unreachable("Unhandled scalar cast"); 7398 } 7399 7400 static bool breakDownVectorType(QualType type, uint64_t &len, 7401 QualType &eltType) { 7402 // Vectors are simple. 7403 if (const VectorType *vecType = type->getAs<VectorType>()) { 7404 len = vecType->getNumElements(); 7405 eltType = vecType->getElementType(); 7406 assert(eltType->isScalarType()); 7407 return true; 7408 } 7409 7410 // We allow lax conversion to and from non-vector types, but only if 7411 // they're real types (i.e. non-complex, non-pointer scalar types). 7412 if (!type->isRealType()) return false; 7413 7414 len = 1; 7415 eltType = type; 7416 return true; 7417 } 7418 7419 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7420 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7421 /// allowed? 7422 /// 7423 /// This will also return false if the two given types do not make sense from 7424 /// the perspective of SVE bitcasts. 7425 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7426 assert(srcTy->isVectorType() || destTy->isVectorType()); 7427 7428 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7429 if (!FirstType->isSizelessBuiltinType()) 7430 return false; 7431 7432 const auto *VecTy = SecondType->getAs<VectorType>(); 7433 return VecTy && 7434 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7435 }; 7436 7437 return ValidScalableConversion(srcTy, destTy) || 7438 ValidScalableConversion(destTy, srcTy); 7439 } 7440 7441 /// Are the two types matrix types and do they have the same dimensions i.e. 7442 /// do they have the same number of rows and the same number of columns? 7443 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7444 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7445 return false; 7446 7447 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7448 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7449 7450 return matSrcType->getNumRows() == matDestType->getNumRows() && 7451 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7452 } 7453 7454 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7455 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7456 7457 uint64_t SrcLen, DestLen; 7458 QualType SrcEltTy, DestEltTy; 7459 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7460 return false; 7461 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7462 return false; 7463 7464 // ASTContext::getTypeSize will return the size rounded up to a 7465 // power of 2, so instead of using that, we need to use the raw 7466 // element size multiplied by the element count. 7467 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7468 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7469 7470 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7471 } 7472 7473 /// Are the two types lax-compatible vector types? That is, given 7474 /// that one of them is a vector, do they have equal storage sizes, 7475 /// where the storage size is the number of elements times the element 7476 /// size? 7477 /// 7478 /// This will also return false if either of the types is neither a 7479 /// vector nor a real type. 7480 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7481 assert(destTy->isVectorType() || srcTy->isVectorType()); 7482 7483 // Disallow lax conversions between scalars and ExtVectors (these 7484 // conversions are allowed for other vector types because common headers 7485 // depend on them). Most scalar OP ExtVector cases are handled by the 7486 // splat path anyway, which does what we want (convert, not bitcast). 7487 // What this rules out for ExtVectors is crazy things like char4*float. 7488 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7489 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7490 7491 return areVectorTypesSameSize(srcTy, destTy); 7492 } 7493 7494 /// Is this a legal conversion between two types, one of which is 7495 /// known to be a vector type? 7496 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7497 assert(destTy->isVectorType() || srcTy->isVectorType()); 7498 7499 switch (Context.getLangOpts().getLaxVectorConversions()) { 7500 case LangOptions::LaxVectorConversionKind::None: 7501 return false; 7502 7503 case LangOptions::LaxVectorConversionKind::Integer: 7504 if (!srcTy->isIntegralOrEnumerationType()) { 7505 auto *Vec = srcTy->getAs<VectorType>(); 7506 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7507 return false; 7508 } 7509 if (!destTy->isIntegralOrEnumerationType()) { 7510 auto *Vec = destTy->getAs<VectorType>(); 7511 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7512 return false; 7513 } 7514 // OK, integer (vector) -> integer (vector) bitcast. 7515 break; 7516 7517 case LangOptions::LaxVectorConversionKind::All: 7518 break; 7519 } 7520 7521 return areLaxCompatibleVectorTypes(srcTy, destTy); 7522 } 7523 7524 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7525 CastKind &Kind) { 7526 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7527 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7528 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7529 << DestTy << SrcTy << R; 7530 } 7531 } else if (SrcTy->isMatrixType()) { 7532 return Diag(R.getBegin(), 7533 diag::err_invalid_conversion_between_matrix_and_type) 7534 << SrcTy << DestTy << R; 7535 } else if (DestTy->isMatrixType()) { 7536 return Diag(R.getBegin(), 7537 diag::err_invalid_conversion_between_matrix_and_type) 7538 << DestTy << SrcTy << R; 7539 } 7540 7541 Kind = CK_MatrixCast; 7542 return false; 7543 } 7544 7545 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7546 CastKind &Kind) { 7547 assert(VectorTy->isVectorType() && "Not a vector type!"); 7548 7549 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7550 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7551 return Diag(R.getBegin(), 7552 Ty->isVectorType() ? 7553 diag::err_invalid_conversion_between_vectors : 7554 diag::err_invalid_conversion_between_vector_and_integer) 7555 << VectorTy << Ty << R; 7556 } else 7557 return Diag(R.getBegin(), 7558 diag::err_invalid_conversion_between_vector_and_scalar) 7559 << VectorTy << Ty << R; 7560 7561 Kind = CK_BitCast; 7562 return false; 7563 } 7564 7565 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7566 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7567 7568 if (DestElemTy == SplattedExpr->getType()) 7569 return SplattedExpr; 7570 7571 assert(DestElemTy->isFloatingType() || 7572 DestElemTy->isIntegralOrEnumerationType()); 7573 7574 CastKind CK; 7575 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7576 // OpenCL requires that we convert `true` boolean expressions to -1, but 7577 // only when splatting vectors. 7578 if (DestElemTy->isFloatingType()) { 7579 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7580 // in two steps: boolean to signed integral, then to floating. 7581 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7582 CK_BooleanToSignedIntegral); 7583 SplattedExpr = CastExprRes.get(); 7584 CK = CK_IntegralToFloating; 7585 } else { 7586 CK = CK_BooleanToSignedIntegral; 7587 } 7588 } else { 7589 ExprResult CastExprRes = SplattedExpr; 7590 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7591 if (CastExprRes.isInvalid()) 7592 return ExprError(); 7593 SplattedExpr = CastExprRes.get(); 7594 } 7595 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7596 } 7597 7598 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7599 Expr *CastExpr, CastKind &Kind) { 7600 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7601 7602 QualType SrcTy = CastExpr->getType(); 7603 7604 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7605 // an ExtVectorType. 7606 // In OpenCL, casts between vectors of different types are not allowed. 7607 // (See OpenCL 6.2). 7608 if (SrcTy->isVectorType()) { 7609 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7610 (getLangOpts().OpenCL && 7611 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7612 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7613 << DestTy << SrcTy << R; 7614 return ExprError(); 7615 } 7616 Kind = CK_BitCast; 7617 return CastExpr; 7618 } 7619 7620 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7621 // conversion will take place first from scalar to elt type, and then 7622 // splat from elt type to vector. 7623 if (SrcTy->isPointerType()) 7624 return Diag(R.getBegin(), 7625 diag::err_invalid_conversion_between_vector_and_scalar) 7626 << DestTy << SrcTy << R; 7627 7628 Kind = CK_VectorSplat; 7629 return prepareVectorSplat(DestTy, CastExpr); 7630 } 7631 7632 ExprResult 7633 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7634 Declarator &D, ParsedType &Ty, 7635 SourceLocation RParenLoc, Expr *CastExpr) { 7636 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7637 "ActOnCastExpr(): missing type or expr"); 7638 7639 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7640 if (D.isInvalidType()) 7641 return ExprError(); 7642 7643 if (getLangOpts().CPlusPlus) { 7644 // Check that there are no default arguments (C++ only). 7645 CheckExtraCXXDefaultArguments(D); 7646 } else { 7647 // Make sure any TypoExprs have been dealt with. 7648 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7649 if (!Res.isUsable()) 7650 return ExprError(); 7651 CastExpr = Res.get(); 7652 } 7653 7654 checkUnusedDeclAttributes(D); 7655 7656 QualType castType = castTInfo->getType(); 7657 Ty = CreateParsedType(castType, castTInfo); 7658 7659 bool isVectorLiteral = false; 7660 7661 // Check for an altivec or OpenCL literal, 7662 // i.e. all the elements are integer constants. 7663 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7664 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7665 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7666 && castType->isVectorType() && (PE || PLE)) { 7667 if (PLE && PLE->getNumExprs() == 0) { 7668 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7669 return ExprError(); 7670 } 7671 if (PE || PLE->getNumExprs() == 1) { 7672 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7673 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7674 isVectorLiteral = true; 7675 } 7676 else 7677 isVectorLiteral = true; 7678 } 7679 7680 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7681 // then handle it as such. 7682 if (isVectorLiteral) 7683 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7684 7685 // If the Expr being casted is a ParenListExpr, handle it specially. 7686 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7687 // sequence of BinOp comma operators. 7688 if (isa<ParenListExpr>(CastExpr)) { 7689 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7690 if (Result.isInvalid()) return ExprError(); 7691 CastExpr = Result.get(); 7692 } 7693 7694 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7695 !getSourceManager().isInSystemMacro(LParenLoc)) 7696 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7697 7698 CheckTollFreeBridgeCast(castType, CastExpr); 7699 7700 CheckObjCBridgeRelatedCast(castType, CastExpr); 7701 7702 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7703 7704 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7705 } 7706 7707 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7708 SourceLocation RParenLoc, Expr *E, 7709 TypeSourceInfo *TInfo) { 7710 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7711 "Expected paren or paren list expression"); 7712 7713 Expr **exprs; 7714 unsigned numExprs; 7715 Expr *subExpr; 7716 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7717 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7718 LiteralLParenLoc = PE->getLParenLoc(); 7719 LiteralRParenLoc = PE->getRParenLoc(); 7720 exprs = PE->getExprs(); 7721 numExprs = PE->getNumExprs(); 7722 } else { // isa<ParenExpr> by assertion at function entrance 7723 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7724 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7725 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7726 exprs = &subExpr; 7727 numExprs = 1; 7728 } 7729 7730 QualType Ty = TInfo->getType(); 7731 assert(Ty->isVectorType() && "Expected vector type"); 7732 7733 SmallVector<Expr *, 8> initExprs; 7734 const VectorType *VTy = Ty->castAs<VectorType>(); 7735 unsigned numElems = VTy->getNumElements(); 7736 7737 // '(...)' form of vector initialization in AltiVec: the number of 7738 // initializers must be one or must match the size of the vector. 7739 // If a single value is specified in the initializer then it will be 7740 // replicated to all the components of the vector 7741 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, 7742 VTy->getElementType())) 7743 return ExprError(); 7744 if (ShouldSplatAltivecScalarInCast(VTy)) { 7745 // The number of initializers must be one or must match the size of the 7746 // vector. If a single value is specified in the initializer then it will 7747 // be replicated to all the components of the vector 7748 if (numExprs == 1) { 7749 QualType ElemTy = VTy->getElementType(); 7750 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7751 if (Literal.isInvalid()) 7752 return ExprError(); 7753 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7754 PrepareScalarCast(Literal, ElemTy)); 7755 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7756 } 7757 else if (numExprs < numElems) { 7758 Diag(E->getExprLoc(), 7759 diag::err_incorrect_number_of_vector_initializers); 7760 return ExprError(); 7761 } 7762 else 7763 initExprs.append(exprs, exprs + numExprs); 7764 } 7765 else { 7766 // For OpenCL, when the number of initializers is a single value, 7767 // it will be replicated to all components of the vector. 7768 if (getLangOpts().OpenCL && 7769 VTy->getVectorKind() == VectorType::GenericVector && 7770 numExprs == 1) { 7771 QualType ElemTy = VTy->getElementType(); 7772 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7773 if (Literal.isInvalid()) 7774 return ExprError(); 7775 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7776 PrepareScalarCast(Literal, ElemTy)); 7777 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7778 } 7779 7780 initExprs.append(exprs, exprs + numExprs); 7781 } 7782 // FIXME: This means that pretty-printing the final AST will produce curly 7783 // braces instead of the original commas. 7784 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7785 initExprs, LiteralRParenLoc); 7786 initE->setType(Ty); 7787 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7788 } 7789 7790 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7791 /// the ParenListExpr into a sequence of comma binary operators. 7792 ExprResult 7793 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7794 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7795 if (!E) 7796 return OrigExpr; 7797 7798 ExprResult Result(E->getExpr(0)); 7799 7800 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7801 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7802 E->getExpr(i)); 7803 7804 if (Result.isInvalid()) return ExprError(); 7805 7806 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7807 } 7808 7809 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7810 SourceLocation R, 7811 MultiExprArg Val) { 7812 return ParenListExpr::Create(Context, L, Val, R); 7813 } 7814 7815 /// Emit a specialized diagnostic when one expression is a null pointer 7816 /// constant and the other is not a pointer. Returns true if a diagnostic is 7817 /// emitted. 7818 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7819 SourceLocation QuestionLoc) { 7820 Expr *NullExpr = LHSExpr; 7821 Expr *NonPointerExpr = RHSExpr; 7822 Expr::NullPointerConstantKind NullKind = 7823 NullExpr->isNullPointerConstant(Context, 7824 Expr::NPC_ValueDependentIsNotNull); 7825 7826 if (NullKind == Expr::NPCK_NotNull) { 7827 NullExpr = RHSExpr; 7828 NonPointerExpr = LHSExpr; 7829 NullKind = 7830 NullExpr->isNullPointerConstant(Context, 7831 Expr::NPC_ValueDependentIsNotNull); 7832 } 7833 7834 if (NullKind == Expr::NPCK_NotNull) 7835 return false; 7836 7837 if (NullKind == Expr::NPCK_ZeroExpression) 7838 return false; 7839 7840 if (NullKind == Expr::NPCK_ZeroLiteral) { 7841 // In this case, check to make sure that we got here from a "NULL" 7842 // string in the source code. 7843 NullExpr = NullExpr->IgnoreParenImpCasts(); 7844 SourceLocation loc = NullExpr->getExprLoc(); 7845 if (!findMacroSpelling(loc, "NULL")) 7846 return false; 7847 } 7848 7849 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7850 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7851 << NonPointerExpr->getType() << DiagType 7852 << NonPointerExpr->getSourceRange(); 7853 return true; 7854 } 7855 7856 /// Return false if the condition expression is valid, true otherwise. 7857 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7858 QualType CondTy = Cond->getType(); 7859 7860 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7861 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7862 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7863 << CondTy << Cond->getSourceRange(); 7864 return true; 7865 } 7866 7867 // C99 6.5.15p2 7868 if (CondTy->isScalarType()) return false; 7869 7870 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7871 << CondTy << Cond->getSourceRange(); 7872 return true; 7873 } 7874 7875 /// Handle when one or both operands are void type. 7876 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7877 ExprResult &RHS) { 7878 Expr *LHSExpr = LHS.get(); 7879 Expr *RHSExpr = RHS.get(); 7880 7881 if (!LHSExpr->getType()->isVoidType()) 7882 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7883 << RHSExpr->getSourceRange(); 7884 if (!RHSExpr->getType()->isVoidType()) 7885 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7886 << LHSExpr->getSourceRange(); 7887 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7888 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7889 return S.Context.VoidTy; 7890 } 7891 7892 /// Return false if the NullExpr can be promoted to PointerTy, 7893 /// true otherwise. 7894 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7895 QualType PointerTy) { 7896 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7897 !NullExpr.get()->isNullPointerConstant(S.Context, 7898 Expr::NPC_ValueDependentIsNull)) 7899 return true; 7900 7901 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7902 return false; 7903 } 7904 7905 /// Checks compatibility between two pointers and return the resulting 7906 /// type. 7907 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7908 ExprResult &RHS, 7909 SourceLocation Loc) { 7910 QualType LHSTy = LHS.get()->getType(); 7911 QualType RHSTy = RHS.get()->getType(); 7912 7913 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7914 // Two identical pointers types are always compatible. 7915 return LHSTy; 7916 } 7917 7918 QualType lhptee, rhptee; 7919 7920 // Get the pointee types. 7921 bool IsBlockPointer = false; 7922 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7923 lhptee = LHSBTy->getPointeeType(); 7924 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7925 IsBlockPointer = true; 7926 } else { 7927 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7928 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7929 } 7930 7931 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7932 // differently qualified versions of compatible types, the result type is 7933 // a pointer to an appropriately qualified version of the composite 7934 // type. 7935 7936 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7937 // clause doesn't make sense for our extensions. E.g. address space 2 should 7938 // be incompatible with address space 3: they may live on different devices or 7939 // anything. 7940 Qualifiers lhQual = lhptee.getQualifiers(); 7941 Qualifiers rhQual = rhptee.getQualifiers(); 7942 7943 LangAS ResultAddrSpace = LangAS::Default; 7944 LangAS LAddrSpace = lhQual.getAddressSpace(); 7945 LangAS RAddrSpace = rhQual.getAddressSpace(); 7946 7947 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7948 // spaces is disallowed. 7949 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7950 ResultAddrSpace = LAddrSpace; 7951 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7952 ResultAddrSpace = RAddrSpace; 7953 else { 7954 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7955 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7956 << RHS.get()->getSourceRange(); 7957 return QualType(); 7958 } 7959 7960 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7961 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7962 lhQual.removeCVRQualifiers(); 7963 rhQual.removeCVRQualifiers(); 7964 7965 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7966 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7967 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7968 // qual types are compatible iff 7969 // * corresponded types are compatible 7970 // * CVR qualifiers are equal 7971 // * address spaces are equal 7972 // Thus for conditional operator we merge CVR and address space unqualified 7973 // pointees and if there is a composite type we return a pointer to it with 7974 // merged qualifiers. 7975 LHSCastKind = 7976 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7977 RHSCastKind = 7978 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7979 lhQual.removeAddressSpace(); 7980 rhQual.removeAddressSpace(); 7981 7982 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7983 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7984 7985 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7986 7987 if (CompositeTy.isNull()) { 7988 // In this situation, we assume void* type. No especially good 7989 // reason, but this is what gcc does, and we do have to pick 7990 // to get a consistent AST. 7991 QualType incompatTy; 7992 incompatTy = S.Context.getPointerType( 7993 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7994 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7995 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7996 7997 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7998 // for casts between types with incompatible address space qualifiers. 7999 // For the following code the compiler produces casts between global and 8000 // local address spaces of the corresponded innermost pointees: 8001 // local int *global *a; 8002 // global int *global *b; 8003 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 8004 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 8005 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8006 << RHS.get()->getSourceRange(); 8007 8008 return incompatTy; 8009 } 8010 8011 // The pointer types are compatible. 8012 // In case of OpenCL ResultTy should have the address space qualifier 8013 // which is a superset of address spaces of both the 2nd and the 3rd 8014 // operands of the conditional operator. 8015 QualType ResultTy = [&, ResultAddrSpace]() { 8016 if (S.getLangOpts().OpenCL) { 8017 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 8018 CompositeQuals.setAddressSpace(ResultAddrSpace); 8019 return S.Context 8020 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 8021 .withCVRQualifiers(MergedCVRQual); 8022 } 8023 return CompositeTy.withCVRQualifiers(MergedCVRQual); 8024 }(); 8025 if (IsBlockPointer) 8026 ResultTy = S.Context.getBlockPointerType(ResultTy); 8027 else 8028 ResultTy = S.Context.getPointerType(ResultTy); 8029 8030 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 8031 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 8032 return ResultTy; 8033 } 8034 8035 /// Return the resulting type when the operands are both block pointers. 8036 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 8037 ExprResult &LHS, 8038 ExprResult &RHS, 8039 SourceLocation Loc) { 8040 QualType LHSTy = LHS.get()->getType(); 8041 QualType RHSTy = RHS.get()->getType(); 8042 8043 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 8044 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 8045 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 8046 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8047 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8048 return destType; 8049 } 8050 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 8051 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8052 << RHS.get()->getSourceRange(); 8053 return QualType(); 8054 } 8055 8056 // We have 2 block pointer types. 8057 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8058 } 8059 8060 /// Return the resulting type when the operands are both pointers. 8061 static QualType 8062 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8063 ExprResult &RHS, 8064 SourceLocation Loc) { 8065 // get the pointer types 8066 QualType LHSTy = LHS.get()->getType(); 8067 QualType RHSTy = RHS.get()->getType(); 8068 8069 // get the "pointed to" types 8070 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8071 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8072 8073 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8074 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8075 // Figure out necessary qualifiers (C99 6.5.15p6) 8076 QualType destPointee 8077 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8078 QualType destType = S.Context.getPointerType(destPointee); 8079 // Add qualifiers if necessary. 8080 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8081 // Promote to void*. 8082 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8083 return destType; 8084 } 8085 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8086 QualType destPointee 8087 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8088 QualType destType = S.Context.getPointerType(destPointee); 8089 // Add qualifiers if necessary. 8090 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8091 // Promote to void*. 8092 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8093 return destType; 8094 } 8095 8096 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8097 } 8098 8099 /// Return false if the first expression is not an integer and the second 8100 /// expression is not a pointer, true otherwise. 8101 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8102 Expr* PointerExpr, SourceLocation Loc, 8103 bool IsIntFirstExpr) { 8104 if (!PointerExpr->getType()->isPointerType() || 8105 !Int.get()->getType()->isIntegerType()) 8106 return false; 8107 8108 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8109 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8110 8111 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8112 << Expr1->getType() << Expr2->getType() 8113 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8114 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8115 CK_IntegralToPointer); 8116 return true; 8117 } 8118 8119 /// Simple conversion between integer and floating point types. 8120 /// 8121 /// Used when handling the OpenCL conditional operator where the 8122 /// condition is a vector while the other operands are scalar. 8123 /// 8124 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8125 /// types are either integer or floating type. Between the two 8126 /// operands, the type with the higher rank is defined as the "result 8127 /// type". The other operand needs to be promoted to the same type. No 8128 /// other type promotion is allowed. We cannot use 8129 /// UsualArithmeticConversions() for this purpose, since it always 8130 /// promotes promotable types. 8131 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8132 ExprResult &RHS, 8133 SourceLocation QuestionLoc) { 8134 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8135 if (LHS.isInvalid()) 8136 return QualType(); 8137 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8138 if (RHS.isInvalid()) 8139 return QualType(); 8140 8141 // For conversion purposes, we ignore any qualifiers. 8142 // For example, "const float" and "float" are equivalent. 8143 QualType LHSType = 8144 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8145 QualType RHSType = 8146 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8147 8148 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8149 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8150 << LHSType << LHS.get()->getSourceRange(); 8151 return QualType(); 8152 } 8153 8154 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8155 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8156 << RHSType << RHS.get()->getSourceRange(); 8157 return QualType(); 8158 } 8159 8160 // If both types are identical, no conversion is needed. 8161 if (LHSType == RHSType) 8162 return LHSType; 8163 8164 // Now handle "real" floating types (i.e. float, double, long double). 8165 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8166 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8167 /*IsCompAssign = */ false); 8168 8169 // Finally, we have two differing integer types. 8170 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8171 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8172 } 8173 8174 /// Convert scalar operands to a vector that matches the 8175 /// condition in length. 8176 /// 8177 /// Used when handling the OpenCL conditional operator where the 8178 /// condition is a vector while the other operands are scalar. 8179 /// 8180 /// We first compute the "result type" for the scalar operands 8181 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8182 /// into a vector of that type where the length matches the condition 8183 /// vector type. s6.11.6 requires that the element types of the result 8184 /// and the condition must have the same number of bits. 8185 static QualType 8186 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8187 QualType CondTy, SourceLocation QuestionLoc) { 8188 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8189 if (ResTy.isNull()) return QualType(); 8190 8191 const VectorType *CV = CondTy->getAs<VectorType>(); 8192 assert(CV); 8193 8194 // Determine the vector result type 8195 unsigned NumElements = CV->getNumElements(); 8196 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8197 8198 // Ensure that all types have the same number of bits 8199 if (S.Context.getTypeSize(CV->getElementType()) 8200 != S.Context.getTypeSize(ResTy)) { 8201 // Since VectorTy is created internally, it does not pretty print 8202 // with an OpenCL name. Instead, we just print a description. 8203 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8204 SmallString<64> Str; 8205 llvm::raw_svector_ostream OS(Str); 8206 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8207 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8208 << CondTy << OS.str(); 8209 return QualType(); 8210 } 8211 8212 // Convert operands to the vector result type 8213 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8214 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8215 8216 return VectorTy; 8217 } 8218 8219 /// Return false if this is a valid OpenCL condition vector 8220 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8221 SourceLocation QuestionLoc) { 8222 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8223 // integral type. 8224 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8225 assert(CondTy); 8226 QualType EleTy = CondTy->getElementType(); 8227 if (EleTy->isIntegerType()) return false; 8228 8229 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8230 << Cond->getType() << Cond->getSourceRange(); 8231 return true; 8232 } 8233 8234 /// Return false if the vector condition type and the vector 8235 /// result type are compatible. 8236 /// 8237 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8238 /// number of elements, and their element types have the same number 8239 /// of bits. 8240 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8241 SourceLocation QuestionLoc) { 8242 const VectorType *CV = CondTy->getAs<VectorType>(); 8243 const VectorType *RV = VecResTy->getAs<VectorType>(); 8244 assert(CV && RV); 8245 8246 if (CV->getNumElements() != RV->getNumElements()) { 8247 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8248 << CondTy << VecResTy; 8249 return true; 8250 } 8251 8252 QualType CVE = CV->getElementType(); 8253 QualType RVE = RV->getElementType(); 8254 8255 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8256 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8257 << CondTy << VecResTy; 8258 return true; 8259 } 8260 8261 return false; 8262 } 8263 8264 /// Return the resulting type for the conditional operator in 8265 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8266 /// s6.3.i) when the condition is a vector type. 8267 static QualType 8268 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8269 ExprResult &LHS, ExprResult &RHS, 8270 SourceLocation QuestionLoc) { 8271 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8272 if (Cond.isInvalid()) 8273 return QualType(); 8274 QualType CondTy = Cond.get()->getType(); 8275 8276 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8277 return QualType(); 8278 8279 // If either operand is a vector then find the vector type of the 8280 // result as specified in OpenCL v1.1 s6.3.i. 8281 if (LHS.get()->getType()->isVectorType() || 8282 RHS.get()->getType()->isVectorType()) { 8283 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8284 /*isCompAssign*/false, 8285 /*AllowBothBool*/true, 8286 /*AllowBoolConversions*/false); 8287 if (VecResTy.isNull()) return QualType(); 8288 // The result type must match the condition type as specified in 8289 // OpenCL v1.1 s6.11.6. 8290 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8291 return QualType(); 8292 return VecResTy; 8293 } 8294 8295 // Both operands are scalar. 8296 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8297 } 8298 8299 /// Return true if the Expr is block type 8300 static bool checkBlockType(Sema &S, const Expr *E) { 8301 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8302 QualType Ty = CE->getCallee()->getType(); 8303 if (Ty->isBlockPointerType()) { 8304 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8305 return true; 8306 } 8307 } 8308 return false; 8309 } 8310 8311 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8312 /// In that case, LHS = cond. 8313 /// C99 6.5.15 8314 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8315 ExprResult &RHS, ExprValueKind &VK, 8316 ExprObjectKind &OK, 8317 SourceLocation QuestionLoc) { 8318 8319 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8320 if (!LHSResult.isUsable()) return QualType(); 8321 LHS = LHSResult; 8322 8323 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8324 if (!RHSResult.isUsable()) return QualType(); 8325 RHS = RHSResult; 8326 8327 // C++ is sufficiently different to merit its own checker. 8328 if (getLangOpts().CPlusPlus) 8329 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8330 8331 VK = VK_PRValue; 8332 OK = OK_Ordinary; 8333 8334 if (Context.isDependenceAllowed() && 8335 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8336 RHS.get()->isTypeDependent())) { 8337 assert(!getLangOpts().CPlusPlus); 8338 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8339 RHS.get()->containsErrors()) && 8340 "should only occur in error-recovery path."); 8341 return Context.DependentTy; 8342 } 8343 8344 // The OpenCL operator with a vector condition is sufficiently 8345 // different to merit its own checker. 8346 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8347 Cond.get()->getType()->isExtVectorType()) 8348 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8349 8350 // First, check the condition. 8351 Cond = UsualUnaryConversions(Cond.get()); 8352 if (Cond.isInvalid()) 8353 return QualType(); 8354 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8355 return QualType(); 8356 8357 // Now check the two expressions. 8358 if (LHS.get()->getType()->isVectorType() || 8359 RHS.get()->getType()->isVectorType()) 8360 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8361 /*AllowBothBool*/true, 8362 /*AllowBoolConversions*/false); 8363 8364 QualType ResTy = 8365 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8366 if (LHS.isInvalid() || RHS.isInvalid()) 8367 return QualType(); 8368 8369 QualType LHSTy = LHS.get()->getType(); 8370 QualType RHSTy = RHS.get()->getType(); 8371 8372 // Diagnose attempts to convert between __ibm128, __float128 and long double 8373 // where such conversions currently can't be handled. 8374 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8375 Diag(QuestionLoc, 8376 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8377 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8378 return QualType(); 8379 } 8380 8381 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8382 // selection operator (?:). 8383 if (getLangOpts().OpenCL && 8384 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) { 8385 return QualType(); 8386 } 8387 8388 // If both operands have arithmetic type, do the usual arithmetic conversions 8389 // to find a common type: C99 6.5.15p3,5. 8390 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8391 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8392 // different sizes, or between ExtInts and other types. 8393 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8394 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8395 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8396 << RHS.get()->getSourceRange(); 8397 return QualType(); 8398 } 8399 8400 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8401 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8402 8403 return ResTy; 8404 } 8405 8406 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8407 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8408 return LHSTy; 8409 } 8410 8411 // If both operands are the same structure or union type, the result is that 8412 // type. 8413 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8414 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8415 if (LHSRT->getDecl() == RHSRT->getDecl()) 8416 // "If both the operands have structure or union type, the result has 8417 // that type." This implies that CV qualifiers are dropped. 8418 return LHSTy.getUnqualifiedType(); 8419 // FIXME: Type of conditional expression must be complete in C mode. 8420 } 8421 8422 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8423 // The following || allows only one side to be void (a GCC-ism). 8424 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8425 return checkConditionalVoidType(*this, LHS, RHS); 8426 } 8427 8428 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8429 // the type of the other operand." 8430 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8431 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8432 8433 // All objective-c pointer type analysis is done here. 8434 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8435 QuestionLoc); 8436 if (LHS.isInvalid() || RHS.isInvalid()) 8437 return QualType(); 8438 if (!compositeType.isNull()) 8439 return compositeType; 8440 8441 8442 // Handle block pointer types. 8443 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8444 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8445 QuestionLoc); 8446 8447 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8448 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8449 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8450 QuestionLoc); 8451 8452 // GCC compatibility: soften pointer/integer mismatch. Note that 8453 // null pointers have been filtered out by this point. 8454 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8455 /*IsIntFirstExpr=*/true)) 8456 return RHSTy; 8457 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8458 /*IsIntFirstExpr=*/false)) 8459 return LHSTy; 8460 8461 // Allow ?: operations in which both operands have the same 8462 // built-in sizeless type. 8463 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) 8464 return LHSTy; 8465 8466 // Emit a better diagnostic if one of the expressions is a null pointer 8467 // constant and the other is not a pointer type. In this case, the user most 8468 // likely forgot to take the address of the other expression. 8469 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8470 return QualType(); 8471 8472 // Otherwise, the operands are not compatible. 8473 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8474 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8475 << RHS.get()->getSourceRange(); 8476 return QualType(); 8477 } 8478 8479 /// FindCompositeObjCPointerType - Helper method to find composite type of 8480 /// two objective-c pointer types of the two input expressions. 8481 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8482 SourceLocation QuestionLoc) { 8483 QualType LHSTy = LHS.get()->getType(); 8484 QualType RHSTy = RHS.get()->getType(); 8485 8486 // Handle things like Class and struct objc_class*. Here we case the result 8487 // to the pseudo-builtin, because that will be implicitly cast back to the 8488 // redefinition type if an attempt is made to access its fields. 8489 if (LHSTy->isObjCClassType() && 8490 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8491 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8492 return LHSTy; 8493 } 8494 if (RHSTy->isObjCClassType() && 8495 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8496 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8497 return RHSTy; 8498 } 8499 // And the same for struct objc_object* / id 8500 if (LHSTy->isObjCIdType() && 8501 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8502 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8503 return LHSTy; 8504 } 8505 if (RHSTy->isObjCIdType() && 8506 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8507 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8508 return RHSTy; 8509 } 8510 // And the same for struct objc_selector* / SEL 8511 if (Context.isObjCSelType(LHSTy) && 8512 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8513 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8514 return LHSTy; 8515 } 8516 if (Context.isObjCSelType(RHSTy) && 8517 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8518 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8519 return RHSTy; 8520 } 8521 // Check constraints for Objective-C object pointers types. 8522 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8523 8524 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8525 // Two identical object pointer types are always compatible. 8526 return LHSTy; 8527 } 8528 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8529 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8530 QualType compositeType = LHSTy; 8531 8532 // If both operands are interfaces and either operand can be 8533 // assigned to the other, use that type as the composite 8534 // type. This allows 8535 // xxx ? (A*) a : (B*) b 8536 // where B is a subclass of A. 8537 // 8538 // Additionally, as for assignment, if either type is 'id' 8539 // allow silent coercion. Finally, if the types are 8540 // incompatible then make sure to use 'id' as the composite 8541 // type so the result is acceptable for sending messages to. 8542 8543 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8544 // It could return the composite type. 8545 if (!(compositeType = 8546 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8547 // Nothing more to do. 8548 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8549 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8550 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8551 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8552 } else if ((LHSOPT->isObjCQualifiedIdType() || 8553 RHSOPT->isObjCQualifiedIdType()) && 8554 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8555 true)) { 8556 // Need to handle "id<xx>" explicitly. 8557 // GCC allows qualified id and any Objective-C type to devolve to 8558 // id. Currently localizing to here until clear this should be 8559 // part of ObjCQualifiedIdTypesAreCompatible. 8560 compositeType = Context.getObjCIdType(); 8561 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8562 compositeType = Context.getObjCIdType(); 8563 } else { 8564 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8565 << LHSTy << RHSTy 8566 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8567 QualType incompatTy = Context.getObjCIdType(); 8568 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8569 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8570 return incompatTy; 8571 } 8572 // The object pointer types are compatible. 8573 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8574 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8575 return compositeType; 8576 } 8577 // Check Objective-C object pointer types and 'void *' 8578 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8579 if (getLangOpts().ObjCAutoRefCount) { 8580 // ARC forbids the implicit conversion of object pointers to 'void *', 8581 // so these types are not compatible. 8582 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8583 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8584 LHS = RHS = true; 8585 return QualType(); 8586 } 8587 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8588 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8589 QualType destPointee 8590 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8591 QualType destType = Context.getPointerType(destPointee); 8592 // Add qualifiers if necessary. 8593 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8594 // Promote to void*. 8595 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8596 return destType; 8597 } 8598 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8599 if (getLangOpts().ObjCAutoRefCount) { 8600 // ARC forbids the implicit conversion of object pointers to 'void *', 8601 // so these types are not compatible. 8602 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8603 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8604 LHS = RHS = true; 8605 return QualType(); 8606 } 8607 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8608 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8609 QualType destPointee 8610 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8611 QualType destType = Context.getPointerType(destPointee); 8612 // Add qualifiers if necessary. 8613 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8614 // Promote to void*. 8615 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8616 return destType; 8617 } 8618 return QualType(); 8619 } 8620 8621 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8622 /// ParenRange in parentheses. 8623 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8624 const PartialDiagnostic &Note, 8625 SourceRange ParenRange) { 8626 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8627 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8628 EndLoc.isValid()) { 8629 Self.Diag(Loc, Note) 8630 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8631 << FixItHint::CreateInsertion(EndLoc, ")"); 8632 } else { 8633 // We can't display the parentheses, so just show the bare note. 8634 Self.Diag(Loc, Note) << ParenRange; 8635 } 8636 } 8637 8638 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8639 return BinaryOperator::isAdditiveOp(Opc) || 8640 BinaryOperator::isMultiplicativeOp(Opc) || 8641 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8642 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8643 // not any of the logical operators. Bitwise-xor is commonly used as a 8644 // logical-xor because there is no logical-xor operator. The logical 8645 // operators, including uses of xor, have a high false positive rate for 8646 // precedence warnings. 8647 } 8648 8649 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8650 /// expression, either using a built-in or overloaded operator, 8651 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8652 /// expression. 8653 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8654 Expr **RHSExprs) { 8655 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8656 E = E->IgnoreImpCasts(); 8657 E = E->IgnoreConversionOperatorSingleStep(); 8658 E = E->IgnoreImpCasts(); 8659 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8660 E = MTE->getSubExpr(); 8661 E = E->IgnoreImpCasts(); 8662 } 8663 8664 // Built-in binary operator. 8665 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8666 if (IsArithmeticOp(OP->getOpcode())) { 8667 *Opcode = OP->getOpcode(); 8668 *RHSExprs = OP->getRHS(); 8669 return true; 8670 } 8671 } 8672 8673 // Overloaded operator. 8674 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8675 if (Call->getNumArgs() != 2) 8676 return false; 8677 8678 // Make sure this is really a binary operator that is safe to pass into 8679 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8680 OverloadedOperatorKind OO = Call->getOperator(); 8681 if (OO < OO_Plus || OO > OO_Arrow || 8682 OO == OO_PlusPlus || OO == OO_MinusMinus) 8683 return false; 8684 8685 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8686 if (IsArithmeticOp(OpKind)) { 8687 *Opcode = OpKind; 8688 *RHSExprs = Call->getArg(1); 8689 return true; 8690 } 8691 } 8692 8693 return false; 8694 } 8695 8696 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8697 /// or is a logical expression such as (x==y) which has int type, but is 8698 /// commonly interpreted as boolean. 8699 static bool ExprLooksBoolean(Expr *E) { 8700 E = E->IgnoreParenImpCasts(); 8701 8702 if (E->getType()->isBooleanType()) 8703 return true; 8704 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8705 return OP->isComparisonOp() || OP->isLogicalOp(); 8706 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8707 return OP->getOpcode() == UO_LNot; 8708 if (E->getType()->isPointerType()) 8709 return true; 8710 // FIXME: What about overloaded operator calls returning "unspecified boolean 8711 // type"s (commonly pointer-to-members)? 8712 8713 return false; 8714 } 8715 8716 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8717 /// and binary operator are mixed in a way that suggests the programmer assumed 8718 /// the conditional operator has higher precedence, for example: 8719 /// "int x = a + someBinaryCondition ? 1 : 2". 8720 static void DiagnoseConditionalPrecedence(Sema &Self, 8721 SourceLocation OpLoc, 8722 Expr *Condition, 8723 Expr *LHSExpr, 8724 Expr *RHSExpr) { 8725 BinaryOperatorKind CondOpcode; 8726 Expr *CondRHS; 8727 8728 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8729 return; 8730 if (!ExprLooksBoolean(CondRHS)) 8731 return; 8732 8733 // The condition is an arithmetic binary expression, with a right- 8734 // hand side that looks boolean, so warn. 8735 8736 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8737 ? diag::warn_precedence_bitwise_conditional 8738 : diag::warn_precedence_conditional; 8739 8740 Self.Diag(OpLoc, DiagID) 8741 << Condition->getSourceRange() 8742 << BinaryOperator::getOpcodeStr(CondOpcode); 8743 8744 SuggestParentheses( 8745 Self, OpLoc, 8746 Self.PDiag(diag::note_precedence_silence) 8747 << BinaryOperator::getOpcodeStr(CondOpcode), 8748 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8749 8750 SuggestParentheses(Self, OpLoc, 8751 Self.PDiag(diag::note_precedence_conditional_first), 8752 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8753 } 8754 8755 /// Compute the nullability of a conditional expression. 8756 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8757 QualType LHSTy, QualType RHSTy, 8758 ASTContext &Ctx) { 8759 if (!ResTy->isAnyPointerType()) 8760 return ResTy; 8761 8762 auto GetNullability = [&Ctx](QualType Ty) { 8763 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8764 if (Kind) { 8765 // For our purposes, treat _Nullable_result as _Nullable. 8766 if (*Kind == NullabilityKind::NullableResult) 8767 return NullabilityKind::Nullable; 8768 return *Kind; 8769 } 8770 return NullabilityKind::Unspecified; 8771 }; 8772 8773 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8774 NullabilityKind MergedKind; 8775 8776 // Compute nullability of a binary conditional expression. 8777 if (IsBin) { 8778 if (LHSKind == NullabilityKind::NonNull) 8779 MergedKind = NullabilityKind::NonNull; 8780 else 8781 MergedKind = RHSKind; 8782 // Compute nullability of a normal conditional expression. 8783 } else { 8784 if (LHSKind == NullabilityKind::Nullable || 8785 RHSKind == NullabilityKind::Nullable) 8786 MergedKind = NullabilityKind::Nullable; 8787 else if (LHSKind == NullabilityKind::NonNull) 8788 MergedKind = RHSKind; 8789 else if (RHSKind == NullabilityKind::NonNull) 8790 MergedKind = LHSKind; 8791 else 8792 MergedKind = NullabilityKind::Unspecified; 8793 } 8794 8795 // Return if ResTy already has the correct nullability. 8796 if (GetNullability(ResTy) == MergedKind) 8797 return ResTy; 8798 8799 // Strip all nullability from ResTy. 8800 while (ResTy->getNullability(Ctx)) 8801 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8802 8803 // Create a new AttributedType with the new nullability kind. 8804 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8805 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8806 } 8807 8808 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8809 /// in the case of a the GNU conditional expr extension. 8810 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8811 SourceLocation ColonLoc, 8812 Expr *CondExpr, Expr *LHSExpr, 8813 Expr *RHSExpr) { 8814 if (!Context.isDependenceAllowed()) { 8815 // C cannot handle TypoExpr nodes in the condition because it 8816 // doesn't handle dependent types properly, so make sure any TypoExprs have 8817 // been dealt with before checking the operands. 8818 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8819 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8820 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8821 8822 if (!CondResult.isUsable()) 8823 return ExprError(); 8824 8825 if (LHSExpr) { 8826 if (!LHSResult.isUsable()) 8827 return ExprError(); 8828 } 8829 8830 if (!RHSResult.isUsable()) 8831 return ExprError(); 8832 8833 CondExpr = CondResult.get(); 8834 LHSExpr = LHSResult.get(); 8835 RHSExpr = RHSResult.get(); 8836 } 8837 8838 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8839 // was the condition. 8840 OpaqueValueExpr *opaqueValue = nullptr; 8841 Expr *commonExpr = nullptr; 8842 if (!LHSExpr) { 8843 commonExpr = CondExpr; 8844 // Lower out placeholder types first. This is important so that we don't 8845 // try to capture a placeholder. This happens in few cases in C++; such 8846 // as Objective-C++'s dictionary subscripting syntax. 8847 if (commonExpr->hasPlaceholderType()) { 8848 ExprResult result = CheckPlaceholderExpr(commonExpr); 8849 if (!result.isUsable()) return ExprError(); 8850 commonExpr = result.get(); 8851 } 8852 // We usually want to apply unary conversions *before* saving, except 8853 // in the special case of a C++ l-value conditional. 8854 if (!(getLangOpts().CPlusPlus 8855 && !commonExpr->isTypeDependent() 8856 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8857 && commonExpr->isGLValue() 8858 && commonExpr->isOrdinaryOrBitFieldObject() 8859 && RHSExpr->isOrdinaryOrBitFieldObject() 8860 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8861 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8862 if (commonRes.isInvalid()) 8863 return ExprError(); 8864 commonExpr = commonRes.get(); 8865 } 8866 8867 // If the common expression is a class or array prvalue, materialize it 8868 // so that we can safely refer to it multiple times. 8869 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 8870 commonExpr->getType()->isArrayType())) { 8871 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8872 if (MatExpr.isInvalid()) 8873 return ExprError(); 8874 commonExpr = MatExpr.get(); 8875 } 8876 8877 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8878 commonExpr->getType(), 8879 commonExpr->getValueKind(), 8880 commonExpr->getObjectKind(), 8881 commonExpr); 8882 LHSExpr = CondExpr = opaqueValue; 8883 } 8884 8885 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8886 ExprValueKind VK = VK_PRValue; 8887 ExprObjectKind OK = OK_Ordinary; 8888 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8889 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8890 VK, OK, QuestionLoc); 8891 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8892 RHS.isInvalid()) 8893 return ExprError(); 8894 8895 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8896 RHS.get()); 8897 8898 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8899 8900 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8901 Context); 8902 8903 if (!commonExpr) 8904 return new (Context) 8905 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8906 RHS.get(), result, VK, OK); 8907 8908 return new (Context) BinaryConditionalOperator( 8909 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8910 ColonLoc, result, VK, OK); 8911 } 8912 8913 // Check if we have a conversion between incompatible cmse function pointer 8914 // types, that is, a conversion between a function pointer with the 8915 // cmse_nonsecure_call attribute and one without. 8916 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8917 QualType ToType) { 8918 if (const auto *ToFn = 8919 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8920 if (const auto *FromFn = 8921 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8922 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8923 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8924 8925 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8926 } 8927 } 8928 return false; 8929 } 8930 8931 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8932 // being closely modeled after the C99 spec:-). The odd characteristic of this 8933 // routine is it effectively iqnores the qualifiers on the top level pointee. 8934 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8935 // FIXME: add a couple examples in this comment. 8936 static Sema::AssignConvertType 8937 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8938 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8939 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8940 8941 // get the "pointed to" type (ignoring qualifiers at the top level) 8942 const Type *lhptee, *rhptee; 8943 Qualifiers lhq, rhq; 8944 std::tie(lhptee, lhq) = 8945 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8946 std::tie(rhptee, rhq) = 8947 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8948 8949 Sema::AssignConvertType ConvTy = Sema::Compatible; 8950 8951 // C99 6.5.16.1p1: This following citation is common to constraints 8952 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8953 // qualifiers of the type *pointed to* by the right; 8954 8955 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8956 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8957 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8958 // Ignore lifetime for further calculation. 8959 lhq.removeObjCLifetime(); 8960 rhq.removeObjCLifetime(); 8961 } 8962 8963 if (!lhq.compatiblyIncludes(rhq)) { 8964 // Treat address-space mismatches as fatal. 8965 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8966 return Sema::IncompatiblePointerDiscardsQualifiers; 8967 8968 // It's okay to add or remove GC or lifetime qualifiers when converting to 8969 // and from void*. 8970 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8971 .compatiblyIncludes( 8972 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8973 && (lhptee->isVoidType() || rhptee->isVoidType())) 8974 ; // keep old 8975 8976 // Treat lifetime mismatches as fatal. 8977 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8978 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8979 8980 // For GCC/MS compatibility, other qualifier mismatches are treated 8981 // as still compatible in C. 8982 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8983 } 8984 8985 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8986 // incomplete type and the other is a pointer to a qualified or unqualified 8987 // version of void... 8988 if (lhptee->isVoidType()) { 8989 if (rhptee->isIncompleteOrObjectType()) 8990 return ConvTy; 8991 8992 // As an extension, we allow cast to/from void* to function pointer. 8993 assert(rhptee->isFunctionType()); 8994 return Sema::FunctionVoidPointer; 8995 } 8996 8997 if (rhptee->isVoidType()) { 8998 if (lhptee->isIncompleteOrObjectType()) 8999 return ConvTy; 9000 9001 // As an extension, we allow cast to/from void* to function pointer. 9002 assert(lhptee->isFunctionType()); 9003 return Sema::FunctionVoidPointer; 9004 } 9005 9006 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 9007 // unqualified versions of compatible types, ... 9008 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 9009 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 9010 // Check if the pointee types are compatible ignoring the sign. 9011 // We explicitly check for char so that we catch "char" vs 9012 // "unsigned char" on systems where "char" is unsigned. 9013 if (lhptee->isCharType()) 9014 ltrans = S.Context.UnsignedCharTy; 9015 else if (lhptee->hasSignedIntegerRepresentation()) 9016 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 9017 9018 if (rhptee->isCharType()) 9019 rtrans = S.Context.UnsignedCharTy; 9020 else if (rhptee->hasSignedIntegerRepresentation()) 9021 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 9022 9023 if (ltrans == rtrans) { 9024 // Types are compatible ignoring the sign. Qualifier incompatibility 9025 // takes priority over sign incompatibility because the sign 9026 // warning can be disabled. 9027 if (ConvTy != Sema::Compatible) 9028 return ConvTy; 9029 9030 return Sema::IncompatiblePointerSign; 9031 } 9032 9033 // If we are a multi-level pointer, it's possible that our issue is simply 9034 // one of qualification - e.g. char ** -> const char ** is not allowed. If 9035 // the eventual target type is the same and the pointers have the same 9036 // level of indirection, this must be the issue. 9037 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 9038 do { 9039 std::tie(lhptee, lhq) = 9040 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 9041 std::tie(rhptee, rhq) = 9042 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 9043 9044 // Inconsistent address spaces at this point is invalid, even if the 9045 // address spaces would be compatible. 9046 // FIXME: This doesn't catch address space mismatches for pointers of 9047 // different nesting levels, like: 9048 // __local int *** a; 9049 // int ** b = a; 9050 // It's not clear how to actually determine when such pointers are 9051 // invalidly incompatible. 9052 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 9053 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 9054 9055 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 9056 9057 if (lhptee == rhptee) 9058 return Sema::IncompatibleNestedPointerQualifiers; 9059 } 9060 9061 // General pointer incompatibility takes priority over qualifiers. 9062 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9063 return Sema::IncompatibleFunctionPointer; 9064 return Sema::IncompatiblePointer; 9065 } 9066 if (!S.getLangOpts().CPlusPlus && 9067 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9068 return Sema::IncompatibleFunctionPointer; 9069 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9070 return Sema::IncompatibleFunctionPointer; 9071 return ConvTy; 9072 } 9073 9074 /// checkBlockPointerTypesForAssignment - This routine determines whether two 9075 /// block pointer types are compatible or whether a block and normal pointer 9076 /// are compatible. It is more restrict than comparing two function pointer 9077 // types. 9078 static Sema::AssignConvertType 9079 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9080 QualType RHSType) { 9081 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9082 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9083 9084 QualType lhptee, rhptee; 9085 9086 // get the "pointed to" type (ignoring qualifiers at the top level) 9087 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9088 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9089 9090 // In C++, the types have to match exactly. 9091 if (S.getLangOpts().CPlusPlus) 9092 return Sema::IncompatibleBlockPointer; 9093 9094 Sema::AssignConvertType ConvTy = Sema::Compatible; 9095 9096 // For blocks we enforce that qualifiers are identical. 9097 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9098 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9099 if (S.getLangOpts().OpenCL) { 9100 LQuals.removeAddressSpace(); 9101 RQuals.removeAddressSpace(); 9102 } 9103 if (LQuals != RQuals) 9104 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9105 9106 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9107 // assignment. 9108 // The current behavior is similar to C++ lambdas. A block might be 9109 // assigned to a variable iff its return type and parameters are compatible 9110 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9111 // an assignment. Presumably it should behave in way that a function pointer 9112 // assignment does in C, so for each parameter and return type: 9113 // * CVR and address space of LHS should be a superset of CVR and address 9114 // space of RHS. 9115 // * unqualified types should be compatible. 9116 if (S.getLangOpts().OpenCL) { 9117 if (!S.Context.typesAreBlockPointerCompatible( 9118 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9119 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9120 return Sema::IncompatibleBlockPointer; 9121 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9122 return Sema::IncompatibleBlockPointer; 9123 9124 return ConvTy; 9125 } 9126 9127 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9128 /// for assignment compatibility. 9129 static Sema::AssignConvertType 9130 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9131 QualType RHSType) { 9132 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9133 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9134 9135 if (LHSType->isObjCBuiltinType()) { 9136 // Class is not compatible with ObjC object pointers. 9137 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9138 !RHSType->isObjCQualifiedClassType()) 9139 return Sema::IncompatiblePointer; 9140 return Sema::Compatible; 9141 } 9142 if (RHSType->isObjCBuiltinType()) { 9143 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9144 !LHSType->isObjCQualifiedClassType()) 9145 return Sema::IncompatiblePointer; 9146 return Sema::Compatible; 9147 } 9148 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9149 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9150 9151 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9152 // make an exception for id<P> 9153 !LHSType->isObjCQualifiedIdType()) 9154 return Sema::CompatiblePointerDiscardsQualifiers; 9155 9156 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9157 return Sema::Compatible; 9158 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9159 return Sema::IncompatibleObjCQualifiedId; 9160 return Sema::IncompatiblePointer; 9161 } 9162 9163 Sema::AssignConvertType 9164 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9165 QualType LHSType, QualType RHSType) { 9166 // Fake up an opaque expression. We don't actually care about what 9167 // cast operations are required, so if CheckAssignmentConstraints 9168 // adds casts to this they'll be wasted, but fortunately that doesn't 9169 // usually happen on valid code. 9170 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 9171 ExprResult RHSPtr = &RHSExpr; 9172 CastKind K; 9173 9174 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9175 } 9176 9177 /// This helper function returns true if QT is a vector type that has element 9178 /// type ElementType. 9179 static bool isVector(QualType QT, QualType ElementType) { 9180 if (const VectorType *VT = QT->getAs<VectorType>()) 9181 return VT->getElementType().getCanonicalType() == ElementType; 9182 return false; 9183 } 9184 9185 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9186 /// has code to accommodate several GCC extensions when type checking 9187 /// pointers. Here are some objectionable examples that GCC considers warnings: 9188 /// 9189 /// int a, *pint; 9190 /// short *pshort; 9191 /// struct foo *pfoo; 9192 /// 9193 /// pint = pshort; // warning: assignment from incompatible pointer type 9194 /// a = pint; // warning: assignment makes integer from pointer without a cast 9195 /// pint = a; // warning: assignment makes pointer from integer without a cast 9196 /// pint = pfoo; // warning: assignment from incompatible pointer type 9197 /// 9198 /// As a result, the code for dealing with pointers is more complex than the 9199 /// C99 spec dictates. 9200 /// 9201 /// Sets 'Kind' for any result kind except Incompatible. 9202 Sema::AssignConvertType 9203 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9204 CastKind &Kind, bool ConvertRHS) { 9205 QualType RHSType = RHS.get()->getType(); 9206 QualType OrigLHSType = LHSType; 9207 9208 // Get canonical types. We're not formatting these types, just comparing 9209 // them. 9210 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9211 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9212 9213 // Common case: no conversion required. 9214 if (LHSType == RHSType) { 9215 Kind = CK_NoOp; 9216 return Compatible; 9217 } 9218 9219 // If we have an atomic type, try a non-atomic assignment, then just add an 9220 // atomic qualification step. 9221 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9222 Sema::AssignConvertType result = 9223 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9224 if (result != Compatible) 9225 return result; 9226 if (Kind != CK_NoOp && ConvertRHS) 9227 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9228 Kind = CK_NonAtomicToAtomic; 9229 return Compatible; 9230 } 9231 9232 // If the left-hand side is a reference type, then we are in a 9233 // (rare!) case where we've allowed the use of references in C, 9234 // e.g., as a parameter type in a built-in function. In this case, 9235 // just make sure that the type referenced is compatible with the 9236 // right-hand side type. The caller is responsible for adjusting 9237 // LHSType so that the resulting expression does not have reference 9238 // type. 9239 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9240 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9241 Kind = CK_LValueBitCast; 9242 return Compatible; 9243 } 9244 return Incompatible; 9245 } 9246 9247 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9248 // to the same ExtVector type. 9249 if (LHSType->isExtVectorType()) { 9250 if (RHSType->isExtVectorType()) 9251 return Incompatible; 9252 if (RHSType->isArithmeticType()) { 9253 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9254 if (ConvertRHS) 9255 RHS = prepareVectorSplat(LHSType, RHS.get()); 9256 Kind = CK_VectorSplat; 9257 return Compatible; 9258 } 9259 } 9260 9261 // Conversions to or from vector type. 9262 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9263 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9264 // Allow assignments of an AltiVec vector type to an equivalent GCC 9265 // vector type and vice versa 9266 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9267 Kind = CK_BitCast; 9268 return Compatible; 9269 } 9270 9271 // If we are allowing lax vector conversions, and LHS and RHS are both 9272 // vectors, the total size only needs to be the same. This is a bitcast; 9273 // no bits are changed but the result type is different. 9274 if (isLaxVectorConversion(RHSType, LHSType)) { 9275 Kind = CK_BitCast; 9276 return IncompatibleVectors; 9277 } 9278 } 9279 9280 // When the RHS comes from another lax conversion (e.g. binops between 9281 // scalars and vectors) the result is canonicalized as a vector. When the 9282 // LHS is also a vector, the lax is allowed by the condition above. Handle 9283 // the case where LHS is a scalar. 9284 if (LHSType->isScalarType()) { 9285 const VectorType *VecType = RHSType->getAs<VectorType>(); 9286 if (VecType && VecType->getNumElements() == 1 && 9287 isLaxVectorConversion(RHSType, LHSType)) { 9288 ExprResult *VecExpr = &RHS; 9289 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9290 Kind = CK_BitCast; 9291 return Compatible; 9292 } 9293 } 9294 9295 // Allow assignments between fixed-length and sizeless SVE vectors. 9296 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9297 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9298 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9299 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9300 Kind = CK_BitCast; 9301 return Compatible; 9302 } 9303 9304 return Incompatible; 9305 } 9306 9307 // Diagnose attempts to convert between __ibm128, __float128 and long double 9308 // where such conversions currently can't be handled. 9309 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9310 return Incompatible; 9311 9312 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9313 // discards the imaginary part. 9314 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9315 !LHSType->getAs<ComplexType>()) 9316 return Incompatible; 9317 9318 // Arithmetic conversions. 9319 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9320 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9321 if (ConvertRHS) 9322 Kind = PrepareScalarCast(RHS, LHSType); 9323 return Compatible; 9324 } 9325 9326 // Conversions to normal pointers. 9327 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9328 // U* -> T* 9329 if (isa<PointerType>(RHSType)) { 9330 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9331 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9332 if (AddrSpaceL != AddrSpaceR) 9333 Kind = CK_AddressSpaceConversion; 9334 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9335 Kind = CK_NoOp; 9336 else 9337 Kind = CK_BitCast; 9338 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9339 } 9340 9341 // int -> T* 9342 if (RHSType->isIntegerType()) { 9343 Kind = CK_IntegralToPointer; // FIXME: null? 9344 return IntToPointer; 9345 } 9346 9347 // C pointers are not compatible with ObjC object pointers, 9348 // with two exceptions: 9349 if (isa<ObjCObjectPointerType>(RHSType)) { 9350 // - conversions to void* 9351 if (LHSPointer->getPointeeType()->isVoidType()) { 9352 Kind = CK_BitCast; 9353 return Compatible; 9354 } 9355 9356 // - conversions from 'Class' to the redefinition type 9357 if (RHSType->isObjCClassType() && 9358 Context.hasSameType(LHSType, 9359 Context.getObjCClassRedefinitionType())) { 9360 Kind = CK_BitCast; 9361 return Compatible; 9362 } 9363 9364 Kind = CK_BitCast; 9365 return IncompatiblePointer; 9366 } 9367 9368 // U^ -> void* 9369 if (RHSType->getAs<BlockPointerType>()) { 9370 if (LHSPointer->getPointeeType()->isVoidType()) { 9371 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9372 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9373 ->getPointeeType() 9374 .getAddressSpace(); 9375 Kind = 9376 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9377 return Compatible; 9378 } 9379 } 9380 9381 return Incompatible; 9382 } 9383 9384 // Conversions to block pointers. 9385 if (isa<BlockPointerType>(LHSType)) { 9386 // U^ -> T^ 9387 if (RHSType->isBlockPointerType()) { 9388 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9389 ->getPointeeType() 9390 .getAddressSpace(); 9391 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9392 ->getPointeeType() 9393 .getAddressSpace(); 9394 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9395 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9396 } 9397 9398 // int or null -> T^ 9399 if (RHSType->isIntegerType()) { 9400 Kind = CK_IntegralToPointer; // FIXME: null 9401 return IntToBlockPointer; 9402 } 9403 9404 // id -> T^ 9405 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9406 Kind = CK_AnyPointerToBlockPointerCast; 9407 return Compatible; 9408 } 9409 9410 // void* -> T^ 9411 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9412 if (RHSPT->getPointeeType()->isVoidType()) { 9413 Kind = CK_AnyPointerToBlockPointerCast; 9414 return Compatible; 9415 } 9416 9417 return Incompatible; 9418 } 9419 9420 // Conversions to Objective-C pointers. 9421 if (isa<ObjCObjectPointerType>(LHSType)) { 9422 // A* -> B* 9423 if (RHSType->isObjCObjectPointerType()) { 9424 Kind = CK_BitCast; 9425 Sema::AssignConvertType result = 9426 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9427 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9428 result == Compatible && 9429 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9430 result = IncompatibleObjCWeakRef; 9431 return result; 9432 } 9433 9434 // int or null -> A* 9435 if (RHSType->isIntegerType()) { 9436 Kind = CK_IntegralToPointer; // FIXME: null 9437 return IntToPointer; 9438 } 9439 9440 // In general, C pointers are not compatible with ObjC object pointers, 9441 // with two exceptions: 9442 if (isa<PointerType>(RHSType)) { 9443 Kind = CK_CPointerToObjCPointerCast; 9444 9445 // - conversions from 'void*' 9446 if (RHSType->isVoidPointerType()) { 9447 return Compatible; 9448 } 9449 9450 // - conversions to 'Class' from its redefinition type 9451 if (LHSType->isObjCClassType() && 9452 Context.hasSameType(RHSType, 9453 Context.getObjCClassRedefinitionType())) { 9454 return Compatible; 9455 } 9456 9457 return IncompatiblePointer; 9458 } 9459 9460 // Only under strict condition T^ is compatible with an Objective-C pointer. 9461 if (RHSType->isBlockPointerType() && 9462 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9463 if (ConvertRHS) 9464 maybeExtendBlockObject(RHS); 9465 Kind = CK_BlockPointerToObjCPointerCast; 9466 return Compatible; 9467 } 9468 9469 return Incompatible; 9470 } 9471 9472 // Conversions from pointers that are not covered by the above. 9473 if (isa<PointerType>(RHSType)) { 9474 // T* -> _Bool 9475 if (LHSType == Context.BoolTy) { 9476 Kind = CK_PointerToBoolean; 9477 return Compatible; 9478 } 9479 9480 // T* -> int 9481 if (LHSType->isIntegerType()) { 9482 Kind = CK_PointerToIntegral; 9483 return PointerToInt; 9484 } 9485 9486 return Incompatible; 9487 } 9488 9489 // Conversions from Objective-C pointers that are not covered by the above. 9490 if (isa<ObjCObjectPointerType>(RHSType)) { 9491 // T* -> _Bool 9492 if (LHSType == Context.BoolTy) { 9493 Kind = CK_PointerToBoolean; 9494 return Compatible; 9495 } 9496 9497 // T* -> int 9498 if (LHSType->isIntegerType()) { 9499 Kind = CK_PointerToIntegral; 9500 return PointerToInt; 9501 } 9502 9503 return Incompatible; 9504 } 9505 9506 // struct A -> struct B 9507 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9508 if (Context.typesAreCompatible(LHSType, RHSType)) { 9509 Kind = CK_NoOp; 9510 return Compatible; 9511 } 9512 } 9513 9514 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9515 Kind = CK_IntToOCLSampler; 9516 return Compatible; 9517 } 9518 9519 return Incompatible; 9520 } 9521 9522 /// Constructs a transparent union from an expression that is 9523 /// used to initialize the transparent union. 9524 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9525 ExprResult &EResult, QualType UnionType, 9526 FieldDecl *Field) { 9527 // Build an initializer list that designates the appropriate member 9528 // of the transparent union. 9529 Expr *E = EResult.get(); 9530 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9531 E, SourceLocation()); 9532 Initializer->setType(UnionType); 9533 Initializer->setInitializedFieldInUnion(Field); 9534 9535 // Build a compound literal constructing a value of the transparent 9536 // union type from this initializer list. 9537 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9538 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9539 VK_PRValue, Initializer, false); 9540 } 9541 9542 Sema::AssignConvertType 9543 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9544 ExprResult &RHS) { 9545 QualType RHSType = RHS.get()->getType(); 9546 9547 // If the ArgType is a Union type, we want to handle a potential 9548 // transparent_union GCC extension. 9549 const RecordType *UT = ArgType->getAsUnionType(); 9550 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9551 return Incompatible; 9552 9553 // The field to initialize within the transparent union. 9554 RecordDecl *UD = UT->getDecl(); 9555 FieldDecl *InitField = nullptr; 9556 // It's compatible if the expression matches any of the fields. 9557 for (auto *it : UD->fields()) { 9558 if (it->getType()->isPointerType()) { 9559 // If the transparent union contains a pointer type, we allow: 9560 // 1) void pointer 9561 // 2) null pointer constant 9562 if (RHSType->isPointerType()) 9563 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9564 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9565 InitField = it; 9566 break; 9567 } 9568 9569 if (RHS.get()->isNullPointerConstant(Context, 9570 Expr::NPC_ValueDependentIsNull)) { 9571 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9572 CK_NullToPointer); 9573 InitField = it; 9574 break; 9575 } 9576 } 9577 9578 CastKind Kind; 9579 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9580 == Compatible) { 9581 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9582 InitField = it; 9583 break; 9584 } 9585 } 9586 9587 if (!InitField) 9588 return Incompatible; 9589 9590 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9591 return Compatible; 9592 } 9593 9594 Sema::AssignConvertType 9595 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9596 bool Diagnose, 9597 bool DiagnoseCFAudited, 9598 bool ConvertRHS) { 9599 // We need to be able to tell the caller whether we diagnosed a problem, if 9600 // they ask us to issue diagnostics. 9601 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9602 9603 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9604 // we can't avoid *all* modifications at the moment, so we need some somewhere 9605 // to put the updated value. 9606 ExprResult LocalRHS = CallerRHS; 9607 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9608 9609 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9610 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9611 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9612 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9613 Diag(RHS.get()->getExprLoc(), 9614 diag::warn_noderef_to_dereferenceable_pointer) 9615 << RHS.get()->getSourceRange(); 9616 } 9617 } 9618 } 9619 9620 if (getLangOpts().CPlusPlus) { 9621 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9622 // C++ 5.17p3: If the left operand is not of class type, the 9623 // expression is implicitly converted (C++ 4) to the 9624 // cv-unqualified type of the left operand. 9625 QualType RHSType = RHS.get()->getType(); 9626 if (Diagnose) { 9627 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9628 AA_Assigning); 9629 } else { 9630 ImplicitConversionSequence ICS = 9631 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9632 /*SuppressUserConversions=*/false, 9633 AllowedExplicit::None, 9634 /*InOverloadResolution=*/false, 9635 /*CStyle=*/false, 9636 /*AllowObjCWritebackConversion=*/false); 9637 if (ICS.isFailure()) 9638 return Incompatible; 9639 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9640 ICS, AA_Assigning); 9641 } 9642 if (RHS.isInvalid()) 9643 return Incompatible; 9644 Sema::AssignConvertType result = Compatible; 9645 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9646 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9647 result = IncompatibleObjCWeakRef; 9648 return result; 9649 } 9650 9651 // FIXME: Currently, we fall through and treat C++ classes like C 9652 // structures. 9653 // FIXME: We also fall through for atomics; not sure what should 9654 // happen there, though. 9655 } else if (RHS.get()->getType() == Context.OverloadTy) { 9656 // As a set of extensions to C, we support overloading on functions. These 9657 // functions need to be resolved here. 9658 DeclAccessPair DAP; 9659 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9660 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9661 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9662 else 9663 return Incompatible; 9664 } 9665 9666 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9667 // a null pointer constant. 9668 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9669 LHSType->isBlockPointerType()) && 9670 RHS.get()->isNullPointerConstant(Context, 9671 Expr::NPC_ValueDependentIsNull)) { 9672 if (Diagnose || ConvertRHS) { 9673 CastKind Kind; 9674 CXXCastPath Path; 9675 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9676 /*IgnoreBaseAccess=*/false, Diagnose); 9677 if (ConvertRHS) 9678 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 9679 } 9680 return Compatible; 9681 } 9682 9683 // OpenCL queue_t type assignment. 9684 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9685 Context, Expr::NPC_ValueDependentIsNull)) { 9686 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9687 return Compatible; 9688 } 9689 9690 // This check seems unnatural, however it is necessary to ensure the proper 9691 // conversion of functions/arrays. If the conversion were done for all 9692 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9693 // expressions that suppress this implicit conversion (&, sizeof). 9694 // 9695 // Suppress this for references: C++ 8.5.3p5. 9696 if (!LHSType->isReferenceType()) { 9697 // FIXME: We potentially allocate here even if ConvertRHS is false. 9698 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9699 if (RHS.isInvalid()) 9700 return Incompatible; 9701 } 9702 CastKind Kind; 9703 Sema::AssignConvertType result = 9704 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9705 9706 // C99 6.5.16.1p2: The value of the right operand is converted to the 9707 // type of the assignment expression. 9708 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9709 // so that we can use references in built-in functions even in C. 9710 // The getNonReferenceType() call makes sure that the resulting expression 9711 // does not have reference type. 9712 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9713 QualType Ty = LHSType.getNonLValueExprType(Context); 9714 Expr *E = RHS.get(); 9715 9716 // Check for various Objective-C errors. If we are not reporting 9717 // diagnostics and just checking for errors, e.g., during overload 9718 // resolution, return Incompatible to indicate the failure. 9719 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9720 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9721 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9722 if (!Diagnose) 9723 return Incompatible; 9724 } 9725 if (getLangOpts().ObjC && 9726 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9727 E->getType(), E, Diagnose) || 9728 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9729 if (!Diagnose) 9730 return Incompatible; 9731 // Replace the expression with a corrected version and continue so we 9732 // can find further errors. 9733 RHS = E; 9734 return Compatible; 9735 } 9736 9737 if (ConvertRHS) 9738 RHS = ImpCastExprToType(E, Ty, Kind); 9739 } 9740 9741 return result; 9742 } 9743 9744 namespace { 9745 /// The original operand to an operator, prior to the application of the usual 9746 /// arithmetic conversions and converting the arguments of a builtin operator 9747 /// candidate. 9748 struct OriginalOperand { 9749 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9750 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9751 Op = MTE->getSubExpr(); 9752 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9753 Op = BTE->getSubExpr(); 9754 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9755 Orig = ICE->getSubExprAsWritten(); 9756 Conversion = ICE->getConversionFunction(); 9757 } 9758 } 9759 9760 QualType getType() const { return Orig->getType(); } 9761 9762 Expr *Orig; 9763 NamedDecl *Conversion; 9764 }; 9765 } 9766 9767 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9768 ExprResult &RHS) { 9769 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9770 9771 Diag(Loc, diag::err_typecheck_invalid_operands) 9772 << OrigLHS.getType() << OrigRHS.getType() 9773 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9774 9775 // If a user-defined conversion was applied to either of the operands prior 9776 // to applying the built-in operator rules, tell the user about it. 9777 if (OrigLHS.Conversion) { 9778 Diag(OrigLHS.Conversion->getLocation(), 9779 diag::note_typecheck_invalid_operands_converted) 9780 << 0 << LHS.get()->getType(); 9781 } 9782 if (OrigRHS.Conversion) { 9783 Diag(OrigRHS.Conversion->getLocation(), 9784 diag::note_typecheck_invalid_operands_converted) 9785 << 1 << RHS.get()->getType(); 9786 } 9787 9788 return QualType(); 9789 } 9790 9791 // Diagnose cases where a scalar was implicitly converted to a vector and 9792 // diagnose the underlying types. Otherwise, diagnose the error 9793 // as invalid vector logical operands for non-C++ cases. 9794 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9795 ExprResult &RHS) { 9796 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9797 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9798 9799 bool LHSNatVec = LHSType->isVectorType(); 9800 bool RHSNatVec = RHSType->isVectorType(); 9801 9802 if (!(LHSNatVec && RHSNatVec)) { 9803 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9804 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9805 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9806 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9807 << Vector->getSourceRange(); 9808 return QualType(); 9809 } 9810 9811 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9812 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9813 << RHS.get()->getSourceRange(); 9814 9815 return QualType(); 9816 } 9817 9818 /// Try to convert a value of non-vector type to a vector type by converting 9819 /// the type to the element type of the vector and then performing a splat. 9820 /// If the language is OpenCL, we only use conversions that promote scalar 9821 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9822 /// for float->int. 9823 /// 9824 /// OpenCL V2.0 6.2.6.p2: 9825 /// An error shall occur if any scalar operand type has greater rank 9826 /// than the type of the vector element. 9827 /// 9828 /// \param scalar - if non-null, actually perform the conversions 9829 /// \return true if the operation fails (but without diagnosing the failure) 9830 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9831 QualType scalarTy, 9832 QualType vectorEltTy, 9833 QualType vectorTy, 9834 unsigned &DiagID) { 9835 // The conversion to apply to the scalar before splatting it, 9836 // if necessary. 9837 CastKind scalarCast = CK_NoOp; 9838 9839 if (vectorEltTy->isIntegralType(S.Context)) { 9840 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9841 (scalarTy->isIntegerType() && 9842 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9843 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9844 return true; 9845 } 9846 if (!scalarTy->isIntegralType(S.Context)) 9847 return true; 9848 scalarCast = CK_IntegralCast; 9849 } else if (vectorEltTy->isRealFloatingType()) { 9850 if (scalarTy->isRealFloatingType()) { 9851 if (S.getLangOpts().OpenCL && 9852 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9853 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9854 return true; 9855 } 9856 scalarCast = CK_FloatingCast; 9857 } 9858 else if (scalarTy->isIntegralType(S.Context)) 9859 scalarCast = CK_IntegralToFloating; 9860 else 9861 return true; 9862 } else { 9863 return true; 9864 } 9865 9866 // Adjust scalar if desired. 9867 if (scalar) { 9868 if (scalarCast != CK_NoOp) 9869 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9870 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9871 } 9872 return false; 9873 } 9874 9875 /// Convert vector E to a vector with the same number of elements but different 9876 /// element type. 9877 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9878 const auto *VecTy = E->getType()->getAs<VectorType>(); 9879 assert(VecTy && "Expression E must be a vector"); 9880 QualType NewVecTy = S.Context.getVectorType(ElementType, 9881 VecTy->getNumElements(), 9882 VecTy->getVectorKind()); 9883 9884 // Look through the implicit cast. Return the subexpression if its type is 9885 // NewVecTy. 9886 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9887 if (ICE->getSubExpr()->getType() == NewVecTy) 9888 return ICE->getSubExpr(); 9889 9890 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9891 return S.ImpCastExprToType(E, NewVecTy, Cast); 9892 } 9893 9894 /// Test if a (constant) integer Int can be casted to another integer type 9895 /// IntTy without losing precision. 9896 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9897 QualType OtherIntTy) { 9898 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9899 9900 // Reject cases where the value of the Int is unknown as that would 9901 // possibly cause truncation, but accept cases where the scalar can be 9902 // demoted without loss of precision. 9903 Expr::EvalResult EVResult; 9904 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9905 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9906 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9907 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9908 9909 if (CstInt) { 9910 // If the scalar is constant and is of a higher order and has more active 9911 // bits that the vector element type, reject it. 9912 llvm::APSInt Result = EVResult.Val.getInt(); 9913 unsigned NumBits = IntSigned 9914 ? (Result.isNegative() ? Result.getMinSignedBits() 9915 : Result.getActiveBits()) 9916 : Result.getActiveBits(); 9917 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9918 return true; 9919 9920 // If the signedness of the scalar type and the vector element type 9921 // differs and the number of bits is greater than that of the vector 9922 // element reject it. 9923 return (IntSigned != OtherIntSigned && 9924 NumBits > S.Context.getIntWidth(OtherIntTy)); 9925 } 9926 9927 // Reject cases where the value of the scalar is not constant and it's 9928 // order is greater than that of the vector element type. 9929 return (Order < 0); 9930 } 9931 9932 /// Test if a (constant) integer Int can be casted to floating point type 9933 /// FloatTy without losing precision. 9934 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9935 QualType FloatTy) { 9936 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9937 9938 // Determine if the integer constant can be expressed as a floating point 9939 // number of the appropriate type. 9940 Expr::EvalResult EVResult; 9941 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9942 9943 uint64_t Bits = 0; 9944 if (CstInt) { 9945 // Reject constants that would be truncated if they were converted to 9946 // the floating point type. Test by simple to/from conversion. 9947 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9948 // could be avoided if there was a convertFromAPInt method 9949 // which could signal back if implicit truncation occurred. 9950 llvm::APSInt Result = EVResult.Val.getInt(); 9951 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9952 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9953 llvm::APFloat::rmTowardZero); 9954 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9955 !IntTy->hasSignedIntegerRepresentation()); 9956 bool Ignored = false; 9957 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9958 &Ignored); 9959 if (Result != ConvertBack) 9960 return true; 9961 } else { 9962 // Reject types that cannot be fully encoded into the mantissa of 9963 // the float. 9964 Bits = S.Context.getTypeSize(IntTy); 9965 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9966 S.Context.getFloatTypeSemantics(FloatTy)); 9967 if (Bits > FloatPrec) 9968 return true; 9969 } 9970 9971 return false; 9972 } 9973 9974 /// Attempt to convert and splat Scalar into a vector whose types matches 9975 /// Vector following GCC conversion rules. The rule is that implicit 9976 /// conversion can occur when Scalar can be casted to match Vector's element 9977 /// type without causing truncation of Scalar. 9978 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9979 ExprResult *Vector) { 9980 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9981 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9982 const VectorType *VT = VectorTy->getAs<VectorType>(); 9983 9984 assert(!isa<ExtVectorType>(VT) && 9985 "ExtVectorTypes should not be handled here!"); 9986 9987 QualType VectorEltTy = VT->getElementType(); 9988 9989 // Reject cases where the vector element type or the scalar element type are 9990 // not integral or floating point types. 9991 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9992 return true; 9993 9994 // The conversion to apply to the scalar before splatting it, 9995 // if necessary. 9996 CastKind ScalarCast = CK_NoOp; 9997 9998 // Accept cases where the vector elements are integers and the scalar is 9999 // an integer. 10000 // FIXME: Notionally if the scalar was a floating point value with a precise 10001 // integral representation, we could cast it to an appropriate integer 10002 // type and then perform the rest of the checks here. GCC will perform 10003 // this conversion in some cases as determined by the input language. 10004 // We should accept it on a language independent basis. 10005 if (VectorEltTy->isIntegralType(S.Context) && 10006 ScalarTy->isIntegralType(S.Context) && 10007 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 10008 10009 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 10010 return true; 10011 10012 ScalarCast = CK_IntegralCast; 10013 } else if (VectorEltTy->isIntegralType(S.Context) && 10014 ScalarTy->isRealFloatingType()) { 10015 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 10016 ScalarCast = CK_FloatingToIntegral; 10017 else 10018 return true; 10019 } else if (VectorEltTy->isRealFloatingType()) { 10020 if (ScalarTy->isRealFloatingType()) { 10021 10022 // Reject cases where the scalar type is not a constant and has a higher 10023 // Order than the vector element type. 10024 llvm::APFloat Result(0.0); 10025 10026 // Determine whether this is a constant scalar. In the event that the 10027 // value is dependent (and thus cannot be evaluated by the constant 10028 // evaluator), skip the evaluation. This will then diagnose once the 10029 // expression is instantiated. 10030 bool CstScalar = Scalar->get()->isValueDependent() || 10031 Scalar->get()->EvaluateAsFloat(Result, S.Context); 10032 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 10033 if (!CstScalar && Order < 0) 10034 return true; 10035 10036 // If the scalar cannot be safely casted to the vector element type, 10037 // reject it. 10038 if (CstScalar) { 10039 bool Truncated = false; 10040 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 10041 llvm::APFloat::rmNearestTiesToEven, &Truncated); 10042 if (Truncated) 10043 return true; 10044 } 10045 10046 ScalarCast = CK_FloatingCast; 10047 } else if (ScalarTy->isIntegralType(S.Context)) { 10048 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 10049 return true; 10050 10051 ScalarCast = CK_IntegralToFloating; 10052 } else 10053 return true; 10054 } else if (ScalarTy->isEnumeralType()) 10055 return true; 10056 10057 // Adjust scalar if desired. 10058 if (Scalar) { 10059 if (ScalarCast != CK_NoOp) 10060 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 10061 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 10062 } 10063 return false; 10064 } 10065 10066 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 10067 SourceLocation Loc, bool IsCompAssign, 10068 bool AllowBothBool, 10069 bool AllowBoolConversions) { 10070 if (!IsCompAssign) { 10071 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10072 if (LHS.isInvalid()) 10073 return QualType(); 10074 } 10075 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10076 if (RHS.isInvalid()) 10077 return QualType(); 10078 10079 // For conversion purposes, we ignore any qualifiers. 10080 // For example, "const float" and "float" are equivalent. 10081 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10082 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10083 10084 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10085 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10086 assert(LHSVecType || RHSVecType); 10087 10088 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10089 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10090 return InvalidOperands(Loc, LHS, RHS); 10091 10092 // AltiVec-style "vector bool op vector bool" combinations are allowed 10093 // for some operators but not others. 10094 if (!AllowBothBool && 10095 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10096 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10097 return InvalidOperands(Loc, LHS, RHS); 10098 10099 // If the vector types are identical, return. 10100 if (Context.hasSameType(LHSType, RHSType)) 10101 return LHSType; 10102 10103 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10104 if (LHSVecType && RHSVecType && 10105 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10106 if (isa<ExtVectorType>(LHSVecType)) { 10107 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10108 return LHSType; 10109 } 10110 10111 if (!IsCompAssign) 10112 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10113 return RHSType; 10114 } 10115 10116 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10117 // can be mixed, with the result being the non-bool type. The non-bool 10118 // operand must have integer element type. 10119 if (AllowBoolConversions && LHSVecType && RHSVecType && 10120 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10121 (Context.getTypeSize(LHSVecType->getElementType()) == 10122 Context.getTypeSize(RHSVecType->getElementType()))) { 10123 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10124 LHSVecType->getElementType()->isIntegerType() && 10125 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10126 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10127 return LHSType; 10128 } 10129 if (!IsCompAssign && 10130 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10131 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10132 RHSVecType->getElementType()->isIntegerType()) { 10133 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10134 return RHSType; 10135 } 10136 } 10137 10138 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10139 // since the ambiguity can affect the ABI. 10140 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10141 const VectorType *VecType = SecondType->getAs<VectorType>(); 10142 return FirstType->isSizelessBuiltinType() && VecType && 10143 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10144 VecType->getVectorKind() == 10145 VectorType::SveFixedLengthPredicateVector); 10146 }; 10147 10148 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10149 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10150 return QualType(); 10151 } 10152 10153 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10154 // since the ambiguity can affect the ABI. 10155 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10156 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10157 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10158 10159 if (FirstVecType && SecondVecType) 10160 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10161 (SecondVecType->getVectorKind() == 10162 VectorType::SveFixedLengthDataVector || 10163 SecondVecType->getVectorKind() == 10164 VectorType::SveFixedLengthPredicateVector); 10165 10166 return FirstType->isSizelessBuiltinType() && SecondVecType && 10167 SecondVecType->getVectorKind() == VectorType::GenericVector; 10168 }; 10169 10170 if (IsSveGnuConversion(LHSType, RHSType) || 10171 IsSveGnuConversion(RHSType, LHSType)) { 10172 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10173 return QualType(); 10174 } 10175 10176 // If there's a vector type and a scalar, try to convert the scalar to 10177 // the vector element type and splat. 10178 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10179 if (!RHSVecType) { 10180 if (isa<ExtVectorType>(LHSVecType)) { 10181 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10182 LHSVecType->getElementType(), LHSType, 10183 DiagID)) 10184 return LHSType; 10185 } else { 10186 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10187 return LHSType; 10188 } 10189 } 10190 if (!LHSVecType) { 10191 if (isa<ExtVectorType>(RHSVecType)) { 10192 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10193 LHSType, RHSVecType->getElementType(), 10194 RHSType, DiagID)) 10195 return RHSType; 10196 } else { 10197 if (LHS.get()->isLValue() || 10198 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10199 return RHSType; 10200 } 10201 } 10202 10203 // FIXME: The code below also handles conversion between vectors and 10204 // non-scalars, we should break this down into fine grained specific checks 10205 // and emit proper diagnostics. 10206 QualType VecType = LHSVecType ? LHSType : RHSType; 10207 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10208 QualType OtherType = LHSVecType ? RHSType : LHSType; 10209 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10210 if (isLaxVectorConversion(OtherType, VecType)) { 10211 // If we're allowing lax vector conversions, only the total (data) size 10212 // needs to be the same. For non compound assignment, if one of the types is 10213 // scalar, the result is always the vector type. 10214 if (!IsCompAssign) { 10215 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10216 return VecType; 10217 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10218 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10219 // type. Note that this is already done by non-compound assignments in 10220 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10221 // <1 x T> -> T. The result is also a vector type. 10222 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10223 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10224 ExprResult *RHSExpr = &RHS; 10225 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10226 return VecType; 10227 } 10228 } 10229 10230 // Okay, the expression is invalid. 10231 10232 // If there's a non-vector, non-real operand, diagnose that. 10233 if ((!RHSVecType && !RHSType->isRealType()) || 10234 (!LHSVecType && !LHSType->isRealType())) { 10235 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10236 << LHSType << RHSType 10237 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10238 return QualType(); 10239 } 10240 10241 // OpenCL V1.1 6.2.6.p1: 10242 // If the operands are of more than one vector type, then an error shall 10243 // occur. Implicit conversions between vector types are not permitted, per 10244 // section 6.2.1. 10245 if (getLangOpts().OpenCL && 10246 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10247 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10248 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10249 << RHSType; 10250 return QualType(); 10251 } 10252 10253 10254 // If there is a vector type that is not a ExtVector and a scalar, we reach 10255 // this point if scalar could not be converted to the vector's element type 10256 // without truncation. 10257 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10258 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10259 QualType Scalar = LHSVecType ? RHSType : LHSType; 10260 QualType Vector = LHSVecType ? LHSType : RHSType; 10261 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10262 Diag(Loc, 10263 diag::err_typecheck_vector_not_convertable_implict_truncation) 10264 << ScalarOrVector << Scalar << Vector; 10265 10266 return QualType(); 10267 } 10268 10269 // Otherwise, use the generic diagnostic. 10270 Diag(Loc, DiagID) 10271 << LHSType << RHSType 10272 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10273 return QualType(); 10274 } 10275 10276 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10277 // expression. These are mainly cases where the null pointer is used as an 10278 // integer instead of a pointer. 10279 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10280 SourceLocation Loc, bool IsCompare) { 10281 // The canonical way to check for a GNU null is with isNullPointerConstant, 10282 // but we use a bit of a hack here for speed; this is a relatively 10283 // hot path, and isNullPointerConstant is slow. 10284 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10285 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10286 10287 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10288 10289 // Avoid analyzing cases where the result will either be invalid (and 10290 // diagnosed as such) or entirely valid and not something to warn about. 10291 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10292 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10293 return; 10294 10295 // Comparison operations would not make sense with a null pointer no matter 10296 // what the other expression is. 10297 if (!IsCompare) { 10298 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10299 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10300 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10301 return; 10302 } 10303 10304 // The rest of the operations only make sense with a null pointer 10305 // if the other expression is a pointer. 10306 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10307 NonNullType->canDecayToPointerType()) 10308 return; 10309 10310 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10311 << LHSNull /* LHS is NULL */ << NonNullType 10312 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10313 } 10314 10315 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10316 SourceLocation Loc) { 10317 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10318 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10319 if (!LUE || !RUE) 10320 return; 10321 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10322 RUE->getKind() != UETT_SizeOf) 10323 return; 10324 10325 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10326 QualType LHSTy = LHSArg->getType(); 10327 QualType RHSTy; 10328 10329 if (RUE->isArgumentType()) 10330 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10331 else 10332 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10333 10334 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10335 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10336 return; 10337 10338 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10339 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10340 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10341 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10342 << LHSArgDecl; 10343 } 10344 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10345 QualType ArrayElemTy = ArrayTy->getElementType(); 10346 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10347 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10348 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10349 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10350 return; 10351 S.Diag(Loc, diag::warn_division_sizeof_array) 10352 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10353 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10354 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10355 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10356 << LHSArgDecl; 10357 } 10358 10359 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10360 } 10361 } 10362 10363 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10364 ExprResult &RHS, 10365 SourceLocation Loc, bool IsDiv) { 10366 // Check for division/remainder by zero. 10367 Expr::EvalResult RHSValue; 10368 if (!RHS.get()->isValueDependent() && 10369 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10370 RHSValue.Val.getInt() == 0) 10371 S.DiagRuntimeBehavior(Loc, RHS.get(), 10372 S.PDiag(diag::warn_remainder_division_by_zero) 10373 << IsDiv << RHS.get()->getSourceRange()); 10374 } 10375 10376 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10377 SourceLocation Loc, 10378 bool IsCompAssign, bool IsDiv) { 10379 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10380 10381 QualType LHSTy = LHS.get()->getType(); 10382 QualType RHSTy = RHS.get()->getType(); 10383 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10384 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10385 /*AllowBothBool*/getLangOpts().AltiVec, 10386 /*AllowBoolConversions*/false); 10387 if (!IsDiv && 10388 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10389 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10390 // For division, only matrix-by-scalar is supported. Other combinations with 10391 // matrix types are invalid. 10392 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10393 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10394 10395 QualType compType = UsualArithmeticConversions( 10396 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10397 if (LHS.isInvalid() || RHS.isInvalid()) 10398 return QualType(); 10399 10400 10401 if (compType.isNull() || !compType->isArithmeticType()) 10402 return InvalidOperands(Loc, LHS, RHS); 10403 if (IsDiv) { 10404 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10405 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10406 } 10407 return compType; 10408 } 10409 10410 QualType Sema::CheckRemainderOperands( 10411 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10412 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10413 10414 if (LHS.get()->getType()->isVectorType() || 10415 RHS.get()->getType()->isVectorType()) { 10416 if (LHS.get()->getType()->hasIntegerRepresentation() && 10417 RHS.get()->getType()->hasIntegerRepresentation()) 10418 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10419 /*AllowBothBool*/getLangOpts().AltiVec, 10420 /*AllowBoolConversions*/false); 10421 return InvalidOperands(Loc, LHS, RHS); 10422 } 10423 10424 QualType compType = UsualArithmeticConversions( 10425 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10426 if (LHS.isInvalid() || RHS.isInvalid()) 10427 return QualType(); 10428 10429 if (compType.isNull() || !compType->isIntegerType()) 10430 return InvalidOperands(Loc, LHS, RHS); 10431 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10432 return compType; 10433 } 10434 10435 /// Diagnose invalid arithmetic on two void pointers. 10436 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10437 Expr *LHSExpr, Expr *RHSExpr) { 10438 S.Diag(Loc, S.getLangOpts().CPlusPlus 10439 ? diag::err_typecheck_pointer_arith_void_type 10440 : diag::ext_gnu_void_ptr) 10441 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10442 << RHSExpr->getSourceRange(); 10443 } 10444 10445 /// Diagnose invalid arithmetic on a void pointer. 10446 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10447 Expr *Pointer) { 10448 S.Diag(Loc, S.getLangOpts().CPlusPlus 10449 ? diag::err_typecheck_pointer_arith_void_type 10450 : diag::ext_gnu_void_ptr) 10451 << 0 /* one pointer */ << Pointer->getSourceRange(); 10452 } 10453 10454 /// Diagnose invalid arithmetic on a null pointer. 10455 /// 10456 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10457 /// idiom, which we recognize as a GNU extension. 10458 /// 10459 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10460 Expr *Pointer, bool IsGNUIdiom) { 10461 if (IsGNUIdiom) 10462 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10463 << Pointer->getSourceRange(); 10464 else 10465 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10466 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10467 } 10468 10469 /// Diagnose invalid subraction on a null pointer. 10470 /// 10471 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, 10472 Expr *Pointer, bool BothNull) { 10473 // Null - null is valid in C++ [expr.add]p7 10474 if (BothNull && S.getLangOpts().CPlusPlus) 10475 return; 10476 10477 // Is this s a macro from a system header? 10478 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) 10479 return; 10480 10481 S.Diag(Loc, diag::warn_pointer_sub_null_ptr) 10482 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10483 } 10484 10485 /// Diagnose invalid arithmetic on two function pointers. 10486 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10487 Expr *LHS, Expr *RHS) { 10488 assert(LHS->getType()->isAnyPointerType()); 10489 assert(RHS->getType()->isAnyPointerType()); 10490 S.Diag(Loc, S.getLangOpts().CPlusPlus 10491 ? diag::err_typecheck_pointer_arith_function_type 10492 : diag::ext_gnu_ptr_func_arith) 10493 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10494 // We only show the second type if it differs from the first. 10495 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10496 RHS->getType()) 10497 << RHS->getType()->getPointeeType() 10498 << LHS->getSourceRange() << RHS->getSourceRange(); 10499 } 10500 10501 /// Diagnose invalid arithmetic on a function pointer. 10502 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10503 Expr *Pointer) { 10504 assert(Pointer->getType()->isAnyPointerType()); 10505 S.Diag(Loc, S.getLangOpts().CPlusPlus 10506 ? diag::err_typecheck_pointer_arith_function_type 10507 : diag::ext_gnu_ptr_func_arith) 10508 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10509 << 0 /* one pointer, so only one type */ 10510 << Pointer->getSourceRange(); 10511 } 10512 10513 /// Emit error if Operand is incomplete pointer type 10514 /// 10515 /// \returns True if pointer has incomplete type 10516 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10517 Expr *Operand) { 10518 QualType ResType = Operand->getType(); 10519 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10520 ResType = ResAtomicType->getValueType(); 10521 10522 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10523 QualType PointeeTy = ResType->getPointeeType(); 10524 return S.RequireCompleteSizedType( 10525 Loc, PointeeTy, 10526 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10527 Operand->getSourceRange()); 10528 } 10529 10530 /// Check the validity of an arithmetic pointer operand. 10531 /// 10532 /// If the operand has pointer type, this code will check for pointer types 10533 /// which are invalid in arithmetic operations. These will be diagnosed 10534 /// appropriately, including whether or not the use is supported as an 10535 /// extension. 10536 /// 10537 /// \returns True when the operand is valid to use (even if as an extension). 10538 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10539 Expr *Operand) { 10540 QualType ResType = Operand->getType(); 10541 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10542 ResType = ResAtomicType->getValueType(); 10543 10544 if (!ResType->isAnyPointerType()) return true; 10545 10546 QualType PointeeTy = ResType->getPointeeType(); 10547 if (PointeeTy->isVoidType()) { 10548 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10549 return !S.getLangOpts().CPlusPlus; 10550 } 10551 if (PointeeTy->isFunctionType()) { 10552 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10553 return !S.getLangOpts().CPlusPlus; 10554 } 10555 10556 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10557 10558 return true; 10559 } 10560 10561 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10562 /// operands. 10563 /// 10564 /// This routine will diagnose any invalid arithmetic on pointer operands much 10565 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10566 /// for emitting a single diagnostic even for operations where both LHS and RHS 10567 /// are (potentially problematic) pointers. 10568 /// 10569 /// \returns True when the operand is valid to use (even if as an extension). 10570 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10571 Expr *LHSExpr, Expr *RHSExpr) { 10572 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10573 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10574 if (!isLHSPointer && !isRHSPointer) return true; 10575 10576 QualType LHSPointeeTy, RHSPointeeTy; 10577 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10578 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10579 10580 // if both are pointers check if operation is valid wrt address spaces 10581 if (isLHSPointer && isRHSPointer) { 10582 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10583 S.Diag(Loc, 10584 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10585 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10586 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10587 return false; 10588 } 10589 } 10590 10591 // Check for arithmetic on pointers to incomplete types. 10592 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10593 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10594 if (isLHSVoidPtr || isRHSVoidPtr) { 10595 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10596 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10597 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10598 10599 return !S.getLangOpts().CPlusPlus; 10600 } 10601 10602 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10603 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10604 if (isLHSFuncPtr || isRHSFuncPtr) { 10605 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10606 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10607 RHSExpr); 10608 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10609 10610 return !S.getLangOpts().CPlusPlus; 10611 } 10612 10613 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10614 return false; 10615 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10616 return false; 10617 10618 return true; 10619 } 10620 10621 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10622 /// literal. 10623 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10624 Expr *LHSExpr, Expr *RHSExpr) { 10625 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10626 Expr* IndexExpr = RHSExpr; 10627 if (!StrExpr) { 10628 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10629 IndexExpr = LHSExpr; 10630 } 10631 10632 bool IsStringPlusInt = StrExpr && 10633 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10634 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10635 return; 10636 10637 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10638 Self.Diag(OpLoc, diag::warn_string_plus_int) 10639 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10640 10641 // Only print a fixit for "str" + int, not for int + "str". 10642 if (IndexExpr == RHSExpr) { 10643 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10644 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10645 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10646 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10647 << FixItHint::CreateInsertion(EndLoc, "]"); 10648 } else 10649 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10650 } 10651 10652 /// Emit a warning when adding a char literal to a string. 10653 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10654 Expr *LHSExpr, Expr *RHSExpr) { 10655 const Expr *StringRefExpr = LHSExpr; 10656 const CharacterLiteral *CharExpr = 10657 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10658 10659 if (!CharExpr) { 10660 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10661 StringRefExpr = RHSExpr; 10662 } 10663 10664 if (!CharExpr || !StringRefExpr) 10665 return; 10666 10667 const QualType StringType = StringRefExpr->getType(); 10668 10669 // Return if not a PointerType. 10670 if (!StringType->isAnyPointerType()) 10671 return; 10672 10673 // Return if not a CharacterType. 10674 if (!StringType->getPointeeType()->isAnyCharacterType()) 10675 return; 10676 10677 ASTContext &Ctx = Self.getASTContext(); 10678 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10679 10680 const QualType CharType = CharExpr->getType(); 10681 if (!CharType->isAnyCharacterType() && 10682 CharType->isIntegerType() && 10683 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10684 Self.Diag(OpLoc, diag::warn_string_plus_char) 10685 << DiagRange << Ctx.CharTy; 10686 } else { 10687 Self.Diag(OpLoc, diag::warn_string_plus_char) 10688 << DiagRange << CharExpr->getType(); 10689 } 10690 10691 // Only print a fixit for str + char, not for char + str. 10692 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10693 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10694 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10695 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10696 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10697 << FixItHint::CreateInsertion(EndLoc, "]"); 10698 } else { 10699 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10700 } 10701 } 10702 10703 /// Emit error when two pointers are incompatible. 10704 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10705 Expr *LHSExpr, Expr *RHSExpr) { 10706 assert(LHSExpr->getType()->isAnyPointerType()); 10707 assert(RHSExpr->getType()->isAnyPointerType()); 10708 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10709 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10710 << RHSExpr->getSourceRange(); 10711 } 10712 10713 // C99 6.5.6 10714 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10715 SourceLocation Loc, BinaryOperatorKind Opc, 10716 QualType* CompLHSTy) { 10717 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10718 10719 if (LHS.get()->getType()->isVectorType() || 10720 RHS.get()->getType()->isVectorType()) { 10721 QualType compType = CheckVectorOperands( 10722 LHS, RHS, Loc, CompLHSTy, 10723 /*AllowBothBool*/getLangOpts().AltiVec, 10724 /*AllowBoolConversions*/getLangOpts().ZVector); 10725 if (CompLHSTy) *CompLHSTy = compType; 10726 return compType; 10727 } 10728 10729 if (LHS.get()->getType()->isConstantMatrixType() || 10730 RHS.get()->getType()->isConstantMatrixType()) { 10731 QualType compType = 10732 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10733 if (CompLHSTy) 10734 *CompLHSTy = compType; 10735 return compType; 10736 } 10737 10738 QualType compType = UsualArithmeticConversions( 10739 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10740 if (LHS.isInvalid() || RHS.isInvalid()) 10741 return QualType(); 10742 10743 // Diagnose "string literal" '+' int and string '+' "char literal". 10744 if (Opc == BO_Add) { 10745 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10746 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10747 } 10748 10749 // handle the common case first (both operands are arithmetic). 10750 if (!compType.isNull() && compType->isArithmeticType()) { 10751 if (CompLHSTy) *CompLHSTy = compType; 10752 return compType; 10753 } 10754 10755 // Type-checking. Ultimately the pointer's going to be in PExp; 10756 // note that we bias towards the LHS being the pointer. 10757 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10758 10759 bool isObjCPointer; 10760 if (PExp->getType()->isPointerType()) { 10761 isObjCPointer = false; 10762 } else if (PExp->getType()->isObjCObjectPointerType()) { 10763 isObjCPointer = true; 10764 } else { 10765 std::swap(PExp, IExp); 10766 if (PExp->getType()->isPointerType()) { 10767 isObjCPointer = false; 10768 } else if (PExp->getType()->isObjCObjectPointerType()) { 10769 isObjCPointer = true; 10770 } else { 10771 return InvalidOperands(Loc, LHS, RHS); 10772 } 10773 } 10774 assert(PExp->getType()->isAnyPointerType()); 10775 10776 if (!IExp->getType()->isIntegerType()) 10777 return InvalidOperands(Loc, LHS, RHS); 10778 10779 // Adding to a null pointer results in undefined behavior. 10780 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10781 Context, Expr::NPC_ValueDependentIsNotNull)) { 10782 // In C++ adding zero to a null pointer is defined. 10783 Expr::EvalResult KnownVal; 10784 if (!getLangOpts().CPlusPlus || 10785 (!IExp->isValueDependent() && 10786 (!IExp->EvaluateAsInt(KnownVal, Context) || 10787 KnownVal.Val.getInt() != 0))) { 10788 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10789 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10790 Context, BO_Add, PExp, IExp); 10791 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10792 } 10793 } 10794 10795 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10796 return QualType(); 10797 10798 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10799 return QualType(); 10800 10801 // Check array bounds for pointer arithemtic 10802 CheckArrayAccess(PExp, IExp); 10803 10804 if (CompLHSTy) { 10805 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10806 if (LHSTy.isNull()) { 10807 LHSTy = LHS.get()->getType(); 10808 if (LHSTy->isPromotableIntegerType()) 10809 LHSTy = Context.getPromotedIntegerType(LHSTy); 10810 } 10811 *CompLHSTy = LHSTy; 10812 } 10813 10814 return PExp->getType(); 10815 } 10816 10817 // C99 6.5.6 10818 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10819 SourceLocation Loc, 10820 QualType* CompLHSTy) { 10821 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10822 10823 if (LHS.get()->getType()->isVectorType() || 10824 RHS.get()->getType()->isVectorType()) { 10825 QualType compType = CheckVectorOperands( 10826 LHS, RHS, Loc, CompLHSTy, 10827 /*AllowBothBool*/getLangOpts().AltiVec, 10828 /*AllowBoolConversions*/getLangOpts().ZVector); 10829 if (CompLHSTy) *CompLHSTy = compType; 10830 return compType; 10831 } 10832 10833 if (LHS.get()->getType()->isConstantMatrixType() || 10834 RHS.get()->getType()->isConstantMatrixType()) { 10835 QualType compType = 10836 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10837 if (CompLHSTy) 10838 *CompLHSTy = compType; 10839 return compType; 10840 } 10841 10842 QualType compType = UsualArithmeticConversions( 10843 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10844 if (LHS.isInvalid() || RHS.isInvalid()) 10845 return QualType(); 10846 10847 // Enforce type constraints: C99 6.5.6p3. 10848 10849 // Handle the common case first (both operands are arithmetic). 10850 if (!compType.isNull() && compType->isArithmeticType()) { 10851 if (CompLHSTy) *CompLHSTy = compType; 10852 return compType; 10853 } 10854 10855 // Either ptr - int or ptr - ptr. 10856 if (LHS.get()->getType()->isAnyPointerType()) { 10857 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10858 10859 // Diagnose bad cases where we step over interface counts. 10860 if (LHS.get()->getType()->isObjCObjectPointerType() && 10861 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10862 return QualType(); 10863 10864 // The result type of a pointer-int computation is the pointer type. 10865 if (RHS.get()->getType()->isIntegerType()) { 10866 // Subtracting from a null pointer should produce a warning. 10867 // The last argument to the diagnose call says this doesn't match the 10868 // GNU int-to-pointer idiom. 10869 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10870 Expr::NPC_ValueDependentIsNotNull)) { 10871 // In C++ adding zero to a null pointer is defined. 10872 Expr::EvalResult KnownVal; 10873 if (!getLangOpts().CPlusPlus || 10874 (!RHS.get()->isValueDependent() && 10875 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10876 KnownVal.Val.getInt() != 0))) { 10877 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10878 } 10879 } 10880 10881 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10882 return QualType(); 10883 10884 // Check array bounds for pointer arithemtic 10885 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10886 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10887 10888 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10889 return LHS.get()->getType(); 10890 } 10891 10892 // Handle pointer-pointer subtractions. 10893 if (const PointerType *RHSPTy 10894 = RHS.get()->getType()->getAs<PointerType>()) { 10895 QualType rpointee = RHSPTy->getPointeeType(); 10896 10897 if (getLangOpts().CPlusPlus) { 10898 // Pointee types must be the same: C++ [expr.add] 10899 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10900 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10901 } 10902 } else { 10903 // Pointee types must be compatible C99 6.5.6p3 10904 if (!Context.typesAreCompatible( 10905 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10906 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10907 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10908 return QualType(); 10909 } 10910 } 10911 10912 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10913 LHS.get(), RHS.get())) 10914 return QualType(); 10915 10916 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10917 Context, Expr::NPC_ValueDependentIsNotNull); 10918 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10919 Context, Expr::NPC_ValueDependentIsNotNull); 10920 10921 // Subtracting nullptr or from nullptr is suspect 10922 if (LHSIsNullPtr) 10923 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); 10924 if (RHSIsNullPtr) 10925 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); 10926 10927 // The pointee type may have zero size. As an extension, a structure or 10928 // union may have zero size or an array may have zero length. In this 10929 // case subtraction does not make sense. 10930 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10931 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10932 if (ElementSize.isZero()) { 10933 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10934 << rpointee.getUnqualifiedType() 10935 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10936 } 10937 } 10938 10939 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10940 return Context.getPointerDiffType(); 10941 } 10942 } 10943 10944 return InvalidOperands(Loc, LHS, RHS); 10945 } 10946 10947 static bool isScopedEnumerationType(QualType T) { 10948 if (const EnumType *ET = T->getAs<EnumType>()) 10949 return ET->getDecl()->isScoped(); 10950 return false; 10951 } 10952 10953 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10954 SourceLocation Loc, BinaryOperatorKind Opc, 10955 QualType LHSType) { 10956 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10957 // so skip remaining warnings as we don't want to modify values within Sema. 10958 if (S.getLangOpts().OpenCL) 10959 return; 10960 10961 // Check right/shifter operand 10962 Expr::EvalResult RHSResult; 10963 if (RHS.get()->isValueDependent() || 10964 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10965 return; 10966 llvm::APSInt Right = RHSResult.Val.getInt(); 10967 10968 if (Right.isNegative()) { 10969 S.DiagRuntimeBehavior(Loc, RHS.get(), 10970 S.PDiag(diag::warn_shift_negative) 10971 << RHS.get()->getSourceRange()); 10972 return; 10973 } 10974 10975 QualType LHSExprType = LHS.get()->getType(); 10976 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10977 if (LHSExprType->isExtIntType()) 10978 LeftSize = S.Context.getIntWidth(LHSExprType); 10979 else if (LHSExprType->isFixedPointType()) { 10980 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10981 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10982 } 10983 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10984 if (Right.uge(LeftBits)) { 10985 S.DiagRuntimeBehavior(Loc, RHS.get(), 10986 S.PDiag(diag::warn_shift_gt_typewidth) 10987 << RHS.get()->getSourceRange()); 10988 return; 10989 } 10990 10991 // FIXME: We probably need to handle fixed point types specially here. 10992 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10993 return; 10994 10995 // When left shifting an ICE which is signed, we can check for overflow which 10996 // according to C++ standards prior to C++2a has undefined behavior 10997 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10998 // more than the maximum value representable in the result type, so never 10999 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 11000 // expression is still probably a bug.) 11001 Expr::EvalResult LHSResult; 11002 if (LHS.get()->isValueDependent() || 11003 LHSType->hasUnsignedIntegerRepresentation() || 11004 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 11005 return; 11006 llvm::APSInt Left = LHSResult.Val.getInt(); 11007 11008 // If LHS does not have a signed type and non-negative value 11009 // then, the behavior is undefined before C++2a. Warn about it. 11010 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 11011 !S.getLangOpts().CPlusPlus20) { 11012 S.DiagRuntimeBehavior(Loc, LHS.get(), 11013 S.PDiag(diag::warn_shift_lhs_negative) 11014 << LHS.get()->getSourceRange()); 11015 return; 11016 } 11017 11018 llvm::APInt ResultBits = 11019 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 11020 if (LeftBits.uge(ResultBits)) 11021 return; 11022 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 11023 Result = Result.shl(Right); 11024 11025 // Print the bit representation of the signed integer as an unsigned 11026 // hexadecimal number. 11027 SmallString<40> HexResult; 11028 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 11029 11030 // If we are only missing a sign bit, this is less likely to result in actual 11031 // bugs -- if the result is cast back to an unsigned type, it will have the 11032 // expected value. Thus we place this behind a different warning that can be 11033 // turned off separately if needed. 11034 if (LeftBits == ResultBits - 1) { 11035 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 11036 << HexResult << LHSType 11037 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11038 return; 11039 } 11040 11041 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 11042 << HexResult.str() << Result.getMinSignedBits() << LHSType 11043 << Left.getBitWidth() << LHS.get()->getSourceRange() 11044 << RHS.get()->getSourceRange(); 11045 } 11046 11047 /// Return the resulting type when a vector is shifted 11048 /// by a scalar or vector shift amount. 11049 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 11050 SourceLocation Loc, bool IsCompAssign) { 11051 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 11052 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 11053 !LHS.get()->getType()->isVectorType()) { 11054 S.Diag(Loc, diag::err_shift_rhs_only_vector) 11055 << RHS.get()->getType() << LHS.get()->getType() 11056 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11057 return QualType(); 11058 } 11059 11060 if (!IsCompAssign) { 11061 LHS = S.UsualUnaryConversions(LHS.get()); 11062 if (LHS.isInvalid()) return QualType(); 11063 } 11064 11065 RHS = S.UsualUnaryConversions(RHS.get()); 11066 if (RHS.isInvalid()) return QualType(); 11067 11068 QualType LHSType = LHS.get()->getType(); 11069 // Note that LHS might be a scalar because the routine calls not only in 11070 // OpenCL case. 11071 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 11072 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 11073 11074 // Note that RHS might not be a vector. 11075 QualType RHSType = RHS.get()->getType(); 11076 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 11077 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 11078 11079 // The operands need to be integers. 11080 if (!LHSEleType->isIntegerType()) { 11081 S.Diag(Loc, diag::err_typecheck_expect_int) 11082 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11083 return QualType(); 11084 } 11085 11086 if (!RHSEleType->isIntegerType()) { 11087 S.Diag(Loc, diag::err_typecheck_expect_int) 11088 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11089 return QualType(); 11090 } 11091 11092 if (!LHSVecTy) { 11093 assert(RHSVecTy); 11094 if (IsCompAssign) 11095 return RHSType; 11096 if (LHSEleType != RHSEleType) { 11097 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 11098 LHSEleType = RHSEleType; 11099 } 11100 QualType VecTy = 11101 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11102 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11103 LHSType = VecTy; 11104 } else if (RHSVecTy) { 11105 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11106 // are applied component-wise. So if RHS is a vector, then ensure 11107 // that the number of elements is the same as LHS... 11108 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11109 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11110 << LHS.get()->getType() << RHS.get()->getType() 11111 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11112 return QualType(); 11113 } 11114 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11115 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11116 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11117 if (LHSBT != RHSBT && 11118 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11119 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11120 << LHS.get()->getType() << RHS.get()->getType() 11121 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11122 } 11123 } 11124 } else { 11125 // ...else expand RHS to match the number of elements in LHS. 11126 QualType VecTy = 11127 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11128 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11129 } 11130 11131 return LHSType; 11132 } 11133 11134 // C99 6.5.7 11135 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11136 SourceLocation Loc, BinaryOperatorKind Opc, 11137 bool IsCompAssign) { 11138 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11139 11140 // Vector shifts promote their scalar inputs to vector type. 11141 if (LHS.get()->getType()->isVectorType() || 11142 RHS.get()->getType()->isVectorType()) { 11143 if (LangOpts.ZVector) { 11144 // The shift operators for the z vector extensions work basically 11145 // like general shifts, except that neither the LHS nor the RHS is 11146 // allowed to be a "vector bool". 11147 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11148 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11149 return InvalidOperands(Loc, LHS, RHS); 11150 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11151 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11152 return InvalidOperands(Loc, LHS, RHS); 11153 } 11154 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11155 } 11156 11157 // Shifts don't perform usual arithmetic conversions, they just do integer 11158 // promotions on each operand. C99 6.5.7p3 11159 11160 // For the LHS, do usual unary conversions, but then reset them away 11161 // if this is a compound assignment. 11162 ExprResult OldLHS = LHS; 11163 LHS = UsualUnaryConversions(LHS.get()); 11164 if (LHS.isInvalid()) 11165 return QualType(); 11166 QualType LHSType = LHS.get()->getType(); 11167 if (IsCompAssign) LHS = OldLHS; 11168 11169 // The RHS is simpler. 11170 RHS = UsualUnaryConversions(RHS.get()); 11171 if (RHS.isInvalid()) 11172 return QualType(); 11173 QualType RHSType = RHS.get()->getType(); 11174 11175 // C99 6.5.7p2: Each of the operands shall have integer type. 11176 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11177 if ((!LHSType->isFixedPointOrIntegerType() && 11178 !LHSType->hasIntegerRepresentation()) || 11179 !RHSType->hasIntegerRepresentation()) 11180 return InvalidOperands(Loc, LHS, RHS); 11181 11182 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11183 // hasIntegerRepresentation() above instead of this. 11184 if (isScopedEnumerationType(LHSType) || 11185 isScopedEnumerationType(RHSType)) { 11186 return InvalidOperands(Loc, LHS, RHS); 11187 } 11188 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11189 11190 // "The type of the result is that of the promoted left operand." 11191 return LHSType; 11192 } 11193 11194 /// Diagnose bad pointer comparisons. 11195 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11196 ExprResult &LHS, ExprResult &RHS, 11197 bool IsError) { 11198 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11199 : diag::ext_typecheck_comparison_of_distinct_pointers) 11200 << LHS.get()->getType() << RHS.get()->getType() 11201 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11202 } 11203 11204 /// Returns false if the pointers are converted to a composite type, 11205 /// true otherwise. 11206 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11207 ExprResult &LHS, ExprResult &RHS) { 11208 // C++ [expr.rel]p2: 11209 // [...] Pointer conversions (4.10) and qualification 11210 // conversions (4.4) are performed on pointer operands (or on 11211 // a pointer operand and a null pointer constant) to bring 11212 // them to their composite pointer type. [...] 11213 // 11214 // C++ [expr.eq]p1 uses the same notion for (in)equality 11215 // comparisons of pointers. 11216 11217 QualType LHSType = LHS.get()->getType(); 11218 QualType RHSType = RHS.get()->getType(); 11219 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11220 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11221 11222 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11223 if (T.isNull()) { 11224 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11225 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11226 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11227 else 11228 S.InvalidOperands(Loc, LHS, RHS); 11229 return true; 11230 } 11231 11232 return false; 11233 } 11234 11235 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11236 ExprResult &LHS, 11237 ExprResult &RHS, 11238 bool IsError) { 11239 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11240 : diag::ext_typecheck_comparison_of_fptr_to_void) 11241 << LHS.get()->getType() << RHS.get()->getType() 11242 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11243 } 11244 11245 static bool isObjCObjectLiteral(ExprResult &E) { 11246 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11247 case Stmt::ObjCArrayLiteralClass: 11248 case Stmt::ObjCDictionaryLiteralClass: 11249 case Stmt::ObjCStringLiteralClass: 11250 case Stmt::ObjCBoxedExprClass: 11251 return true; 11252 default: 11253 // Note that ObjCBoolLiteral is NOT an object literal! 11254 return false; 11255 } 11256 } 11257 11258 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11259 const ObjCObjectPointerType *Type = 11260 LHS->getType()->getAs<ObjCObjectPointerType>(); 11261 11262 // If this is not actually an Objective-C object, bail out. 11263 if (!Type) 11264 return false; 11265 11266 // Get the LHS object's interface type. 11267 QualType InterfaceType = Type->getPointeeType(); 11268 11269 // If the RHS isn't an Objective-C object, bail out. 11270 if (!RHS->getType()->isObjCObjectPointerType()) 11271 return false; 11272 11273 // Try to find the -isEqual: method. 11274 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11275 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11276 InterfaceType, 11277 /*IsInstance=*/true); 11278 if (!Method) { 11279 if (Type->isObjCIdType()) { 11280 // For 'id', just check the global pool. 11281 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11282 /*receiverId=*/true); 11283 } else { 11284 // Check protocols. 11285 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11286 /*IsInstance=*/true); 11287 } 11288 } 11289 11290 if (!Method) 11291 return false; 11292 11293 QualType T = Method->parameters()[0]->getType(); 11294 if (!T->isObjCObjectPointerType()) 11295 return false; 11296 11297 QualType R = Method->getReturnType(); 11298 if (!R->isScalarType()) 11299 return false; 11300 11301 return true; 11302 } 11303 11304 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11305 FromE = FromE->IgnoreParenImpCasts(); 11306 switch (FromE->getStmtClass()) { 11307 default: 11308 break; 11309 case Stmt::ObjCStringLiteralClass: 11310 // "string literal" 11311 return LK_String; 11312 case Stmt::ObjCArrayLiteralClass: 11313 // "array literal" 11314 return LK_Array; 11315 case Stmt::ObjCDictionaryLiteralClass: 11316 // "dictionary literal" 11317 return LK_Dictionary; 11318 case Stmt::BlockExprClass: 11319 return LK_Block; 11320 case Stmt::ObjCBoxedExprClass: { 11321 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11322 switch (Inner->getStmtClass()) { 11323 case Stmt::IntegerLiteralClass: 11324 case Stmt::FloatingLiteralClass: 11325 case Stmt::CharacterLiteralClass: 11326 case Stmt::ObjCBoolLiteralExprClass: 11327 case Stmt::CXXBoolLiteralExprClass: 11328 // "numeric literal" 11329 return LK_Numeric; 11330 case Stmt::ImplicitCastExprClass: { 11331 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11332 // Boolean literals can be represented by implicit casts. 11333 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11334 return LK_Numeric; 11335 break; 11336 } 11337 default: 11338 break; 11339 } 11340 return LK_Boxed; 11341 } 11342 } 11343 return LK_None; 11344 } 11345 11346 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11347 ExprResult &LHS, ExprResult &RHS, 11348 BinaryOperator::Opcode Opc){ 11349 Expr *Literal; 11350 Expr *Other; 11351 if (isObjCObjectLiteral(LHS)) { 11352 Literal = LHS.get(); 11353 Other = RHS.get(); 11354 } else { 11355 Literal = RHS.get(); 11356 Other = LHS.get(); 11357 } 11358 11359 // Don't warn on comparisons against nil. 11360 Other = Other->IgnoreParenCasts(); 11361 if (Other->isNullPointerConstant(S.getASTContext(), 11362 Expr::NPC_ValueDependentIsNotNull)) 11363 return; 11364 11365 // This should be kept in sync with warn_objc_literal_comparison. 11366 // LK_String should always be after the other literals, since it has its own 11367 // warning flag. 11368 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11369 assert(LiteralKind != Sema::LK_Block); 11370 if (LiteralKind == Sema::LK_None) { 11371 llvm_unreachable("Unknown Objective-C object literal kind"); 11372 } 11373 11374 if (LiteralKind == Sema::LK_String) 11375 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11376 << Literal->getSourceRange(); 11377 else 11378 S.Diag(Loc, diag::warn_objc_literal_comparison) 11379 << LiteralKind << Literal->getSourceRange(); 11380 11381 if (BinaryOperator::isEqualityOp(Opc) && 11382 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11383 SourceLocation Start = LHS.get()->getBeginLoc(); 11384 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11385 CharSourceRange OpRange = 11386 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11387 11388 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11389 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11390 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11391 << FixItHint::CreateInsertion(End, "]"); 11392 } 11393 } 11394 11395 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11396 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11397 ExprResult &RHS, SourceLocation Loc, 11398 BinaryOperatorKind Opc) { 11399 // Check that left hand side is !something. 11400 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11401 if (!UO || UO->getOpcode() != UO_LNot) return; 11402 11403 // Only check if the right hand side is non-bool arithmetic type. 11404 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11405 11406 // Make sure that the something in !something is not bool. 11407 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11408 if (SubExpr->isKnownToHaveBooleanValue()) return; 11409 11410 // Emit warning. 11411 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11412 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11413 << Loc << IsBitwiseOp; 11414 11415 // First note suggest !(x < y) 11416 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11417 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11418 FirstClose = S.getLocForEndOfToken(FirstClose); 11419 if (FirstClose.isInvalid()) 11420 FirstOpen = SourceLocation(); 11421 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11422 << IsBitwiseOp 11423 << FixItHint::CreateInsertion(FirstOpen, "(") 11424 << FixItHint::CreateInsertion(FirstClose, ")"); 11425 11426 // Second note suggests (!x) < y 11427 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11428 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11429 SecondClose = S.getLocForEndOfToken(SecondClose); 11430 if (SecondClose.isInvalid()) 11431 SecondOpen = SourceLocation(); 11432 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11433 << FixItHint::CreateInsertion(SecondOpen, "(") 11434 << FixItHint::CreateInsertion(SecondClose, ")"); 11435 } 11436 11437 // Returns true if E refers to a non-weak array. 11438 static bool checkForArray(const Expr *E) { 11439 const ValueDecl *D = nullptr; 11440 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11441 D = DR->getDecl(); 11442 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11443 if (Mem->isImplicitAccess()) 11444 D = Mem->getMemberDecl(); 11445 } 11446 if (!D) 11447 return false; 11448 return D->getType()->isArrayType() && !D->isWeak(); 11449 } 11450 11451 /// Diagnose some forms of syntactically-obvious tautological comparison. 11452 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11453 Expr *LHS, Expr *RHS, 11454 BinaryOperatorKind Opc) { 11455 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11456 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11457 11458 QualType LHSType = LHS->getType(); 11459 QualType RHSType = RHS->getType(); 11460 if (LHSType->hasFloatingRepresentation() || 11461 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11462 S.inTemplateInstantiation()) 11463 return; 11464 11465 // Comparisons between two array types are ill-formed for operator<=>, so 11466 // we shouldn't emit any additional warnings about it. 11467 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11468 return; 11469 11470 // For non-floating point types, check for self-comparisons of the form 11471 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11472 // often indicate logic errors in the program. 11473 // 11474 // NOTE: Don't warn about comparison expressions resulting from macro 11475 // expansion. Also don't warn about comparisons which are only self 11476 // comparisons within a template instantiation. The warnings should catch 11477 // obvious cases in the definition of the template anyways. The idea is to 11478 // warn when the typed comparison operator will always evaluate to the same 11479 // result. 11480 11481 // Used for indexing into %select in warn_comparison_always 11482 enum { 11483 AlwaysConstant, 11484 AlwaysTrue, 11485 AlwaysFalse, 11486 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11487 }; 11488 11489 // C++2a [depr.array.comp]: 11490 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11491 // operands of array type are deprecated. 11492 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11493 RHSStripped->getType()->isArrayType()) { 11494 S.Diag(Loc, diag::warn_depr_array_comparison) 11495 << LHS->getSourceRange() << RHS->getSourceRange() 11496 << LHSStripped->getType() << RHSStripped->getType(); 11497 // Carry on to produce the tautological comparison warning, if this 11498 // expression is potentially-evaluated, we can resolve the array to a 11499 // non-weak declaration, and so on. 11500 } 11501 11502 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11503 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11504 unsigned Result; 11505 switch (Opc) { 11506 case BO_EQ: 11507 case BO_LE: 11508 case BO_GE: 11509 Result = AlwaysTrue; 11510 break; 11511 case BO_NE: 11512 case BO_LT: 11513 case BO_GT: 11514 Result = AlwaysFalse; 11515 break; 11516 case BO_Cmp: 11517 Result = AlwaysEqual; 11518 break; 11519 default: 11520 Result = AlwaysConstant; 11521 break; 11522 } 11523 S.DiagRuntimeBehavior(Loc, nullptr, 11524 S.PDiag(diag::warn_comparison_always) 11525 << 0 /*self-comparison*/ 11526 << Result); 11527 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11528 // What is it always going to evaluate to? 11529 unsigned Result; 11530 switch (Opc) { 11531 case BO_EQ: // e.g. array1 == array2 11532 Result = AlwaysFalse; 11533 break; 11534 case BO_NE: // e.g. array1 != array2 11535 Result = AlwaysTrue; 11536 break; 11537 default: // e.g. array1 <= array2 11538 // The best we can say is 'a constant' 11539 Result = AlwaysConstant; 11540 break; 11541 } 11542 S.DiagRuntimeBehavior(Loc, nullptr, 11543 S.PDiag(diag::warn_comparison_always) 11544 << 1 /*array comparison*/ 11545 << Result); 11546 } 11547 } 11548 11549 if (isa<CastExpr>(LHSStripped)) 11550 LHSStripped = LHSStripped->IgnoreParenCasts(); 11551 if (isa<CastExpr>(RHSStripped)) 11552 RHSStripped = RHSStripped->IgnoreParenCasts(); 11553 11554 // Warn about comparisons against a string constant (unless the other 11555 // operand is null); the user probably wants string comparison function. 11556 Expr *LiteralString = nullptr; 11557 Expr *LiteralStringStripped = nullptr; 11558 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11559 !RHSStripped->isNullPointerConstant(S.Context, 11560 Expr::NPC_ValueDependentIsNull)) { 11561 LiteralString = LHS; 11562 LiteralStringStripped = LHSStripped; 11563 } else if ((isa<StringLiteral>(RHSStripped) || 11564 isa<ObjCEncodeExpr>(RHSStripped)) && 11565 !LHSStripped->isNullPointerConstant(S.Context, 11566 Expr::NPC_ValueDependentIsNull)) { 11567 LiteralString = RHS; 11568 LiteralStringStripped = RHSStripped; 11569 } 11570 11571 if (LiteralString) { 11572 S.DiagRuntimeBehavior(Loc, nullptr, 11573 S.PDiag(diag::warn_stringcompare) 11574 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11575 << LiteralString->getSourceRange()); 11576 } 11577 } 11578 11579 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11580 switch (CK) { 11581 default: { 11582 #ifndef NDEBUG 11583 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11584 << "\n"; 11585 #endif 11586 llvm_unreachable("unhandled cast kind"); 11587 } 11588 case CK_UserDefinedConversion: 11589 return ICK_Identity; 11590 case CK_LValueToRValue: 11591 return ICK_Lvalue_To_Rvalue; 11592 case CK_ArrayToPointerDecay: 11593 return ICK_Array_To_Pointer; 11594 case CK_FunctionToPointerDecay: 11595 return ICK_Function_To_Pointer; 11596 case CK_IntegralCast: 11597 return ICK_Integral_Conversion; 11598 case CK_FloatingCast: 11599 return ICK_Floating_Conversion; 11600 case CK_IntegralToFloating: 11601 case CK_FloatingToIntegral: 11602 return ICK_Floating_Integral; 11603 case CK_IntegralComplexCast: 11604 case CK_FloatingComplexCast: 11605 case CK_FloatingComplexToIntegralComplex: 11606 case CK_IntegralComplexToFloatingComplex: 11607 return ICK_Complex_Conversion; 11608 case CK_FloatingComplexToReal: 11609 case CK_FloatingRealToComplex: 11610 case CK_IntegralComplexToReal: 11611 case CK_IntegralRealToComplex: 11612 return ICK_Complex_Real; 11613 } 11614 } 11615 11616 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11617 QualType FromType, 11618 SourceLocation Loc) { 11619 // Check for a narrowing implicit conversion. 11620 StandardConversionSequence SCS; 11621 SCS.setAsIdentityConversion(); 11622 SCS.setToType(0, FromType); 11623 SCS.setToType(1, ToType); 11624 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11625 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11626 11627 APValue PreNarrowingValue; 11628 QualType PreNarrowingType; 11629 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11630 PreNarrowingType, 11631 /*IgnoreFloatToIntegralConversion*/ true)) { 11632 case NK_Dependent_Narrowing: 11633 // Implicit conversion to a narrower type, but the expression is 11634 // value-dependent so we can't tell whether it's actually narrowing. 11635 case NK_Not_Narrowing: 11636 return false; 11637 11638 case NK_Constant_Narrowing: 11639 // Implicit conversion to a narrower type, and the value is not a constant 11640 // expression. 11641 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11642 << /*Constant*/ 1 11643 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11644 return true; 11645 11646 case NK_Variable_Narrowing: 11647 // Implicit conversion to a narrower type, and the value is not a constant 11648 // expression. 11649 case NK_Type_Narrowing: 11650 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11651 << /*Constant*/ 0 << FromType << ToType; 11652 // TODO: It's not a constant expression, but what if the user intended it 11653 // to be? Can we produce notes to help them figure out why it isn't? 11654 return true; 11655 } 11656 llvm_unreachable("unhandled case in switch"); 11657 } 11658 11659 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11660 ExprResult &LHS, 11661 ExprResult &RHS, 11662 SourceLocation Loc) { 11663 QualType LHSType = LHS.get()->getType(); 11664 QualType RHSType = RHS.get()->getType(); 11665 // Dig out the original argument type and expression before implicit casts 11666 // were applied. These are the types/expressions we need to check the 11667 // [expr.spaceship] requirements against. 11668 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11669 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11670 QualType LHSStrippedType = LHSStripped.get()->getType(); 11671 QualType RHSStrippedType = RHSStripped.get()->getType(); 11672 11673 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11674 // other is not, the program is ill-formed. 11675 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11676 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11677 return QualType(); 11678 } 11679 11680 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11681 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11682 RHSStrippedType->isEnumeralType(); 11683 if (NumEnumArgs == 1) { 11684 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11685 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11686 if (OtherTy->hasFloatingRepresentation()) { 11687 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11688 return QualType(); 11689 } 11690 } 11691 if (NumEnumArgs == 2) { 11692 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11693 // type E, the operator yields the result of converting the operands 11694 // to the underlying type of E and applying <=> to the converted operands. 11695 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11696 S.InvalidOperands(Loc, LHS, RHS); 11697 return QualType(); 11698 } 11699 QualType IntType = 11700 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11701 assert(IntType->isArithmeticType()); 11702 11703 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11704 // promote the boolean type, and all other promotable integer types, to 11705 // avoid this. 11706 if (IntType->isPromotableIntegerType()) 11707 IntType = S.Context.getPromotedIntegerType(IntType); 11708 11709 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11710 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11711 LHSType = RHSType = IntType; 11712 } 11713 11714 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11715 // usual arithmetic conversions are applied to the operands. 11716 QualType Type = 11717 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11718 if (LHS.isInvalid() || RHS.isInvalid()) 11719 return QualType(); 11720 if (Type.isNull()) 11721 return S.InvalidOperands(Loc, LHS, RHS); 11722 11723 Optional<ComparisonCategoryType> CCT = 11724 getComparisonCategoryForBuiltinCmp(Type); 11725 if (!CCT) 11726 return S.InvalidOperands(Loc, LHS, RHS); 11727 11728 bool HasNarrowing = checkThreeWayNarrowingConversion( 11729 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11730 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11731 RHS.get()->getBeginLoc()); 11732 if (HasNarrowing) 11733 return QualType(); 11734 11735 assert(!Type.isNull() && "composite type for <=> has not been set"); 11736 11737 return S.CheckComparisonCategoryType( 11738 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11739 } 11740 11741 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11742 ExprResult &RHS, 11743 SourceLocation Loc, 11744 BinaryOperatorKind Opc) { 11745 if (Opc == BO_Cmp) 11746 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11747 11748 // C99 6.5.8p3 / C99 6.5.9p4 11749 QualType Type = 11750 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11751 if (LHS.isInvalid() || RHS.isInvalid()) 11752 return QualType(); 11753 if (Type.isNull()) 11754 return S.InvalidOperands(Loc, LHS, RHS); 11755 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11756 11757 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11758 return S.InvalidOperands(Loc, LHS, RHS); 11759 11760 // Check for comparisons of floating point operands using != and ==. 11761 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11762 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11763 11764 // The result of comparisons is 'bool' in C++, 'int' in C. 11765 return S.Context.getLogicalOperationType(); 11766 } 11767 11768 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11769 if (!NullE.get()->getType()->isAnyPointerType()) 11770 return; 11771 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11772 if (!E.get()->getType()->isAnyPointerType() && 11773 E.get()->isNullPointerConstant(Context, 11774 Expr::NPC_ValueDependentIsNotNull) == 11775 Expr::NPCK_ZeroExpression) { 11776 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11777 if (CL->getValue() == 0) 11778 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11779 << NullValue 11780 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11781 NullValue ? "NULL" : "(void *)0"); 11782 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11783 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11784 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11785 if (T == Context.CharTy) 11786 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11787 << NullValue 11788 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11789 NullValue ? "NULL" : "(void *)0"); 11790 } 11791 } 11792 } 11793 11794 // C99 6.5.8, C++ [expr.rel] 11795 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11796 SourceLocation Loc, 11797 BinaryOperatorKind Opc) { 11798 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11799 bool IsThreeWay = Opc == BO_Cmp; 11800 bool IsOrdered = IsRelational || IsThreeWay; 11801 auto IsAnyPointerType = [](ExprResult E) { 11802 QualType Ty = E.get()->getType(); 11803 return Ty->isPointerType() || Ty->isMemberPointerType(); 11804 }; 11805 11806 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11807 // type, array-to-pointer, ..., conversions are performed on both operands to 11808 // bring them to their composite type. 11809 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11810 // any type-related checks. 11811 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11812 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11813 if (LHS.isInvalid()) 11814 return QualType(); 11815 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11816 if (RHS.isInvalid()) 11817 return QualType(); 11818 } else { 11819 LHS = DefaultLvalueConversion(LHS.get()); 11820 if (LHS.isInvalid()) 11821 return QualType(); 11822 RHS = DefaultLvalueConversion(RHS.get()); 11823 if (RHS.isInvalid()) 11824 return QualType(); 11825 } 11826 11827 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11828 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11829 CheckPtrComparisonWithNullChar(LHS, RHS); 11830 CheckPtrComparisonWithNullChar(RHS, LHS); 11831 } 11832 11833 // Handle vector comparisons separately. 11834 if (LHS.get()->getType()->isVectorType() || 11835 RHS.get()->getType()->isVectorType()) 11836 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11837 11838 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11839 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11840 11841 QualType LHSType = LHS.get()->getType(); 11842 QualType RHSType = RHS.get()->getType(); 11843 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11844 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11845 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11846 11847 const Expr::NullPointerConstantKind LHSNullKind = 11848 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11849 const Expr::NullPointerConstantKind RHSNullKind = 11850 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11851 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11852 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11853 11854 auto computeResultTy = [&]() { 11855 if (Opc != BO_Cmp) 11856 return Context.getLogicalOperationType(); 11857 assert(getLangOpts().CPlusPlus); 11858 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11859 11860 QualType CompositeTy = LHS.get()->getType(); 11861 assert(!CompositeTy->isReferenceType()); 11862 11863 Optional<ComparisonCategoryType> CCT = 11864 getComparisonCategoryForBuiltinCmp(CompositeTy); 11865 if (!CCT) 11866 return InvalidOperands(Loc, LHS, RHS); 11867 11868 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11869 // P0946R0: Comparisons between a null pointer constant and an object 11870 // pointer result in std::strong_equality, which is ill-formed under 11871 // P1959R0. 11872 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11873 << (LHSIsNull ? LHS.get()->getSourceRange() 11874 : RHS.get()->getSourceRange()); 11875 return QualType(); 11876 } 11877 11878 return CheckComparisonCategoryType( 11879 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11880 }; 11881 11882 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11883 bool IsEquality = Opc == BO_EQ; 11884 if (RHSIsNull) 11885 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11886 RHS.get()->getSourceRange()); 11887 else 11888 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11889 LHS.get()->getSourceRange()); 11890 } 11891 11892 if (IsOrdered && LHSType->isFunctionPointerType() && 11893 RHSType->isFunctionPointerType()) { 11894 // Valid unless a relational comparison of function pointers 11895 bool IsError = Opc == BO_Cmp; 11896 auto DiagID = 11897 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 11898 : getLangOpts().CPlusPlus 11899 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 11900 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 11901 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 11902 << RHS.get()->getSourceRange(); 11903 if (IsError) 11904 return QualType(); 11905 } 11906 11907 if ((LHSType->isIntegerType() && !LHSIsNull) || 11908 (RHSType->isIntegerType() && !RHSIsNull)) { 11909 // Skip normal pointer conversion checks in this case; we have better 11910 // diagnostics for this below. 11911 } else if (getLangOpts().CPlusPlus) { 11912 // Equality comparison of a function pointer to a void pointer is invalid, 11913 // but we allow it as an extension. 11914 // FIXME: If we really want to allow this, should it be part of composite 11915 // pointer type computation so it works in conditionals too? 11916 if (!IsOrdered && 11917 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11918 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11919 // This is a gcc extension compatibility comparison. 11920 // In a SFINAE context, we treat this as a hard error to maintain 11921 // conformance with the C++ standard. 11922 diagnoseFunctionPointerToVoidComparison( 11923 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11924 11925 if (isSFINAEContext()) 11926 return QualType(); 11927 11928 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11929 return computeResultTy(); 11930 } 11931 11932 // C++ [expr.eq]p2: 11933 // If at least one operand is a pointer [...] bring them to their 11934 // composite pointer type. 11935 // C++ [expr.spaceship]p6 11936 // If at least one of the operands is of pointer type, [...] bring them 11937 // to their composite pointer type. 11938 // C++ [expr.rel]p2: 11939 // If both operands are pointers, [...] bring them to their composite 11940 // pointer type. 11941 // For <=>, the only valid non-pointer types are arrays and functions, and 11942 // we already decayed those, so this is really the same as the relational 11943 // comparison rule. 11944 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11945 (IsOrdered ? 2 : 1) && 11946 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11947 RHSType->isObjCObjectPointerType()))) { 11948 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11949 return QualType(); 11950 return computeResultTy(); 11951 } 11952 } else if (LHSType->isPointerType() && 11953 RHSType->isPointerType()) { // C99 6.5.8p2 11954 // All of the following pointer-related warnings are GCC extensions, except 11955 // when handling null pointer constants. 11956 QualType LCanPointeeTy = 11957 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11958 QualType RCanPointeeTy = 11959 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11960 11961 // C99 6.5.9p2 and C99 6.5.8p2 11962 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11963 RCanPointeeTy.getUnqualifiedType())) { 11964 if (IsRelational) { 11965 // Pointers both need to point to complete or incomplete types 11966 if ((LCanPointeeTy->isIncompleteType() != 11967 RCanPointeeTy->isIncompleteType()) && 11968 !getLangOpts().C11) { 11969 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11970 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11971 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11972 << RCanPointeeTy->isIncompleteType(); 11973 } 11974 } 11975 } else if (!IsRelational && 11976 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11977 // Valid unless comparison between non-null pointer and function pointer 11978 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11979 && !LHSIsNull && !RHSIsNull) 11980 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11981 /*isError*/false); 11982 } else { 11983 // Invalid 11984 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11985 } 11986 if (LCanPointeeTy != RCanPointeeTy) { 11987 // Treat NULL constant as a special case in OpenCL. 11988 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11989 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11990 Diag(Loc, 11991 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11992 << LHSType << RHSType << 0 /* comparison */ 11993 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11994 } 11995 } 11996 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11997 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11998 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11999 : CK_BitCast; 12000 if (LHSIsNull && !RHSIsNull) 12001 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 12002 else 12003 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 12004 } 12005 return computeResultTy(); 12006 } 12007 12008 if (getLangOpts().CPlusPlus) { 12009 // C++ [expr.eq]p4: 12010 // Two operands of type std::nullptr_t or one operand of type 12011 // std::nullptr_t and the other a null pointer constant compare equal. 12012 if (!IsOrdered && LHSIsNull && RHSIsNull) { 12013 if (LHSType->isNullPtrType()) { 12014 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12015 return computeResultTy(); 12016 } 12017 if (RHSType->isNullPtrType()) { 12018 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12019 return computeResultTy(); 12020 } 12021 } 12022 12023 // Comparison of Objective-C pointers and block pointers against nullptr_t. 12024 // These aren't covered by the composite pointer type rules. 12025 if (!IsOrdered && RHSType->isNullPtrType() && 12026 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 12027 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12028 return computeResultTy(); 12029 } 12030 if (!IsOrdered && LHSType->isNullPtrType() && 12031 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 12032 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12033 return computeResultTy(); 12034 } 12035 12036 if (IsRelational && 12037 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 12038 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 12039 // HACK: Relational comparison of nullptr_t against a pointer type is 12040 // invalid per DR583, but we allow it within std::less<> and friends, 12041 // since otherwise common uses of it break. 12042 // FIXME: Consider removing this hack once LWG fixes std::less<> and 12043 // friends to have std::nullptr_t overload candidates. 12044 DeclContext *DC = CurContext; 12045 if (isa<FunctionDecl>(DC)) 12046 DC = DC->getParent(); 12047 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 12048 if (CTSD->isInStdNamespace() && 12049 llvm::StringSwitch<bool>(CTSD->getName()) 12050 .Cases("less", "less_equal", "greater", "greater_equal", true) 12051 .Default(false)) { 12052 if (RHSType->isNullPtrType()) 12053 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12054 else 12055 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12056 return computeResultTy(); 12057 } 12058 } 12059 } 12060 12061 // C++ [expr.eq]p2: 12062 // If at least one operand is a pointer to member, [...] bring them to 12063 // their composite pointer type. 12064 if (!IsOrdered && 12065 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 12066 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12067 return QualType(); 12068 else 12069 return computeResultTy(); 12070 } 12071 } 12072 12073 // Handle block pointer types. 12074 if (!IsOrdered && LHSType->isBlockPointerType() && 12075 RHSType->isBlockPointerType()) { 12076 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 12077 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 12078 12079 if (!LHSIsNull && !RHSIsNull && 12080 !Context.typesAreCompatible(lpointee, rpointee)) { 12081 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12082 << LHSType << RHSType << LHS.get()->getSourceRange() 12083 << RHS.get()->getSourceRange(); 12084 } 12085 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12086 return computeResultTy(); 12087 } 12088 12089 // Allow block pointers to be compared with null pointer constants. 12090 if (!IsOrdered 12091 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 12092 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 12093 if (!LHSIsNull && !RHSIsNull) { 12094 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 12095 ->getPointeeType()->isVoidType()) 12096 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12097 ->getPointeeType()->isVoidType()))) 12098 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12099 << LHSType << RHSType << LHS.get()->getSourceRange() 12100 << RHS.get()->getSourceRange(); 12101 } 12102 if (LHSIsNull && !RHSIsNull) 12103 LHS = ImpCastExprToType(LHS.get(), RHSType, 12104 RHSType->isPointerType() ? CK_BitCast 12105 : CK_AnyPointerToBlockPointerCast); 12106 else 12107 RHS = ImpCastExprToType(RHS.get(), LHSType, 12108 LHSType->isPointerType() ? CK_BitCast 12109 : CK_AnyPointerToBlockPointerCast); 12110 return computeResultTy(); 12111 } 12112 12113 if (LHSType->isObjCObjectPointerType() || 12114 RHSType->isObjCObjectPointerType()) { 12115 const PointerType *LPT = LHSType->getAs<PointerType>(); 12116 const PointerType *RPT = RHSType->getAs<PointerType>(); 12117 if (LPT || RPT) { 12118 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12119 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12120 12121 if (!LPtrToVoid && !RPtrToVoid && 12122 !Context.typesAreCompatible(LHSType, RHSType)) { 12123 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12124 /*isError*/false); 12125 } 12126 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12127 // the RHS, but we have test coverage for this behavior. 12128 // FIXME: Consider using convertPointersToCompositeType in C++. 12129 if (LHSIsNull && !RHSIsNull) { 12130 Expr *E = LHS.get(); 12131 if (getLangOpts().ObjCAutoRefCount) 12132 CheckObjCConversion(SourceRange(), RHSType, E, 12133 CCK_ImplicitConversion); 12134 LHS = ImpCastExprToType(E, RHSType, 12135 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12136 } 12137 else { 12138 Expr *E = RHS.get(); 12139 if (getLangOpts().ObjCAutoRefCount) 12140 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12141 /*Diagnose=*/true, 12142 /*DiagnoseCFAudited=*/false, Opc); 12143 RHS = ImpCastExprToType(E, LHSType, 12144 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12145 } 12146 return computeResultTy(); 12147 } 12148 if (LHSType->isObjCObjectPointerType() && 12149 RHSType->isObjCObjectPointerType()) { 12150 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12151 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12152 /*isError*/false); 12153 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12154 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12155 12156 if (LHSIsNull && !RHSIsNull) 12157 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12158 else 12159 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12160 return computeResultTy(); 12161 } 12162 12163 if (!IsOrdered && LHSType->isBlockPointerType() && 12164 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12165 LHS = ImpCastExprToType(LHS.get(), RHSType, 12166 CK_BlockPointerToObjCPointerCast); 12167 return computeResultTy(); 12168 } else if (!IsOrdered && 12169 LHSType->isBlockCompatibleObjCPointerType(Context) && 12170 RHSType->isBlockPointerType()) { 12171 RHS = ImpCastExprToType(RHS.get(), LHSType, 12172 CK_BlockPointerToObjCPointerCast); 12173 return computeResultTy(); 12174 } 12175 } 12176 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12177 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12178 unsigned DiagID = 0; 12179 bool isError = false; 12180 if (LangOpts.DebuggerSupport) { 12181 // Under a debugger, allow the comparison of pointers to integers, 12182 // since users tend to want to compare addresses. 12183 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12184 (RHSIsNull && RHSType->isIntegerType())) { 12185 if (IsOrdered) { 12186 isError = getLangOpts().CPlusPlus; 12187 DiagID = 12188 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12189 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12190 } 12191 } else if (getLangOpts().CPlusPlus) { 12192 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12193 isError = true; 12194 } else if (IsOrdered) 12195 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12196 else 12197 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12198 12199 if (DiagID) { 12200 Diag(Loc, DiagID) 12201 << LHSType << RHSType << LHS.get()->getSourceRange() 12202 << RHS.get()->getSourceRange(); 12203 if (isError) 12204 return QualType(); 12205 } 12206 12207 if (LHSType->isIntegerType()) 12208 LHS = ImpCastExprToType(LHS.get(), RHSType, 12209 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12210 else 12211 RHS = ImpCastExprToType(RHS.get(), LHSType, 12212 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12213 return computeResultTy(); 12214 } 12215 12216 // Handle block pointers. 12217 if (!IsOrdered && RHSIsNull 12218 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12219 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12220 return computeResultTy(); 12221 } 12222 if (!IsOrdered && LHSIsNull 12223 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12224 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12225 return computeResultTy(); 12226 } 12227 12228 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 12229 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12230 return computeResultTy(); 12231 } 12232 12233 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12234 return computeResultTy(); 12235 } 12236 12237 if (LHSIsNull && RHSType->isQueueT()) { 12238 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12239 return computeResultTy(); 12240 } 12241 12242 if (LHSType->isQueueT() && RHSIsNull) { 12243 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12244 return computeResultTy(); 12245 } 12246 } 12247 12248 return InvalidOperands(Loc, LHS, RHS); 12249 } 12250 12251 // Return a signed ext_vector_type that is of identical size and number of 12252 // elements. For floating point vectors, return an integer type of identical 12253 // size and number of elements. In the non ext_vector_type case, search from 12254 // the largest type to the smallest type to avoid cases where long long == long, 12255 // where long gets picked over long long. 12256 QualType Sema::GetSignedVectorType(QualType V) { 12257 const VectorType *VTy = V->castAs<VectorType>(); 12258 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12259 12260 if (isa<ExtVectorType>(VTy)) { 12261 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12262 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12263 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12264 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12265 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12266 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12267 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12268 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12269 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12270 "Unhandled vector element size in vector compare"); 12271 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12272 } 12273 12274 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12275 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12276 VectorType::GenericVector); 12277 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12278 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12279 VectorType::GenericVector); 12280 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12281 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12282 VectorType::GenericVector); 12283 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12284 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12285 VectorType::GenericVector); 12286 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12287 "Unhandled vector element size in vector compare"); 12288 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12289 VectorType::GenericVector); 12290 } 12291 12292 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12293 /// operates on extended vector types. Instead of producing an IntTy result, 12294 /// like a scalar comparison, a vector comparison produces a vector of integer 12295 /// types. 12296 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12297 SourceLocation Loc, 12298 BinaryOperatorKind Opc) { 12299 if (Opc == BO_Cmp) { 12300 Diag(Loc, diag::err_three_way_vector_comparison); 12301 return QualType(); 12302 } 12303 12304 // Check to make sure we're operating on vectors of the same type and width, 12305 // Allowing one side to be a scalar of element type. 12306 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12307 /*AllowBothBool*/true, 12308 /*AllowBoolConversions*/getLangOpts().ZVector); 12309 if (vType.isNull()) 12310 return vType; 12311 12312 QualType LHSType = LHS.get()->getType(); 12313 12314 // Determine the return type of a vector compare. By default clang will return 12315 // a scalar for all vector compares except vector bool and vector pixel. 12316 // With the gcc compiler we will always return a vector type and with the xl 12317 // compiler we will always return a scalar type. This switch allows choosing 12318 // which behavior is prefered. 12319 if (getLangOpts().AltiVec) { 12320 switch (getLangOpts().getAltivecSrcCompat()) { 12321 case LangOptions::AltivecSrcCompatKind::Mixed: 12322 // If AltiVec, the comparison results in a numeric type, i.e. 12323 // bool for C++, int for C 12324 if (vType->castAs<VectorType>()->getVectorKind() == 12325 VectorType::AltiVecVector) 12326 return Context.getLogicalOperationType(); 12327 else 12328 Diag(Loc, diag::warn_deprecated_altivec_src_compat); 12329 break; 12330 case LangOptions::AltivecSrcCompatKind::GCC: 12331 // For GCC we always return the vector type. 12332 break; 12333 case LangOptions::AltivecSrcCompatKind::XL: 12334 return Context.getLogicalOperationType(); 12335 break; 12336 } 12337 } 12338 12339 // For non-floating point types, check for self-comparisons of the form 12340 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12341 // often indicate logic errors in the program. 12342 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12343 12344 // Check for comparisons of floating point operands using != and ==. 12345 if (BinaryOperator::isEqualityOp(Opc) && 12346 LHSType->hasFloatingRepresentation()) { 12347 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12348 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12349 } 12350 12351 // Return a signed type for the vector. 12352 return GetSignedVectorType(vType); 12353 } 12354 12355 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12356 const ExprResult &XorRHS, 12357 const SourceLocation Loc) { 12358 // Do not diagnose macros. 12359 if (Loc.isMacroID()) 12360 return; 12361 12362 // Do not diagnose if both LHS and RHS are macros. 12363 if (XorLHS.get()->getExprLoc().isMacroID() && 12364 XorRHS.get()->getExprLoc().isMacroID()) 12365 return; 12366 12367 bool Negative = false; 12368 bool ExplicitPlus = false; 12369 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12370 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12371 12372 if (!LHSInt) 12373 return; 12374 if (!RHSInt) { 12375 // Check negative literals. 12376 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12377 UnaryOperatorKind Opc = UO->getOpcode(); 12378 if (Opc != UO_Minus && Opc != UO_Plus) 12379 return; 12380 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12381 if (!RHSInt) 12382 return; 12383 Negative = (Opc == UO_Minus); 12384 ExplicitPlus = !Negative; 12385 } else { 12386 return; 12387 } 12388 } 12389 12390 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12391 llvm::APInt RightSideValue = RHSInt->getValue(); 12392 if (LeftSideValue != 2 && LeftSideValue != 10) 12393 return; 12394 12395 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12396 return; 12397 12398 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12399 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12400 llvm::StringRef ExprStr = 12401 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12402 12403 CharSourceRange XorRange = 12404 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12405 llvm::StringRef XorStr = 12406 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12407 // Do not diagnose if xor keyword/macro is used. 12408 if (XorStr == "xor") 12409 return; 12410 12411 std::string LHSStr = std::string(Lexer::getSourceText( 12412 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12413 S.getSourceManager(), S.getLangOpts())); 12414 std::string RHSStr = std::string(Lexer::getSourceText( 12415 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12416 S.getSourceManager(), S.getLangOpts())); 12417 12418 if (Negative) { 12419 RightSideValue = -RightSideValue; 12420 RHSStr = "-" + RHSStr; 12421 } else if (ExplicitPlus) { 12422 RHSStr = "+" + RHSStr; 12423 } 12424 12425 StringRef LHSStrRef = LHSStr; 12426 StringRef RHSStrRef = RHSStr; 12427 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12428 // literals. 12429 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12430 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12431 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12432 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12433 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12434 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12435 LHSStrRef.contains('\'') || RHSStrRef.contains('\'')) 12436 return; 12437 12438 bool SuggestXor = 12439 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12440 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12441 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12442 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12443 std::string SuggestedExpr = "1 << " + RHSStr; 12444 bool Overflow = false; 12445 llvm::APInt One = (LeftSideValue - 1); 12446 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12447 if (Overflow) { 12448 if (RightSideIntValue < 64) 12449 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12450 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 12451 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12452 else if (RightSideIntValue == 64) 12453 S.Diag(Loc, diag::warn_xor_used_as_pow) 12454 << ExprStr << toString(XorValue, 10, true); 12455 else 12456 return; 12457 } else { 12458 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12459 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 12460 << toString(PowValue, 10, true) 12461 << FixItHint::CreateReplacement( 12462 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12463 } 12464 12465 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12466 << ("0x2 ^ " + RHSStr) << SuggestXor; 12467 } else if (LeftSideValue == 10) { 12468 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12469 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12470 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 12471 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12472 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12473 << ("0xA ^ " + RHSStr) << SuggestXor; 12474 } 12475 } 12476 12477 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12478 SourceLocation Loc) { 12479 // Ensure that either both operands are of the same vector type, or 12480 // one operand is of a vector type and the other is of its element type. 12481 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12482 /*AllowBothBool*/true, 12483 /*AllowBoolConversions*/false); 12484 if (vType.isNull()) 12485 return InvalidOperands(Loc, LHS, RHS); 12486 if (getLangOpts().OpenCL && 12487 getLangOpts().getOpenCLCompatibleVersion() < 120 && 12488 vType->hasFloatingRepresentation()) 12489 return InvalidOperands(Loc, LHS, RHS); 12490 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12491 // usage of the logical operators && and || with vectors in C. This 12492 // check could be notionally dropped. 12493 if (!getLangOpts().CPlusPlus && 12494 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12495 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12496 12497 return GetSignedVectorType(LHS.get()->getType()); 12498 } 12499 12500 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12501 SourceLocation Loc, 12502 bool IsCompAssign) { 12503 if (!IsCompAssign) { 12504 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12505 if (LHS.isInvalid()) 12506 return QualType(); 12507 } 12508 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12509 if (RHS.isInvalid()) 12510 return QualType(); 12511 12512 // For conversion purposes, we ignore any qualifiers. 12513 // For example, "const float" and "float" are equivalent. 12514 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12515 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12516 12517 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12518 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12519 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12520 12521 if (Context.hasSameType(LHSType, RHSType)) 12522 return LHSType; 12523 12524 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12525 // case we have to return InvalidOperands. 12526 ExprResult OriginalLHS = LHS; 12527 ExprResult OriginalRHS = RHS; 12528 if (LHSMatType && !RHSMatType) { 12529 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12530 if (!RHS.isInvalid()) 12531 return LHSType; 12532 12533 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12534 } 12535 12536 if (!LHSMatType && RHSMatType) { 12537 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12538 if (!LHS.isInvalid()) 12539 return RHSType; 12540 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12541 } 12542 12543 return InvalidOperands(Loc, LHS, RHS); 12544 } 12545 12546 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12547 SourceLocation Loc, 12548 bool IsCompAssign) { 12549 if (!IsCompAssign) { 12550 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12551 if (LHS.isInvalid()) 12552 return QualType(); 12553 } 12554 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12555 if (RHS.isInvalid()) 12556 return QualType(); 12557 12558 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12559 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12560 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12561 12562 if (LHSMatType && RHSMatType) { 12563 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12564 return InvalidOperands(Loc, LHS, RHS); 12565 12566 if (!Context.hasSameType(LHSMatType->getElementType(), 12567 RHSMatType->getElementType())) 12568 return InvalidOperands(Loc, LHS, RHS); 12569 12570 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12571 LHSMatType->getNumRows(), 12572 RHSMatType->getNumColumns()); 12573 } 12574 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12575 } 12576 12577 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12578 SourceLocation Loc, 12579 BinaryOperatorKind Opc) { 12580 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12581 12582 bool IsCompAssign = 12583 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12584 12585 if (LHS.get()->getType()->isVectorType() || 12586 RHS.get()->getType()->isVectorType()) { 12587 if (LHS.get()->getType()->hasIntegerRepresentation() && 12588 RHS.get()->getType()->hasIntegerRepresentation()) 12589 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12590 /*AllowBothBool*/true, 12591 /*AllowBoolConversions*/getLangOpts().ZVector); 12592 return InvalidOperands(Loc, LHS, RHS); 12593 } 12594 12595 if (Opc == BO_And) 12596 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12597 12598 if (LHS.get()->getType()->hasFloatingRepresentation() || 12599 RHS.get()->getType()->hasFloatingRepresentation()) 12600 return InvalidOperands(Loc, LHS, RHS); 12601 12602 ExprResult LHSResult = LHS, RHSResult = RHS; 12603 QualType compType = UsualArithmeticConversions( 12604 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12605 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12606 return QualType(); 12607 LHS = LHSResult.get(); 12608 RHS = RHSResult.get(); 12609 12610 if (Opc == BO_Xor) 12611 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12612 12613 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12614 return compType; 12615 return InvalidOperands(Loc, LHS, RHS); 12616 } 12617 12618 // C99 6.5.[13,14] 12619 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12620 SourceLocation Loc, 12621 BinaryOperatorKind Opc) { 12622 // Check vector operands differently. 12623 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12624 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12625 12626 bool EnumConstantInBoolContext = false; 12627 for (const ExprResult &HS : {LHS, RHS}) { 12628 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12629 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12630 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12631 EnumConstantInBoolContext = true; 12632 } 12633 } 12634 12635 if (EnumConstantInBoolContext) 12636 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12637 12638 // Diagnose cases where the user write a logical and/or but probably meant a 12639 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12640 // is a constant. 12641 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12642 !LHS.get()->getType()->isBooleanType() && 12643 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12644 // Don't warn in macros or template instantiations. 12645 !Loc.isMacroID() && !inTemplateInstantiation()) { 12646 // If the RHS can be constant folded, and if it constant folds to something 12647 // that isn't 0 or 1 (which indicate a potential logical operation that 12648 // happened to fold to true/false) then warn. 12649 // Parens on the RHS are ignored. 12650 Expr::EvalResult EVResult; 12651 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12652 llvm::APSInt Result = EVResult.Val.getInt(); 12653 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12654 !RHS.get()->getExprLoc().isMacroID()) || 12655 (Result != 0 && Result != 1)) { 12656 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12657 << RHS.get()->getSourceRange() 12658 << (Opc == BO_LAnd ? "&&" : "||"); 12659 // Suggest replacing the logical operator with the bitwise version 12660 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12661 << (Opc == BO_LAnd ? "&" : "|") 12662 << FixItHint::CreateReplacement(SourceRange( 12663 Loc, getLocForEndOfToken(Loc)), 12664 Opc == BO_LAnd ? "&" : "|"); 12665 if (Opc == BO_LAnd) 12666 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12667 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12668 << FixItHint::CreateRemoval( 12669 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12670 RHS.get()->getEndLoc())); 12671 } 12672 } 12673 } 12674 12675 if (!Context.getLangOpts().CPlusPlus) { 12676 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12677 // not operate on the built-in scalar and vector float types. 12678 if (Context.getLangOpts().OpenCL && 12679 Context.getLangOpts().OpenCLVersion < 120) { 12680 if (LHS.get()->getType()->isFloatingType() || 12681 RHS.get()->getType()->isFloatingType()) 12682 return InvalidOperands(Loc, LHS, RHS); 12683 } 12684 12685 LHS = UsualUnaryConversions(LHS.get()); 12686 if (LHS.isInvalid()) 12687 return QualType(); 12688 12689 RHS = UsualUnaryConversions(RHS.get()); 12690 if (RHS.isInvalid()) 12691 return QualType(); 12692 12693 if (!LHS.get()->getType()->isScalarType() || 12694 !RHS.get()->getType()->isScalarType()) 12695 return InvalidOperands(Loc, LHS, RHS); 12696 12697 return Context.IntTy; 12698 } 12699 12700 // The following is safe because we only use this method for 12701 // non-overloadable operands. 12702 12703 // C++ [expr.log.and]p1 12704 // C++ [expr.log.or]p1 12705 // The operands are both contextually converted to type bool. 12706 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12707 if (LHSRes.isInvalid()) 12708 return InvalidOperands(Loc, LHS, RHS); 12709 LHS = LHSRes; 12710 12711 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12712 if (RHSRes.isInvalid()) 12713 return InvalidOperands(Loc, LHS, RHS); 12714 RHS = RHSRes; 12715 12716 // C++ [expr.log.and]p2 12717 // C++ [expr.log.or]p2 12718 // The result is a bool. 12719 return Context.BoolTy; 12720 } 12721 12722 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12723 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12724 if (!ME) return false; 12725 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12726 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12727 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12728 if (!Base) return false; 12729 return Base->getMethodDecl() != nullptr; 12730 } 12731 12732 /// Is the given expression (which must be 'const') a reference to a 12733 /// variable which was originally non-const, but which has become 12734 /// 'const' due to being captured within a block? 12735 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12736 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12737 assert(E->isLValue() && E->getType().isConstQualified()); 12738 E = E->IgnoreParens(); 12739 12740 // Must be a reference to a declaration from an enclosing scope. 12741 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12742 if (!DRE) return NCCK_None; 12743 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12744 12745 // The declaration must be a variable which is not declared 'const'. 12746 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12747 if (!var) return NCCK_None; 12748 if (var->getType().isConstQualified()) return NCCK_None; 12749 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12750 12751 // Decide whether the first capture was for a block or a lambda. 12752 DeclContext *DC = S.CurContext, *Prev = nullptr; 12753 // Decide whether the first capture was for a block or a lambda. 12754 while (DC) { 12755 // For init-capture, it is possible that the variable belongs to the 12756 // template pattern of the current context. 12757 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12758 if (var->isInitCapture() && 12759 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12760 break; 12761 if (DC == var->getDeclContext()) 12762 break; 12763 Prev = DC; 12764 DC = DC->getParent(); 12765 } 12766 // Unless we have an init-capture, we've gone one step too far. 12767 if (!var->isInitCapture()) 12768 DC = Prev; 12769 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12770 } 12771 12772 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12773 Ty = Ty.getNonReferenceType(); 12774 if (IsDereference && Ty->isPointerType()) 12775 Ty = Ty->getPointeeType(); 12776 return !Ty.isConstQualified(); 12777 } 12778 12779 // Update err_typecheck_assign_const and note_typecheck_assign_const 12780 // when this enum is changed. 12781 enum { 12782 ConstFunction, 12783 ConstVariable, 12784 ConstMember, 12785 ConstMethod, 12786 NestedConstMember, 12787 ConstUnknown, // Keep as last element 12788 }; 12789 12790 /// Emit the "read-only variable not assignable" error and print notes to give 12791 /// more information about why the variable is not assignable, such as pointing 12792 /// to the declaration of a const variable, showing that a method is const, or 12793 /// that the function is returning a const reference. 12794 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12795 SourceLocation Loc) { 12796 SourceRange ExprRange = E->getSourceRange(); 12797 12798 // Only emit one error on the first const found. All other consts will emit 12799 // a note to the error. 12800 bool DiagnosticEmitted = false; 12801 12802 // Track if the current expression is the result of a dereference, and if the 12803 // next checked expression is the result of a dereference. 12804 bool IsDereference = false; 12805 bool NextIsDereference = false; 12806 12807 // Loop to process MemberExpr chains. 12808 while (true) { 12809 IsDereference = NextIsDereference; 12810 12811 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12812 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12813 NextIsDereference = ME->isArrow(); 12814 const ValueDecl *VD = ME->getMemberDecl(); 12815 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12816 // Mutable fields can be modified even if the class is const. 12817 if (Field->isMutable()) { 12818 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12819 break; 12820 } 12821 12822 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12823 if (!DiagnosticEmitted) { 12824 S.Diag(Loc, diag::err_typecheck_assign_const) 12825 << ExprRange << ConstMember << false /*static*/ << Field 12826 << Field->getType(); 12827 DiagnosticEmitted = true; 12828 } 12829 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12830 << ConstMember << false /*static*/ << Field << Field->getType() 12831 << Field->getSourceRange(); 12832 } 12833 E = ME->getBase(); 12834 continue; 12835 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12836 if (VDecl->getType().isConstQualified()) { 12837 if (!DiagnosticEmitted) { 12838 S.Diag(Loc, diag::err_typecheck_assign_const) 12839 << ExprRange << ConstMember << true /*static*/ << VDecl 12840 << VDecl->getType(); 12841 DiagnosticEmitted = true; 12842 } 12843 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12844 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12845 << VDecl->getSourceRange(); 12846 } 12847 // Static fields do not inherit constness from parents. 12848 break; 12849 } 12850 break; // End MemberExpr 12851 } else if (const ArraySubscriptExpr *ASE = 12852 dyn_cast<ArraySubscriptExpr>(E)) { 12853 E = ASE->getBase()->IgnoreParenImpCasts(); 12854 continue; 12855 } else if (const ExtVectorElementExpr *EVE = 12856 dyn_cast<ExtVectorElementExpr>(E)) { 12857 E = EVE->getBase()->IgnoreParenImpCasts(); 12858 continue; 12859 } 12860 break; 12861 } 12862 12863 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12864 // Function calls 12865 const FunctionDecl *FD = CE->getDirectCallee(); 12866 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12867 if (!DiagnosticEmitted) { 12868 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12869 << ConstFunction << FD; 12870 DiagnosticEmitted = true; 12871 } 12872 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12873 diag::note_typecheck_assign_const) 12874 << ConstFunction << FD << FD->getReturnType() 12875 << FD->getReturnTypeSourceRange(); 12876 } 12877 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12878 // Point to variable declaration. 12879 if (const ValueDecl *VD = DRE->getDecl()) { 12880 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12881 if (!DiagnosticEmitted) { 12882 S.Diag(Loc, diag::err_typecheck_assign_const) 12883 << ExprRange << ConstVariable << VD << VD->getType(); 12884 DiagnosticEmitted = true; 12885 } 12886 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12887 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12888 } 12889 } 12890 } else if (isa<CXXThisExpr>(E)) { 12891 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12892 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12893 if (MD->isConst()) { 12894 if (!DiagnosticEmitted) { 12895 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12896 << ConstMethod << MD; 12897 DiagnosticEmitted = true; 12898 } 12899 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12900 << ConstMethod << MD << MD->getSourceRange(); 12901 } 12902 } 12903 } 12904 } 12905 12906 if (DiagnosticEmitted) 12907 return; 12908 12909 // Can't determine a more specific message, so display the generic error. 12910 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12911 } 12912 12913 enum OriginalExprKind { 12914 OEK_Variable, 12915 OEK_Member, 12916 OEK_LValue 12917 }; 12918 12919 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12920 const RecordType *Ty, 12921 SourceLocation Loc, SourceRange Range, 12922 OriginalExprKind OEK, 12923 bool &DiagnosticEmitted) { 12924 std::vector<const RecordType *> RecordTypeList; 12925 RecordTypeList.push_back(Ty); 12926 unsigned NextToCheckIndex = 0; 12927 // We walk the record hierarchy breadth-first to ensure that we print 12928 // diagnostics in field nesting order. 12929 while (RecordTypeList.size() > NextToCheckIndex) { 12930 bool IsNested = NextToCheckIndex > 0; 12931 for (const FieldDecl *Field : 12932 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12933 // First, check every field for constness. 12934 QualType FieldTy = Field->getType(); 12935 if (FieldTy.isConstQualified()) { 12936 if (!DiagnosticEmitted) { 12937 S.Diag(Loc, diag::err_typecheck_assign_const) 12938 << Range << NestedConstMember << OEK << VD 12939 << IsNested << Field; 12940 DiagnosticEmitted = true; 12941 } 12942 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12943 << NestedConstMember << IsNested << Field 12944 << FieldTy << Field->getSourceRange(); 12945 } 12946 12947 // Then we append it to the list to check next in order. 12948 FieldTy = FieldTy.getCanonicalType(); 12949 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12950 if (!llvm::is_contained(RecordTypeList, FieldRecTy)) 12951 RecordTypeList.push_back(FieldRecTy); 12952 } 12953 } 12954 ++NextToCheckIndex; 12955 } 12956 } 12957 12958 /// Emit an error for the case where a record we are trying to assign to has a 12959 /// const-qualified field somewhere in its hierarchy. 12960 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12961 SourceLocation Loc) { 12962 QualType Ty = E->getType(); 12963 assert(Ty->isRecordType() && "lvalue was not record?"); 12964 SourceRange Range = E->getSourceRange(); 12965 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12966 bool DiagEmitted = false; 12967 12968 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12969 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12970 Range, OEK_Member, DiagEmitted); 12971 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12972 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12973 Range, OEK_Variable, DiagEmitted); 12974 else 12975 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12976 Range, OEK_LValue, DiagEmitted); 12977 if (!DiagEmitted) 12978 DiagnoseConstAssignment(S, E, Loc); 12979 } 12980 12981 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12982 /// emit an error and return true. If so, return false. 12983 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12984 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12985 12986 S.CheckShadowingDeclModification(E, Loc); 12987 12988 SourceLocation OrigLoc = Loc; 12989 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12990 &Loc); 12991 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12992 IsLV = Expr::MLV_InvalidMessageExpression; 12993 if (IsLV == Expr::MLV_Valid) 12994 return false; 12995 12996 unsigned DiagID = 0; 12997 bool NeedType = false; 12998 switch (IsLV) { // C99 6.5.16p2 12999 case Expr::MLV_ConstQualified: 13000 // Use a specialized diagnostic when we're assigning to an object 13001 // from an enclosing function or block. 13002 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 13003 if (NCCK == NCCK_Block) 13004 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 13005 else 13006 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 13007 break; 13008 } 13009 13010 // In ARC, use some specialized diagnostics for occasions where we 13011 // infer 'const'. These are always pseudo-strong variables. 13012 if (S.getLangOpts().ObjCAutoRefCount) { 13013 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 13014 if (declRef && isa<VarDecl>(declRef->getDecl())) { 13015 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 13016 13017 // Use the normal diagnostic if it's pseudo-__strong but the 13018 // user actually wrote 'const'. 13019 if (var->isARCPseudoStrong() && 13020 (!var->getTypeSourceInfo() || 13021 !var->getTypeSourceInfo()->getType().isConstQualified())) { 13022 // There are three pseudo-strong cases: 13023 // - self 13024 ObjCMethodDecl *method = S.getCurMethodDecl(); 13025 if (method && var == method->getSelfDecl()) { 13026 DiagID = method->isClassMethod() 13027 ? diag::err_typecheck_arc_assign_self_class_method 13028 : diag::err_typecheck_arc_assign_self; 13029 13030 // - Objective-C externally_retained attribute. 13031 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 13032 isa<ParmVarDecl>(var)) { 13033 DiagID = diag::err_typecheck_arc_assign_externally_retained; 13034 13035 // - fast enumeration variables 13036 } else { 13037 DiagID = diag::err_typecheck_arr_assign_enumeration; 13038 } 13039 13040 SourceRange Assign; 13041 if (Loc != OrigLoc) 13042 Assign = SourceRange(OrigLoc, OrigLoc); 13043 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13044 // We need to preserve the AST regardless, so migration tool 13045 // can do its job. 13046 return false; 13047 } 13048 } 13049 } 13050 13051 // If none of the special cases above are triggered, then this is a 13052 // simple const assignment. 13053 if (DiagID == 0) { 13054 DiagnoseConstAssignment(S, E, Loc); 13055 return true; 13056 } 13057 13058 break; 13059 case Expr::MLV_ConstAddrSpace: 13060 DiagnoseConstAssignment(S, E, Loc); 13061 return true; 13062 case Expr::MLV_ConstQualifiedField: 13063 DiagnoseRecursiveConstFields(S, E, Loc); 13064 return true; 13065 case Expr::MLV_ArrayType: 13066 case Expr::MLV_ArrayTemporary: 13067 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 13068 NeedType = true; 13069 break; 13070 case Expr::MLV_NotObjectType: 13071 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 13072 NeedType = true; 13073 break; 13074 case Expr::MLV_LValueCast: 13075 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 13076 break; 13077 case Expr::MLV_Valid: 13078 llvm_unreachable("did not take early return for MLV_Valid"); 13079 case Expr::MLV_InvalidExpression: 13080 case Expr::MLV_MemberFunction: 13081 case Expr::MLV_ClassTemporary: 13082 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 13083 break; 13084 case Expr::MLV_IncompleteType: 13085 case Expr::MLV_IncompleteVoidType: 13086 return S.RequireCompleteType(Loc, E->getType(), 13087 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 13088 case Expr::MLV_DuplicateVectorComponents: 13089 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 13090 break; 13091 case Expr::MLV_NoSetterProperty: 13092 llvm_unreachable("readonly properties should be processed differently"); 13093 case Expr::MLV_InvalidMessageExpression: 13094 DiagID = diag::err_readonly_message_assignment; 13095 break; 13096 case Expr::MLV_SubObjCPropertySetting: 13097 DiagID = diag::err_no_subobject_property_setting; 13098 break; 13099 } 13100 13101 SourceRange Assign; 13102 if (Loc != OrigLoc) 13103 Assign = SourceRange(OrigLoc, OrigLoc); 13104 if (NeedType) 13105 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 13106 else 13107 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13108 return true; 13109 } 13110 13111 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 13112 SourceLocation Loc, 13113 Sema &Sema) { 13114 if (Sema.inTemplateInstantiation()) 13115 return; 13116 if (Sema.isUnevaluatedContext()) 13117 return; 13118 if (Loc.isInvalid() || Loc.isMacroID()) 13119 return; 13120 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 13121 return; 13122 13123 // C / C++ fields 13124 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 13125 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 13126 if (ML && MR) { 13127 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 13128 return; 13129 const ValueDecl *LHSDecl = 13130 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 13131 const ValueDecl *RHSDecl = 13132 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13133 if (LHSDecl != RHSDecl) 13134 return; 13135 if (LHSDecl->getType().isVolatileQualified()) 13136 return; 13137 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13138 if (RefTy->getPointeeType().isVolatileQualified()) 13139 return; 13140 13141 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13142 } 13143 13144 // Objective-C instance variables 13145 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13146 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13147 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13148 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13149 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13150 if (RL && RR && RL->getDecl() == RR->getDecl()) 13151 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13152 } 13153 } 13154 13155 // C99 6.5.16.1 13156 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13157 SourceLocation Loc, 13158 QualType CompoundType) { 13159 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13160 13161 // Verify that LHS is a modifiable lvalue, and emit error if not. 13162 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13163 return QualType(); 13164 13165 QualType LHSType = LHSExpr->getType(); 13166 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13167 CompoundType; 13168 // OpenCL v1.2 s6.1.1.1 p2: 13169 // The half data type can only be used to declare a pointer to a buffer that 13170 // contains half values 13171 if (getLangOpts().OpenCL && 13172 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13173 LHSType->isHalfType()) { 13174 Diag(Loc, diag::err_opencl_half_load_store) << 1 13175 << LHSType.getUnqualifiedType(); 13176 return QualType(); 13177 } 13178 13179 AssignConvertType ConvTy; 13180 if (CompoundType.isNull()) { 13181 Expr *RHSCheck = RHS.get(); 13182 13183 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13184 13185 QualType LHSTy(LHSType); 13186 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13187 if (RHS.isInvalid()) 13188 return QualType(); 13189 // Special case of NSObject attributes on c-style pointer types. 13190 if (ConvTy == IncompatiblePointer && 13191 ((Context.isObjCNSObjectType(LHSType) && 13192 RHSType->isObjCObjectPointerType()) || 13193 (Context.isObjCNSObjectType(RHSType) && 13194 LHSType->isObjCObjectPointerType()))) 13195 ConvTy = Compatible; 13196 13197 if (ConvTy == Compatible && 13198 LHSType->isObjCObjectType()) 13199 Diag(Loc, diag::err_objc_object_assignment) 13200 << LHSType; 13201 13202 // If the RHS is a unary plus or minus, check to see if they = and + are 13203 // right next to each other. If so, the user may have typo'd "x =+ 4" 13204 // instead of "x += 4". 13205 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13206 RHSCheck = ICE->getSubExpr(); 13207 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13208 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13209 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13210 // Only if the two operators are exactly adjacent. 13211 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13212 // And there is a space or other character before the subexpr of the 13213 // unary +/-. We don't want to warn on "x=-1". 13214 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13215 UO->getSubExpr()->getBeginLoc().isFileID()) { 13216 Diag(Loc, diag::warn_not_compound_assign) 13217 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13218 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13219 } 13220 } 13221 13222 if (ConvTy == Compatible) { 13223 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13224 // Warn about retain cycles where a block captures the LHS, but 13225 // not if the LHS is a simple variable into which the block is 13226 // being stored...unless that variable can be captured by reference! 13227 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13228 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13229 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13230 checkRetainCycles(LHSExpr, RHS.get()); 13231 } 13232 13233 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13234 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13235 // It is safe to assign a weak reference into a strong variable. 13236 // Although this code can still have problems: 13237 // id x = self.weakProp; 13238 // id y = self.weakProp; 13239 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13240 // paths through the function. This should be revisited if 13241 // -Wrepeated-use-of-weak is made flow-sensitive. 13242 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13243 // variable, which will be valid for the current autorelease scope. 13244 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13245 RHS.get()->getBeginLoc())) 13246 getCurFunction()->markSafeWeakUse(RHS.get()); 13247 13248 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13249 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13250 } 13251 } 13252 } else { 13253 // Compound assignment "x += y" 13254 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13255 } 13256 13257 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13258 RHS.get(), AA_Assigning)) 13259 return QualType(); 13260 13261 CheckForNullPointerDereference(*this, LHSExpr); 13262 13263 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13264 if (CompoundType.isNull()) { 13265 // C++2a [expr.ass]p5: 13266 // A simple-assignment whose left operand is of a volatile-qualified 13267 // type is deprecated unless the assignment is either a discarded-value 13268 // expression or an unevaluated operand 13269 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13270 } else { 13271 // C++2a [expr.ass]p6: 13272 // [Compound-assignment] expressions are deprecated if E1 has 13273 // volatile-qualified type 13274 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13275 } 13276 } 13277 13278 // C99 6.5.16p3: The type of an assignment expression is the type of the 13279 // left operand unless the left operand has qualified type, in which case 13280 // it is the unqualified version of the type of the left operand. 13281 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13282 // is converted to the type of the assignment expression (above). 13283 // C++ 5.17p1: the type of the assignment expression is that of its left 13284 // operand. 13285 return (getLangOpts().CPlusPlus 13286 ? LHSType : LHSType.getUnqualifiedType()); 13287 } 13288 13289 // Only ignore explicit casts to void. 13290 static bool IgnoreCommaOperand(const Expr *E) { 13291 E = E->IgnoreParens(); 13292 13293 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13294 if (CE->getCastKind() == CK_ToVoid) { 13295 return true; 13296 } 13297 13298 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13299 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13300 CE->getSubExpr()->getType()->isDependentType()) { 13301 return true; 13302 } 13303 } 13304 13305 return false; 13306 } 13307 13308 // Look for instances where it is likely the comma operator is confused with 13309 // another operator. There is an explicit list of acceptable expressions for 13310 // the left hand side of the comma operator, otherwise emit a warning. 13311 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13312 // No warnings in macros 13313 if (Loc.isMacroID()) 13314 return; 13315 13316 // Don't warn in template instantiations. 13317 if (inTemplateInstantiation()) 13318 return; 13319 13320 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13321 // instead, skip more than needed, then call back into here with the 13322 // CommaVisitor in SemaStmt.cpp. 13323 // The listed locations are the initialization and increment portions 13324 // of a for loop. The additional checks are on the condition of 13325 // if statements, do/while loops, and for loops. 13326 // Differences in scope flags for C89 mode requires the extra logic. 13327 const unsigned ForIncrementFlags = 13328 getLangOpts().C99 || getLangOpts().CPlusPlus 13329 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13330 : Scope::ContinueScope | Scope::BreakScope; 13331 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13332 const unsigned ScopeFlags = getCurScope()->getFlags(); 13333 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13334 (ScopeFlags & ForInitFlags) == ForInitFlags) 13335 return; 13336 13337 // If there are multiple comma operators used together, get the RHS of the 13338 // of the comma operator as the LHS. 13339 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13340 if (BO->getOpcode() != BO_Comma) 13341 break; 13342 LHS = BO->getRHS(); 13343 } 13344 13345 // Only allow some expressions on LHS to not warn. 13346 if (IgnoreCommaOperand(LHS)) 13347 return; 13348 13349 Diag(Loc, diag::warn_comma_operator); 13350 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13351 << LHS->getSourceRange() 13352 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13353 LangOpts.CPlusPlus ? "static_cast<void>(" 13354 : "(void)(") 13355 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13356 ")"); 13357 } 13358 13359 // C99 6.5.17 13360 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13361 SourceLocation Loc) { 13362 LHS = S.CheckPlaceholderExpr(LHS.get()); 13363 RHS = S.CheckPlaceholderExpr(RHS.get()); 13364 if (LHS.isInvalid() || RHS.isInvalid()) 13365 return QualType(); 13366 13367 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13368 // operands, but not unary promotions. 13369 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13370 13371 // So we treat the LHS as a ignored value, and in C++ we allow the 13372 // containing site to determine what should be done with the RHS. 13373 LHS = S.IgnoredValueConversions(LHS.get()); 13374 if (LHS.isInvalid()) 13375 return QualType(); 13376 13377 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand); 13378 13379 if (!S.getLangOpts().CPlusPlus) { 13380 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13381 if (RHS.isInvalid()) 13382 return QualType(); 13383 if (!RHS.get()->getType()->isVoidType()) 13384 S.RequireCompleteType(Loc, RHS.get()->getType(), 13385 diag::err_incomplete_type); 13386 } 13387 13388 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13389 S.DiagnoseCommaOperator(LHS.get(), Loc); 13390 13391 return RHS.get()->getType(); 13392 } 13393 13394 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13395 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13396 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13397 ExprValueKind &VK, 13398 ExprObjectKind &OK, 13399 SourceLocation OpLoc, 13400 bool IsInc, bool IsPrefix) { 13401 if (Op->isTypeDependent()) 13402 return S.Context.DependentTy; 13403 13404 QualType ResType = Op->getType(); 13405 // Atomic types can be used for increment / decrement where the non-atomic 13406 // versions can, so ignore the _Atomic() specifier for the purpose of 13407 // checking. 13408 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13409 ResType = ResAtomicType->getValueType(); 13410 13411 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13412 13413 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13414 // Decrement of bool is not allowed. 13415 if (!IsInc) { 13416 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13417 return QualType(); 13418 } 13419 // Increment of bool sets it to true, but is deprecated. 13420 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13421 : diag::warn_increment_bool) 13422 << Op->getSourceRange(); 13423 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13424 // Error on enum increments and decrements in C++ mode 13425 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13426 return QualType(); 13427 } else if (ResType->isRealType()) { 13428 // OK! 13429 } else if (ResType->isPointerType()) { 13430 // C99 6.5.2.4p2, 6.5.6p2 13431 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13432 return QualType(); 13433 } else if (ResType->isObjCObjectPointerType()) { 13434 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13435 // Otherwise, we just need a complete type. 13436 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13437 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13438 return QualType(); 13439 } else if (ResType->isAnyComplexType()) { 13440 // C99 does not support ++/-- on complex types, we allow as an extension. 13441 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13442 << ResType << Op->getSourceRange(); 13443 } else if (ResType->isPlaceholderType()) { 13444 ExprResult PR = S.CheckPlaceholderExpr(Op); 13445 if (PR.isInvalid()) return QualType(); 13446 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13447 IsInc, IsPrefix); 13448 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13449 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13450 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13451 (ResType->castAs<VectorType>()->getVectorKind() != 13452 VectorType::AltiVecBool)) { 13453 // The z vector extensions allow ++ and -- for non-bool vectors. 13454 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13455 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13456 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13457 } else { 13458 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13459 << ResType << int(IsInc) << Op->getSourceRange(); 13460 return QualType(); 13461 } 13462 // At this point, we know we have a real, complex or pointer type. 13463 // Now make sure the operand is a modifiable lvalue. 13464 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13465 return QualType(); 13466 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13467 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13468 // An operand with volatile-qualified type is deprecated 13469 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13470 << IsInc << ResType; 13471 } 13472 // In C++, a prefix increment is the same type as the operand. Otherwise 13473 // (in C or with postfix), the increment is the unqualified type of the 13474 // operand. 13475 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13476 VK = VK_LValue; 13477 OK = Op->getObjectKind(); 13478 return ResType; 13479 } else { 13480 VK = VK_PRValue; 13481 return ResType.getUnqualifiedType(); 13482 } 13483 } 13484 13485 13486 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13487 /// This routine allows us to typecheck complex/recursive expressions 13488 /// where the declaration is needed for type checking. We only need to 13489 /// handle cases when the expression references a function designator 13490 /// or is an lvalue. Here are some examples: 13491 /// - &(x) => x 13492 /// - &*****f => f for f a function designator. 13493 /// - &s.xx => s 13494 /// - &s.zz[1].yy -> s, if zz is an array 13495 /// - *(x + 1) -> x, if x is an array 13496 /// - &"123"[2] -> 0 13497 /// - & __real__ x -> x 13498 /// 13499 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13500 /// members. 13501 static ValueDecl *getPrimaryDecl(Expr *E) { 13502 switch (E->getStmtClass()) { 13503 case Stmt::DeclRefExprClass: 13504 return cast<DeclRefExpr>(E)->getDecl(); 13505 case Stmt::MemberExprClass: 13506 // If this is an arrow operator, the address is an offset from 13507 // the base's value, so the object the base refers to is 13508 // irrelevant. 13509 if (cast<MemberExpr>(E)->isArrow()) 13510 return nullptr; 13511 // Otherwise, the expression refers to a part of the base 13512 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13513 case Stmt::ArraySubscriptExprClass: { 13514 // FIXME: This code shouldn't be necessary! We should catch the implicit 13515 // promotion of register arrays earlier. 13516 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13517 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13518 if (ICE->getSubExpr()->getType()->isArrayType()) 13519 return getPrimaryDecl(ICE->getSubExpr()); 13520 } 13521 return nullptr; 13522 } 13523 case Stmt::UnaryOperatorClass: { 13524 UnaryOperator *UO = cast<UnaryOperator>(E); 13525 13526 switch(UO->getOpcode()) { 13527 case UO_Real: 13528 case UO_Imag: 13529 case UO_Extension: 13530 return getPrimaryDecl(UO->getSubExpr()); 13531 default: 13532 return nullptr; 13533 } 13534 } 13535 case Stmt::ParenExprClass: 13536 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13537 case Stmt::ImplicitCastExprClass: 13538 // If the result of an implicit cast is an l-value, we care about 13539 // the sub-expression; otherwise, the result here doesn't matter. 13540 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13541 case Stmt::CXXUuidofExprClass: 13542 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13543 default: 13544 return nullptr; 13545 } 13546 } 13547 13548 namespace { 13549 enum { 13550 AO_Bit_Field = 0, 13551 AO_Vector_Element = 1, 13552 AO_Property_Expansion = 2, 13553 AO_Register_Variable = 3, 13554 AO_Matrix_Element = 4, 13555 AO_No_Error = 5 13556 }; 13557 } 13558 /// Diagnose invalid operand for address of operations. 13559 /// 13560 /// \param Type The type of operand which cannot have its address taken. 13561 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13562 Expr *E, unsigned Type) { 13563 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13564 } 13565 13566 /// CheckAddressOfOperand - The operand of & must be either a function 13567 /// designator or an lvalue designating an object. If it is an lvalue, the 13568 /// object cannot be declared with storage class register or be a bit field. 13569 /// Note: The usual conversions are *not* applied to the operand of the & 13570 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13571 /// In C++, the operand might be an overloaded function name, in which case 13572 /// we allow the '&' but retain the overloaded-function type. 13573 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13574 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13575 if (PTy->getKind() == BuiltinType::Overload) { 13576 Expr *E = OrigOp.get()->IgnoreParens(); 13577 if (!isa<OverloadExpr>(E)) { 13578 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13579 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13580 << OrigOp.get()->getSourceRange(); 13581 return QualType(); 13582 } 13583 13584 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13585 if (isa<UnresolvedMemberExpr>(Ovl)) 13586 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13587 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13588 << OrigOp.get()->getSourceRange(); 13589 return QualType(); 13590 } 13591 13592 return Context.OverloadTy; 13593 } 13594 13595 if (PTy->getKind() == BuiltinType::UnknownAny) 13596 return Context.UnknownAnyTy; 13597 13598 if (PTy->getKind() == BuiltinType::BoundMember) { 13599 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13600 << OrigOp.get()->getSourceRange(); 13601 return QualType(); 13602 } 13603 13604 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13605 if (OrigOp.isInvalid()) return QualType(); 13606 } 13607 13608 if (OrigOp.get()->isTypeDependent()) 13609 return Context.DependentTy; 13610 13611 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13612 13613 // Make sure to ignore parentheses in subsequent checks 13614 Expr *op = OrigOp.get()->IgnoreParens(); 13615 13616 // In OpenCL captures for blocks called as lambda functions 13617 // are located in the private address space. Blocks used in 13618 // enqueue_kernel can be located in a different address space 13619 // depending on a vendor implementation. Thus preventing 13620 // taking an address of the capture to avoid invalid AS casts. 13621 if (LangOpts.OpenCL) { 13622 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13623 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13624 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13625 return QualType(); 13626 } 13627 } 13628 13629 if (getLangOpts().C99) { 13630 // Implement C99-only parts of addressof rules. 13631 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13632 if (uOp->getOpcode() == UO_Deref) 13633 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13634 // (assuming the deref expression is valid). 13635 return uOp->getSubExpr()->getType(); 13636 } 13637 // Technically, there should be a check for array subscript 13638 // expressions here, but the result of one is always an lvalue anyway. 13639 } 13640 ValueDecl *dcl = getPrimaryDecl(op); 13641 13642 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13643 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13644 op->getBeginLoc())) 13645 return QualType(); 13646 13647 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13648 unsigned AddressOfError = AO_No_Error; 13649 13650 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13651 bool sfinae = (bool)isSFINAEContext(); 13652 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13653 : diag::ext_typecheck_addrof_temporary) 13654 << op->getType() << op->getSourceRange(); 13655 if (sfinae) 13656 return QualType(); 13657 // Materialize the temporary as an lvalue so that we can take its address. 13658 OrigOp = op = 13659 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13660 } else if (isa<ObjCSelectorExpr>(op)) { 13661 return Context.getPointerType(op->getType()); 13662 } else if (lval == Expr::LV_MemberFunction) { 13663 // If it's an instance method, make a member pointer. 13664 // The expression must have exactly the form &A::foo. 13665 13666 // If the underlying expression isn't a decl ref, give up. 13667 if (!isa<DeclRefExpr>(op)) { 13668 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13669 << OrigOp.get()->getSourceRange(); 13670 return QualType(); 13671 } 13672 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13673 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13674 13675 // The id-expression was parenthesized. 13676 if (OrigOp.get() != DRE) { 13677 Diag(OpLoc, diag::err_parens_pointer_member_function) 13678 << OrigOp.get()->getSourceRange(); 13679 13680 // The method was named without a qualifier. 13681 } else if (!DRE->getQualifier()) { 13682 if (MD->getParent()->getName().empty()) 13683 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13684 << op->getSourceRange(); 13685 else { 13686 SmallString<32> Str; 13687 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13688 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13689 << op->getSourceRange() 13690 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13691 } 13692 } 13693 13694 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13695 if (isa<CXXDestructorDecl>(MD)) 13696 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13697 13698 QualType MPTy = Context.getMemberPointerType( 13699 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13700 // Under the MS ABI, lock down the inheritance model now. 13701 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13702 (void)isCompleteType(OpLoc, MPTy); 13703 return MPTy; 13704 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13705 // C99 6.5.3.2p1 13706 // The operand must be either an l-value or a function designator 13707 if (!op->getType()->isFunctionType()) { 13708 // Use a special diagnostic for loads from property references. 13709 if (isa<PseudoObjectExpr>(op)) { 13710 AddressOfError = AO_Property_Expansion; 13711 } else { 13712 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13713 << op->getType() << op->getSourceRange(); 13714 return QualType(); 13715 } 13716 } 13717 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13718 // The operand cannot be a bit-field 13719 AddressOfError = AO_Bit_Field; 13720 } else if (op->getObjectKind() == OK_VectorComponent) { 13721 // The operand cannot be an element of a vector 13722 AddressOfError = AO_Vector_Element; 13723 } else if (op->getObjectKind() == OK_MatrixComponent) { 13724 // The operand cannot be an element of a matrix. 13725 AddressOfError = AO_Matrix_Element; 13726 } else if (dcl) { // C99 6.5.3.2p1 13727 // We have an lvalue with a decl. Make sure the decl is not declared 13728 // with the register storage-class specifier. 13729 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13730 // in C++ it is not error to take address of a register 13731 // variable (c++03 7.1.1P3) 13732 if (vd->getStorageClass() == SC_Register && 13733 !getLangOpts().CPlusPlus) { 13734 AddressOfError = AO_Register_Variable; 13735 } 13736 } else if (isa<MSPropertyDecl>(dcl)) { 13737 AddressOfError = AO_Property_Expansion; 13738 } else if (isa<FunctionTemplateDecl>(dcl)) { 13739 return Context.OverloadTy; 13740 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13741 // Okay: we can take the address of a field. 13742 // Could be a pointer to member, though, if there is an explicit 13743 // scope qualifier for the class. 13744 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13745 DeclContext *Ctx = dcl->getDeclContext(); 13746 if (Ctx && Ctx->isRecord()) { 13747 if (dcl->getType()->isReferenceType()) { 13748 Diag(OpLoc, 13749 diag::err_cannot_form_pointer_to_member_of_reference_type) 13750 << dcl->getDeclName() << dcl->getType(); 13751 return QualType(); 13752 } 13753 13754 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13755 Ctx = Ctx->getParent(); 13756 13757 QualType MPTy = Context.getMemberPointerType( 13758 op->getType(), 13759 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13760 // Under the MS ABI, lock down the inheritance model now. 13761 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13762 (void)isCompleteType(OpLoc, MPTy); 13763 return MPTy; 13764 } 13765 } 13766 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13767 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13768 llvm_unreachable("Unknown/unexpected decl type"); 13769 } 13770 13771 if (AddressOfError != AO_No_Error) { 13772 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13773 return QualType(); 13774 } 13775 13776 if (lval == Expr::LV_IncompleteVoidType) { 13777 // Taking the address of a void variable is technically illegal, but we 13778 // allow it in cases which are otherwise valid. 13779 // Example: "extern void x; void* y = &x;". 13780 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13781 } 13782 13783 // If the operand has type "type", the result has type "pointer to type". 13784 if (op->getType()->isObjCObjectType()) 13785 return Context.getObjCObjectPointerType(op->getType()); 13786 13787 CheckAddressOfPackedMember(op); 13788 13789 return Context.getPointerType(op->getType()); 13790 } 13791 13792 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13793 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13794 if (!DRE) 13795 return; 13796 const Decl *D = DRE->getDecl(); 13797 if (!D) 13798 return; 13799 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13800 if (!Param) 13801 return; 13802 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13803 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13804 return; 13805 if (FunctionScopeInfo *FD = S.getCurFunction()) 13806 if (!FD->ModifiedNonNullParams.count(Param)) 13807 FD->ModifiedNonNullParams.insert(Param); 13808 } 13809 13810 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13811 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13812 SourceLocation OpLoc) { 13813 if (Op->isTypeDependent()) 13814 return S.Context.DependentTy; 13815 13816 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13817 if (ConvResult.isInvalid()) 13818 return QualType(); 13819 Op = ConvResult.get(); 13820 QualType OpTy = Op->getType(); 13821 QualType Result; 13822 13823 if (isa<CXXReinterpretCastExpr>(Op)) { 13824 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13825 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13826 Op->getSourceRange()); 13827 } 13828 13829 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13830 { 13831 Result = PT->getPointeeType(); 13832 } 13833 else if (const ObjCObjectPointerType *OPT = 13834 OpTy->getAs<ObjCObjectPointerType>()) 13835 Result = OPT->getPointeeType(); 13836 else { 13837 ExprResult PR = S.CheckPlaceholderExpr(Op); 13838 if (PR.isInvalid()) return QualType(); 13839 if (PR.get() != Op) 13840 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13841 } 13842 13843 if (Result.isNull()) { 13844 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13845 << OpTy << Op->getSourceRange(); 13846 return QualType(); 13847 } 13848 13849 // Note that per both C89 and C99, indirection is always legal, even if Result 13850 // is an incomplete type or void. It would be possible to warn about 13851 // dereferencing a void pointer, but it's completely well-defined, and such a 13852 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13853 // for pointers to 'void' but is fine for any other pointer type: 13854 // 13855 // C++ [expr.unary.op]p1: 13856 // [...] the expression to which [the unary * operator] is applied shall 13857 // be a pointer to an object type, or a pointer to a function type 13858 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13859 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13860 << OpTy << Op->getSourceRange(); 13861 13862 // Dereferences are usually l-values... 13863 VK = VK_LValue; 13864 13865 // ...except that certain expressions are never l-values in C. 13866 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13867 VK = VK_PRValue; 13868 13869 return Result; 13870 } 13871 13872 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13873 BinaryOperatorKind Opc; 13874 switch (Kind) { 13875 default: llvm_unreachable("Unknown binop!"); 13876 case tok::periodstar: Opc = BO_PtrMemD; break; 13877 case tok::arrowstar: Opc = BO_PtrMemI; break; 13878 case tok::star: Opc = BO_Mul; break; 13879 case tok::slash: Opc = BO_Div; break; 13880 case tok::percent: Opc = BO_Rem; break; 13881 case tok::plus: Opc = BO_Add; break; 13882 case tok::minus: Opc = BO_Sub; break; 13883 case tok::lessless: Opc = BO_Shl; break; 13884 case tok::greatergreater: Opc = BO_Shr; break; 13885 case tok::lessequal: Opc = BO_LE; break; 13886 case tok::less: Opc = BO_LT; break; 13887 case tok::greaterequal: Opc = BO_GE; break; 13888 case tok::greater: Opc = BO_GT; break; 13889 case tok::exclaimequal: Opc = BO_NE; break; 13890 case tok::equalequal: Opc = BO_EQ; break; 13891 case tok::spaceship: Opc = BO_Cmp; break; 13892 case tok::amp: Opc = BO_And; break; 13893 case tok::caret: Opc = BO_Xor; break; 13894 case tok::pipe: Opc = BO_Or; break; 13895 case tok::ampamp: Opc = BO_LAnd; break; 13896 case tok::pipepipe: Opc = BO_LOr; break; 13897 case tok::equal: Opc = BO_Assign; break; 13898 case tok::starequal: Opc = BO_MulAssign; break; 13899 case tok::slashequal: Opc = BO_DivAssign; break; 13900 case tok::percentequal: Opc = BO_RemAssign; break; 13901 case tok::plusequal: Opc = BO_AddAssign; break; 13902 case tok::minusequal: Opc = BO_SubAssign; break; 13903 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13904 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13905 case tok::ampequal: Opc = BO_AndAssign; break; 13906 case tok::caretequal: Opc = BO_XorAssign; break; 13907 case tok::pipeequal: Opc = BO_OrAssign; break; 13908 case tok::comma: Opc = BO_Comma; break; 13909 } 13910 return Opc; 13911 } 13912 13913 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13914 tok::TokenKind Kind) { 13915 UnaryOperatorKind Opc; 13916 switch (Kind) { 13917 default: llvm_unreachable("Unknown unary op!"); 13918 case tok::plusplus: Opc = UO_PreInc; break; 13919 case tok::minusminus: Opc = UO_PreDec; break; 13920 case tok::amp: Opc = UO_AddrOf; break; 13921 case tok::star: Opc = UO_Deref; break; 13922 case tok::plus: Opc = UO_Plus; break; 13923 case tok::minus: Opc = UO_Minus; break; 13924 case tok::tilde: Opc = UO_Not; break; 13925 case tok::exclaim: Opc = UO_LNot; break; 13926 case tok::kw___real: Opc = UO_Real; break; 13927 case tok::kw___imag: Opc = UO_Imag; break; 13928 case tok::kw___extension__: Opc = UO_Extension; break; 13929 } 13930 return Opc; 13931 } 13932 13933 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13934 /// This warning suppressed in the event of macro expansions. 13935 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13936 SourceLocation OpLoc, bool IsBuiltin) { 13937 if (S.inTemplateInstantiation()) 13938 return; 13939 if (S.isUnevaluatedContext()) 13940 return; 13941 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13942 return; 13943 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13944 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13945 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13946 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13947 if (!LHSDeclRef || !RHSDeclRef || 13948 LHSDeclRef->getLocation().isMacroID() || 13949 RHSDeclRef->getLocation().isMacroID()) 13950 return; 13951 const ValueDecl *LHSDecl = 13952 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13953 const ValueDecl *RHSDecl = 13954 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13955 if (LHSDecl != RHSDecl) 13956 return; 13957 if (LHSDecl->getType().isVolatileQualified()) 13958 return; 13959 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13960 if (RefTy->getPointeeType().isVolatileQualified()) 13961 return; 13962 13963 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13964 : diag::warn_self_assignment_overloaded) 13965 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13966 << RHSExpr->getSourceRange(); 13967 } 13968 13969 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13970 /// is usually indicative of introspection within the Objective-C pointer. 13971 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13972 SourceLocation OpLoc) { 13973 if (!S.getLangOpts().ObjC) 13974 return; 13975 13976 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13977 const Expr *LHS = L.get(); 13978 const Expr *RHS = R.get(); 13979 13980 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13981 ObjCPointerExpr = LHS; 13982 OtherExpr = RHS; 13983 } 13984 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13985 ObjCPointerExpr = RHS; 13986 OtherExpr = LHS; 13987 } 13988 13989 // This warning is deliberately made very specific to reduce false 13990 // positives with logic that uses '&' for hashing. This logic mainly 13991 // looks for code trying to introspect into tagged pointers, which 13992 // code should generally never do. 13993 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13994 unsigned Diag = diag::warn_objc_pointer_masking; 13995 // Determine if we are introspecting the result of performSelectorXXX. 13996 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13997 // Special case messages to -performSelector and friends, which 13998 // can return non-pointer values boxed in a pointer value. 13999 // Some clients may wish to silence warnings in this subcase. 14000 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 14001 Selector S = ME->getSelector(); 14002 StringRef SelArg0 = S.getNameForSlot(0); 14003 if (SelArg0.startswith("performSelector")) 14004 Diag = diag::warn_objc_pointer_masking_performSelector; 14005 } 14006 14007 S.Diag(OpLoc, Diag) 14008 << ObjCPointerExpr->getSourceRange(); 14009 } 14010 } 14011 14012 static NamedDecl *getDeclFromExpr(Expr *E) { 14013 if (!E) 14014 return nullptr; 14015 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 14016 return DRE->getDecl(); 14017 if (auto *ME = dyn_cast<MemberExpr>(E)) 14018 return ME->getMemberDecl(); 14019 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 14020 return IRE->getDecl(); 14021 return nullptr; 14022 } 14023 14024 // This helper function promotes a binary operator's operands (which are of a 14025 // half vector type) to a vector of floats and then truncates the result to 14026 // a vector of either half or short. 14027 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 14028 BinaryOperatorKind Opc, QualType ResultTy, 14029 ExprValueKind VK, ExprObjectKind OK, 14030 bool IsCompAssign, SourceLocation OpLoc, 14031 FPOptionsOverride FPFeatures) { 14032 auto &Context = S.getASTContext(); 14033 assert((isVector(ResultTy, Context.HalfTy) || 14034 isVector(ResultTy, Context.ShortTy)) && 14035 "Result must be a vector of half or short"); 14036 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 14037 isVector(RHS.get()->getType(), Context.HalfTy) && 14038 "both operands expected to be a half vector"); 14039 14040 RHS = convertVector(RHS.get(), Context.FloatTy, S); 14041 QualType BinOpResTy = RHS.get()->getType(); 14042 14043 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 14044 // change BinOpResTy to a vector of ints. 14045 if (isVector(ResultTy, Context.ShortTy)) 14046 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 14047 14048 if (IsCompAssign) 14049 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14050 ResultTy, VK, OK, OpLoc, FPFeatures, 14051 BinOpResTy, BinOpResTy); 14052 14053 LHS = convertVector(LHS.get(), Context.FloatTy, S); 14054 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14055 BinOpResTy, VK, OK, OpLoc, FPFeatures); 14056 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 14057 } 14058 14059 static std::pair<ExprResult, ExprResult> 14060 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 14061 Expr *RHSExpr) { 14062 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14063 if (!S.Context.isDependenceAllowed()) { 14064 // C cannot handle TypoExpr nodes on either side of a binop because it 14065 // doesn't handle dependent types properly, so make sure any TypoExprs have 14066 // been dealt with before checking the operands. 14067 LHS = S.CorrectDelayedTyposInExpr(LHS); 14068 RHS = S.CorrectDelayedTyposInExpr( 14069 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 14070 [Opc, LHS](Expr *E) { 14071 if (Opc != BO_Assign) 14072 return ExprResult(E); 14073 // Avoid correcting the RHS to the same Expr as the LHS. 14074 Decl *D = getDeclFromExpr(E); 14075 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 14076 }); 14077 } 14078 return std::make_pair(LHS, RHS); 14079 } 14080 14081 /// Returns true if conversion between vectors of halfs and vectors of floats 14082 /// is needed. 14083 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 14084 Expr *E0, Expr *E1 = nullptr) { 14085 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 14086 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 14087 return false; 14088 14089 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 14090 QualType Ty = E->IgnoreImplicit()->getType(); 14091 14092 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 14093 // to vectors of floats. Although the element type of the vectors is __fp16, 14094 // the vectors shouldn't be treated as storage-only types. See the 14095 // discussion here: https://reviews.llvm.org/rG825235c140e7 14096 if (const VectorType *VT = Ty->getAs<VectorType>()) { 14097 if (VT->getVectorKind() == VectorType::NeonVector) 14098 return false; 14099 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 14100 } 14101 return false; 14102 }; 14103 14104 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 14105 } 14106 14107 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 14108 /// operator @p Opc at location @c TokLoc. This routine only supports 14109 /// built-in operations; ActOnBinOp handles overloaded operators. 14110 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 14111 BinaryOperatorKind Opc, 14112 Expr *LHSExpr, Expr *RHSExpr) { 14113 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 14114 // The syntax only allows initializer lists on the RHS of assignment, 14115 // so we don't need to worry about accepting invalid code for 14116 // non-assignment operators. 14117 // C++11 5.17p9: 14118 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 14119 // of x = {} is x = T(). 14120 InitializationKind Kind = InitializationKind::CreateDirectList( 14121 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14122 InitializedEntity Entity = 14123 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 14124 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 14125 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 14126 if (Init.isInvalid()) 14127 return Init; 14128 RHSExpr = Init.get(); 14129 } 14130 14131 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14132 QualType ResultTy; // Result type of the binary operator. 14133 // The following two variables are used for compound assignment operators 14134 QualType CompLHSTy; // Type of LHS after promotions for computation 14135 QualType CompResultTy; // Type of computation result 14136 ExprValueKind VK = VK_PRValue; 14137 ExprObjectKind OK = OK_Ordinary; 14138 bool ConvertHalfVec = false; 14139 14140 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14141 if (!LHS.isUsable() || !RHS.isUsable()) 14142 return ExprError(); 14143 14144 if (getLangOpts().OpenCL) { 14145 QualType LHSTy = LHSExpr->getType(); 14146 QualType RHSTy = RHSExpr->getType(); 14147 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14148 // the ATOMIC_VAR_INIT macro. 14149 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14150 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14151 if (BO_Assign == Opc) 14152 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14153 else 14154 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14155 return ExprError(); 14156 } 14157 14158 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14159 // only with a builtin functions and therefore should be disallowed here. 14160 if (LHSTy->isImageType() || RHSTy->isImageType() || 14161 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14162 LHSTy->isPipeType() || RHSTy->isPipeType() || 14163 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14164 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14165 return ExprError(); 14166 } 14167 } 14168 14169 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14170 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14171 14172 switch (Opc) { 14173 case BO_Assign: 14174 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14175 if (getLangOpts().CPlusPlus && 14176 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14177 VK = LHS.get()->getValueKind(); 14178 OK = LHS.get()->getObjectKind(); 14179 } 14180 if (!ResultTy.isNull()) { 14181 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14182 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14183 14184 // Avoid copying a block to the heap if the block is assigned to a local 14185 // auto variable that is declared in the same scope as the block. This 14186 // optimization is unsafe if the local variable is declared in an outer 14187 // scope. For example: 14188 // 14189 // BlockTy b; 14190 // { 14191 // b = ^{...}; 14192 // } 14193 // // It is unsafe to invoke the block here if it wasn't copied to the 14194 // // heap. 14195 // b(); 14196 14197 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14198 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14199 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14200 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14201 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14202 14203 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14204 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14205 NTCUC_Assignment, NTCUK_Copy); 14206 } 14207 RecordModifiableNonNullParam(*this, LHS.get()); 14208 break; 14209 case BO_PtrMemD: 14210 case BO_PtrMemI: 14211 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14212 Opc == BO_PtrMemI); 14213 break; 14214 case BO_Mul: 14215 case BO_Div: 14216 ConvertHalfVec = true; 14217 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14218 Opc == BO_Div); 14219 break; 14220 case BO_Rem: 14221 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14222 break; 14223 case BO_Add: 14224 ConvertHalfVec = true; 14225 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14226 break; 14227 case BO_Sub: 14228 ConvertHalfVec = true; 14229 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14230 break; 14231 case BO_Shl: 14232 case BO_Shr: 14233 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14234 break; 14235 case BO_LE: 14236 case BO_LT: 14237 case BO_GE: 14238 case BO_GT: 14239 ConvertHalfVec = true; 14240 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14241 break; 14242 case BO_EQ: 14243 case BO_NE: 14244 ConvertHalfVec = true; 14245 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14246 break; 14247 case BO_Cmp: 14248 ConvertHalfVec = true; 14249 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14250 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14251 break; 14252 case BO_And: 14253 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14254 LLVM_FALLTHROUGH; 14255 case BO_Xor: 14256 case BO_Or: 14257 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14258 break; 14259 case BO_LAnd: 14260 case BO_LOr: 14261 ConvertHalfVec = true; 14262 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14263 break; 14264 case BO_MulAssign: 14265 case BO_DivAssign: 14266 ConvertHalfVec = true; 14267 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14268 Opc == BO_DivAssign); 14269 CompLHSTy = CompResultTy; 14270 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14271 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14272 break; 14273 case BO_RemAssign: 14274 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14275 CompLHSTy = CompResultTy; 14276 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14277 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14278 break; 14279 case BO_AddAssign: 14280 ConvertHalfVec = true; 14281 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14282 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14283 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14284 break; 14285 case BO_SubAssign: 14286 ConvertHalfVec = true; 14287 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14288 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14289 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14290 break; 14291 case BO_ShlAssign: 14292 case BO_ShrAssign: 14293 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14294 CompLHSTy = CompResultTy; 14295 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14296 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14297 break; 14298 case BO_AndAssign: 14299 case BO_OrAssign: // fallthrough 14300 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14301 LLVM_FALLTHROUGH; 14302 case BO_XorAssign: 14303 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14304 CompLHSTy = CompResultTy; 14305 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14306 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14307 break; 14308 case BO_Comma: 14309 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14310 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14311 VK = RHS.get()->getValueKind(); 14312 OK = RHS.get()->getObjectKind(); 14313 } 14314 break; 14315 } 14316 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14317 return ExprError(); 14318 14319 // Some of the binary operations require promoting operands of half vector to 14320 // float vectors and truncating the result back to half vector. For now, we do 14321 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14322 // arm64). 14323 assert( 14324 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14325 isVector(LHS.get()->getType(), Context.HalfTy)) && 14326 "both sides are half vectors or neither sides are"); 14327 ConvertHalfVec = 14328 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14329 14330 // Check for array bounds violations for both sides of the BinaryOperator 14331 CheckArrayAccess(LHS.get()); 14332 CheckArrayAccess(RHS.get()); 14333 14334 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14335 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14336 &Context.Idents.get("object_setClass"), 14337 SourceLocation(), LookupOrdinaryName); 14338 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14339 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14340 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14341 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14342 "object_setClass(") 14343 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14344 ",") 14345 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14346 } 14347 else 14348 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14349 } 14350 else if (const ObjCIvarRefExpr *OIRE = 14351 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14352 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14353 14354 // Opc is not a compound assignment if CompResultTy is null. 14355 if (CompResultTy.isNull()) { 14356 if (ConvertHalfVec) 14357 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14358 OpLoc, CurFPFeatureOverrides()); 14359 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14360 VK, OK, OpLoc, CurFPFeatureOverrides()); 14361 } 14362 14363 // Handle compound assignments. 14364 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14365 OK_ObjCProperty) { 14366 VK = VK_LValue; 14367 OK = LHS.get()->getObjectKind(); 14368 } 14369 14370 // The LHS is not converted to the result type for fixed-point compound 14371 // assignment as the common type is computed on demand. Reset the CompLHSTy 14372 // to the LHS type we would have gotten after unary conversions. 14373 if (CompResultTy->isFixedPointType()) 14374 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14375 14376 if (ConvertHalfVec) 14377 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14378 OpLoc, CurFPFeatureOverrides()); 14379 14380 return CompoundAssignOperator::Create( 14381 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14382 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14383 } 14384 14385 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14386 /// operators are mixed in a way that suggests that the programmer forgot that 14387 /// comparison operators have higher precedence. The most typical example of 14388 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14389 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14390 SourceLocation OpLoc, Expr *LHSExpr, 14391 Expr *RHSExpr) { 14392 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14393 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14394 14395 // Check that one of the sides is a comparison operator and the other isn't. 14396 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14397 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14398 if (isLeftComp == isRightComp) 14399 return; 14400 14401 // Bitwise operations are sometimes used as eager logical ops. 14402 // Don't diagnose this. 14403 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14404 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14405 if (isLeftBitwise || isRightBitwise) 14406 return; 14407 14408 SourceRange DiagRange = isLeftComp 14409 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14410 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14411 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14412 SourceRange ParensRange = 14413 isLeftComp 14414 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14415 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14416 14417 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14418 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14419 SuggestParentheses(Self, OpLoc, 14420 Self.PDiag(diag::note_precedence_silence) << OpStr, 14421 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14422 SuggestParentheses(Self, OpLoc, 14423 Self.PDiag(diag::note_precedence_bitwise_first) 14424 << BinaryOperator::getOpcodeStr(Opc), 14425 ParensRange); 14426 } 14427 14428 /// It accepts a '&&' expr that is inside a '||' one. 14429 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14430 /// in parentheses. 14431 static void 14432 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14433 BinaryOperator *Bop) { 14434 assert(Bop->getOpcode() == BO_LAnd); 14435 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14436 << Bop->getSourceRange() << OpLoc; 14437 SuggestParentheses(Self, Bop->getOperatorLoc(), 14438 Self.PDiag(diag::note_precedence_silence) 14439 << Bop->getOpcodeStr(), 14440 Bop->getSourceRange()); 14441 } 14442 14443 /// Returns true if the given expression can be evaluated as a constant 14444 /// 'true'. 14445 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14446 bool Res; 14447 return !E->isValueDependent() && 14448 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14449 } 14450 14451 /// Returns true if the given expression can be evaluated as a constant 14452 /// 'false'. 14453 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14454 bool Res; 14455 return !E->isValueDependent() && 14456 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14457 } 14458 14459 /// Look for '&&' in the left hand of a '||' expr. 14460 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14461 Expr *LHSExpr, Expr *RHSExpr) { 14462 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14463 if (Bop->getOpcode() == BO_LAnd) { 14464 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14465 if (EvaluatesAsFalse(S, RHSExpr)) 14466 return; 14467 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14468 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14469 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14470 } else if (Bop->getOpcode() == BO_LOr) { 14471 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14472 // If it's "a || b && 1 || c" we didn't warn earlier for 14473 // "a || b && 1", but warn now. 14474 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14475 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14476 } 14477 } 14478 } 14479 } 14480 14481 /// Look for '&&' in the right hand of a '||' expr. 14482 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14483 Expr *LHSExpr, Expr *RHSExpr) { 14484 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14485 if (Bop->getOpcode() == BO_LAnd) { 14486 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14487 if (EvaluatesAsFalse(S, LHSExpr)) 14488 return; 14489 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14490 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14491 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14492 } 14493 } 14494 } 14495 14496 /// Look for bitwise op in the left or right hand of a bitwise op with 14497 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14498 /// the '&' expression in parentheses. 14499 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14500 SourceLocation OpLoc, Expr *SubExpr) { 14501 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14502 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14503 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14504 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14505 << Bop->getSourceRange() << OpLoc; 14506 SuggestParentheses(S, Bop->getOperatorLoc(), 14507 S.PDiag(diag::note_precedence_silence) 14508 << Bop->getOpcodeStr(), 14509 Bop->getSourceRange()); 14510 } 14511 } 14512 } 14513 14514 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14515 Expr *SubExpr, StringRef Shift) { 14516 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14517 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14518 StringRef Op = Bop->getOpcodeStr(); 14519 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14520 << Bop->getSourceRange() << OpLoc << Shift << Op; 14521 SuggestParentheses(S, Bop->getOperatorLoc(), 14522 S.PDiag(diag::note_precedence_silence) << Op, 14523 Bop->getSourceRange()); 14524 } 14525 } 14526 } 14527 14528 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14529 Expr *LHSExpr, Expr *RHSExpr) { 14530 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14531 if (!OCE) 14532 return; 14533 14534 FunctionDecl *FD = OCE->getDirectCallee(); 14535 if (!FD || !FD->isOverloadedOperator()) 14536 return; 14537 14538 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14539 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14540 return; 14541 14542 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14543 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14544 << (Kind == OO_LessLess); 14545 SuggestParentheses(S, OCE->getOperatorLoc(), 14546 S.PDiag(diag::note_precedence_silence) 14547 << (Kind == OO_LessLess ? "<<" : ">>"), 14548 OCE->getSourceRange()); 14549 SuggestParentheses( 14550 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14551 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14552 } 14553 14554 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14555 /// precedence. 14556 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14557 SourceLocation OpLoc, Expr *LHSExpr, 14558 Expr *RHSExpr){ 14559 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14560 if (BinaryOperator::isBitwiseOp(Opc)) 14561 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14562 14563 // Diagnose "arg1 & arg2 | arg3" 14564 if ((Opc == BO_Or || Opc == BO_Xor) && 14565 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14566 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14567 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14568 } 14569 14570 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14571 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14572 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14573 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14574 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14575 } 14576 14577 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14578 || Opc == BO_Shr) { 14579 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14580 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14581 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14582 } 14583 14584 // Warn on overloaded shift operators and comparisons, such as: 14585 // cout << 5 == 4; 14586 if (BinaryOperator::isComparisonOp(Opc)) 14587 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14588 } 14589 14590 // Binary Operators. 'Tok' is the token for the operator. 14591 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14592 tok::TokenKind Kind, 14593 Expr *LHSExpr, Expr *RHSExpr) { 14594 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14595 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14596 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14597 14598 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14599 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14600 14601 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14602 } 14603 14604 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14605 UnresolvedSetImpl &Functions) { 14606 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14607 if (OverOp != OO_None && OverOp != OO_Equal) 14608 LookupOverloadedOperatorName(OverOp, S, Functions); 14609 14610 // In C++20 onwards, we may have a second operator to look up. 14611 if (getLangOpts().CPlusPlus20) { 14612 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14613 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14614 } 14615 } 14616 14617 /// Build an overloaded binary operator expression in the given scope. 14618 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14619 BinaryOperatorKind Opc, 14620 Expr *LHS, Expr *RHS) { 14621 switch (Opc) { 14622 case BO_Assign: 14623 case BO_DivAssign: 14624 case BO_RemAssign: 14625 case BO_SubAssign: 14626 case BO_AndAssign: 14627 case BO_OrAssign: 14628 case BO_XorAssign: 14629 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14630 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14631 break; 14632 default: 14633 break; 14634 } 14635 14636 // Find all of the overloaded operators visible from this point. 14637 UnresolvedSet<16> Functions; 14638 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14639 14640 // Build the (potentially-overloaded, potentially-dependent) 14641 // binary operation. 14642 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14643 } 14644 14645 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14646 BinaryOperatorKind Opc, 14647 Expr *LHSExpr, Expr *RHSExpr) { 14648 ExprResult LHS, RHS; 14649 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14650 if (!LHS.isUsable() || !RHS.isUsable()) 14651 return ExprError(); 14652 LHSExpr = LHS.get(); 14653 RHSExpr = RHS.get(); 14654 14655 // We want to end up calling one of checkPseudoObjectAssignment 14656 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14657 // both expressions are overloadable or either is type-dependent), 14658 // or CreateBuiltinBinOp (in any other case). We also want to get 14659 // any placeholder types out of the way. 14660 14661 // Handle pseudo-objects in the LHS. 14662 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14663 // Assignments with a pseudo-object l-value need special analysis. 14664 if (pty->getKind() == BuiltinType::PseudoObject && 14665 BinaryOperator::isAssignmentOp(Opc)) 14666 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14667 14668 // Don't resolve overloads if the other type is overloadable. 14669 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14670 // We can't actually test that if we still have a placeholder, 14671 // though. Fortunately, none of the exceptions we see in that 14672 // code below are valid when the LHS is an overload set. Note 14673 // that an overload set can be dependently-typed, but it never 14674 // instantiates to having an overloadable type. 14675 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14676 if (resolvedRHS.isInvalid()) return ExprError(); 14677 RHSExpr = resolvedRHS.get(); 14678 14679 if (RHSExpr->isTypeDependent() || 14680 RHSExpr->getType()->isOverloadableType()) 14681 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14682 } 14683 14684 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14685 // template, diagnose the missing 'template' keyword instead of diagnosing 14686 // an invalid use of a bound member function. 14687 // 14688 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14689 // to C++1z [over.over]/1.4, but we already checked for that case above. 14690 if (Opc == BO_LT && inTemplateInstantiation() && 14691 (pty->getKind() == BuiltinType::BoundMember || 14692 pty->getKind() == BuiltinType::Overload)) { 14693 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14694 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14695 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14696 return isa<FunctionTemplateDecl>(ND); 14697 })) { 14698 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14699 : OE->getNameLoc(), 14700 diag::err_template_kw_missing) 14701 << OE->getName().getAsString() << ""; 14702 return ExprError(); 14703 } 14704 } 14705 14706 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14707 if (LHS.isInvalid()) return ExprError(); 14708 LHSExpr = LHS.get(); 14709 } 14710 14711 // Handle pseudo-objects in the RHS. 14712 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14713 // An overload in the RHS can potentially be resolved by the type 14714 // being assigned to. 14715 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14716 if (getLangOpts().CPlusPlus && 14717 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14718 LHSExpr->getType()->isOverloadableType())) 14719 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14720 14721 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14722 } 14723 14724 // Don't resolve overloads if the other type is overloadable. 14725 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14726 LHSExpr->getType()->isOverloadableType()) 14727 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14728 14729 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14730 if (!resolvedRHS.isUsable()) return ExprError(); 14731 RHSExpr = resolvedRHS.get(); 14732 } 14733 14734 if (getLangOpts().CPlusPlus) { 14735 // If either expression is type-dependent, always build an 14736 // overloaded op. 14737 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14738 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14739 14740 // Otherwise, build an overloaded op if either expression has an 14741 // overloadable type. 14742 if (LHSExpr->getType()->isOverloadableType() || 14743 RHSExpr->getType()->isOverloadableType()) 14744 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14745 } 14746 14747 if (getLangOpts().RecoveryAST && 14748 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14749 assert(!getLangOpts().CPlusPlus); 14750 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14751 "Should only occur in error-recovery path."); 14752 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14753 // C [6.15.16] p3: 14754 // An assignment expression has the value of the left operand after the 14755 // assignment, but is not an lvalue. 14756 return CompoundAssignOperator::Create( 14757 Context, LHSExpr, RHSExpr, Opc, 14758 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 14759 OpLoc, CurFPFeatureOverrides()); 14760 QualType ResultType; 14761 switch (Opc) { 14762 case BO_Assign: 14763 ResultType = LHSExpr->getType().getUnqualifiedType(); 14764 break; 14765 case BO_LT: 14766 case BO_GT: 14767 case BO_LE: 14768 case BO_GE: 14769 case BO_EQ: 14770 case BO_NE: 14771 case BO_LAnd: 14772 case BO_LOr: 14773 // These operators have a fixed result type regardless of operands. 14774 ResultType = Context.IntTy; 14775 break; 14776 case BO_Comma: 14777 ResultType = RHSExpr->getType(); 14778 break; 14779 default: 14780 ResultType = Context.DependentTy; 14781 break; 14782 } 14783 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14784 VK_PRValue, OK_Ordinary, OpLoc, 14785 CurFPFeatureOverrides()); 14786 } 14787 14788 // Build a built-in binary operation. 14789 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14790 } 14791 14792 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14793 if (T.isNull() || T->isDependentType()) 14794 return false; 14795 14796 if (!T->isPromotableIntegerType()) 14797 return true; 14798 14799 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14800 } 14801 14802 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14803 UnaryOperatorKind Opc, 14804 Expr *InputExpr) { 14805 ExprResult Input = InputExpr; 14806 ExprValueKind VK = VK_PRValue; 14807 ExprObjectKind OK = OK_Ordinary; 14808 QualType resultType; 14809 bool CanOverflow = false; 14810 14811 bool ConvertHalfVec = false; 14812 if (getLangOpts().OpenCL) { 14813 QualType Ty = InputExpr->getType(); 14814 // The only legal unary operation for atomics is '&'. 14815 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14816 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14817 // only with a builtin functions and therefore should be disallowed here. 14818 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14819 || Ty->isBlockPointerType())) { 14820 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14821 << InputExpr->getType() 14822 << Input.get()->getSourceRange()); 14823 } 14824 } 14825 14826 switch (Opc) { 14827 case UO_PreInc: 14828 case UO_PreDec: 14829 case UO_PostInc: 14830 case UO_PostDec: 14831 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14832 OpLoc, 14833 Opc == UO_PreInc || 14834 Opc == UO_PostInc, 14835 Opc == UO_PreInc || 14836 Opc == UO_PreDec); 14837 CanOverflow = isOverflowingIntegerType(Context, resultType); 14838 break; 14839 case UO_AddrOf: 14840 resultType = CheckAddressOfOperand(Input, OpLoc); 14841 CheckAddressOfNoDeref(InputExpr); 14842 RecordModifiableNonNullParam(*this, InputExpr); 14843 break; 14844 case UO_Deref: { 14845 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14846 if (Input.isInvalid()) return ExprError(); 14847 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14848 break; 14849 } 14850 case UO_Plus: 14851 case UO_Minus: 14852 CanOverflow = Opc == UO_Minus && 14853 isOverflowingIntegerType(Context, Input.get()->getType()); 14854 Input = UsualUnaryConversions(Input.get()); 14855 if (Input.isInvalid()) return ExprError(); 14856 // Unary plus and minus require promoting an operand of half vector to a 14857 // float vector and truncating the result back to a half vector. For now, we 14858 // do this only when HalfArgsAndReturns is set (that is, when the target is 14859 // arm or arm64). 14860 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14861 14862 // If the operand is a half vector, promote it to a float vector. 14863 if (ConvertHalfVec) 14864 Input = convertVector(Input.get(), Context.FloatTy, *this); 14865 resultType = Input.get()->getType(); 14866 if (resultType->isDependentType()) 14867 break; 14868 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14869 break; 14870 else if (resultType->isVectorType() && 14871 // The z vector extensions don't allow + or - with bool vectors. 14872 (!Context.getLangOpts().ZVector || 14873 resultType->castAs<VectorType>()->getVectorKind() != 14874 VectorType::AltiVecBool)) 14875 break; 14876 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14877 Opc == UO_Plus && 14878 resultType->isPointerType()) 14879 break; 14880 14881 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14882 << resultType << Input.get()->getSourceRange()); 14883 14884 case UO_Not: // bitwise complement 14885 Input = UsualUnaryConversions(Input.get()); 14886 if (Input.isInvalid()) 14887 return ExprError(); 14888 resultType = Input.get()->getType(); 14889 if (resultType->isDependentType()) 14890 break; 14891 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14892 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14893 // C99 does not support '~' for complex conjugation. 14894 Diag(OpLoc, diag::ext_integer_complement_complex) 14895 << resultType << Input.get()->getSourceRange(); 14896 else if (resultType->hasIntegerRepresentation()) 14897 break; 14898 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14899 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14900 // on vector float types. 14901 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14902 if (!T->isIntegerType()) 14903 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14904 << resultType << Input.get()->getSourceRange()); 14905 } else { 14906 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14907 << resultType << Input.get()->getSourceRange()); 14908 } 14909 break; 14910 14911 case UO_LNot: // logical negation 14912 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14913 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14914 if (Input.isInvalid()) return ExprError(); 14915 resultType = Input.get()->getType(); 14916 14917 // Though we still have to promote half FP to float... 14918 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14919 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14920 resultType = Context.FloatTy; 14921 } 14922 14923 if (resultType->isDependentType()) 14924 break; 14925 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14926 // C99 6.5.3.3p1: ok, fallthrough; 14927 if (Context.getLangOpts().CPlusPlus) { 14928 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14929 // operand contextually converted to bool. 14930 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14931 ScalarTypeToBooleanCastKind(resultType)); 14932 } else if (Context.getLangOpts().OpenCL && 14933 Context.getLangOpts().OpenCLVersion < 120) { 14934 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14935 // operate on scalar float types. 14936 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14937 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14938 << resultType << Input.get()->getSourceRange()); 14939 } 14940 } else if (resultType->isExtVectorType()) { 14941 if (Context.getLangOpts().OpenCL && 14942 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { 14943 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14944 // operate on vector float types. 14945 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14946 if (!T->isIntegerType()) 14947 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14948 << resultType << Input.get()->getSourceRange()); 14949 } 14950 // Vector logical not returns the signed variant of the operand type. 14951 resultType = GetSignedVectorType(resultType); 14952 break; 14953 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14954 const VectorType *VTy = resultType->castAs<VectorType>(); 14955 if (VTy->getVectorKind() != VectorType::GenericVector) 14956 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14957 << resultType << Input.get()->getSourceRange()); 14958 14959 // Vector logical not returns the signed variant of the operand type. 14960 resultType = GetSignedVectorType(resultType); 14961 break; 14962 } else { 14963 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14964 << resultType << Input.get()->getSourceRange()); 14965 } 14966 14967 // LNot always has type int. C99 6.5.3.3p5. 14968 // In C++, it's bool. C++ 5.3.1p8 14969 resultType = Context.getLogicalOperationType(); 14970 break; 14971 case UO_Real: 14972 case UO_Imag: 14973 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14974 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14975 // complex l-values to ordinary l-values and all other values to r-values. 14976 if (Input.isInvalid()) return ExprError(); 14977 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14978 if (Input.get()->isGLValue() && 14979 Input.get()->getObjectKind() == OK_Ordinary) 14980 VK = Input.get()->getValueKind(); 14981 } else if (!getLangOpts().CPlusPlus) { 14982 // In C, a volatile scalar is read by __imag. In C++, it is not. 14983 Input = DefaultLvalueConversion(Input.get()); 14984 } 14985 break; 14986 case UO_Extension: 14987 resultType = Input.get()->getType(); 14988 VK = Input.get()->getValueKind(); 14989 OK = Input.get()->getObjectKind(); 14990 break; 14991 case UO_Coawait: 14992 // It's unnecessary to represent the pass-through operator co_await in the 14993 // AST; just return the input expression instead. 14994 assert(!Input.get()->getType()->isDependentType() && 14995 "the co_await expression must be non-dependant before " 14996 "building operator co_await"); 14997 return Input; 14998 } 14999 if (resultType.isNull() || Input.isInvalid()) 15000 return ExprError(); 15001 15002 // Check for array bounds violations in the operand of the UnaryOperator, 15003 // except for the '*' and '&' operators that have to be handled specially 15004 // by CheckArrayAccess (as there are special cases like &array[arraysize] 15005 // that are explicitly defined as valid by the standard). 15006 if (Opc != UO_AddrOf && Opc != UO_Deref) 15007 CheckArrayAccess(Input.get()); 15008 15009 auto *UO = 15010 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 15011 OpLoc, CanOverflow, CurFPFeatureOverrides()); 15012 15013 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 15014 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 15015 !isUnevaluatedContext()) 15016 ExprEvalContexts.back().PossibleDerefs.insert(UO); 15017 15018 // Convert the result back to a half vector. 15019 if (ConvertHalfVec) 15020 return convertVector(UO, Context.HalfTy, *this); 15021 return UO; 15022 } 15023 15024 /// Determine whether the given expression is a qualified member 15025 /// access expression, of a form that could be turned into a pointer to member 15026 /// with the address-of operator. 15027 bool Sema::isQualifiedMemberAccess(Expr *E) { 15028 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15029 if (!DRE->getQualifier()) 15030 return false; 15031 15032 ValueDecl *VD = DRE->getDecl(); 15033 if (!VD->isCXXClassMember()) 15034 return false; 15035 15036 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 15037 return true; 15038 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 15039 return Method->isInstance(); 15040 15041 return false; 15042 } 15043 15044 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15045 if (!ULE->getQualifier()) 15046 return false; 15047 15048 for (NamedDecl *D : ULE->decls()) { 15049 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 15050 if (Method->isInstance()) 15051 return true; 15052 } else { 15053 // Overload set does not contain methods. 15054 break; 15055 } 15056 } 15057 15058 return false; 15059 } 15060 15061 return false; 15062 } 15063 15064 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 15065 UnaryOperatorKind Opc, Expr *Input) { 15066 // First things first: handle placeholders so that the 15067 // overloaded-operator check considers the right type. 15068 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 15069 // Increment and decrement of pseudo-object references. 15070 if (pty->getKind() == BuiltinType::PseudoObject && 15071 UnaryOperator::isIncrementDecrementOp(Opc)) 15072 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 15073 15074 // extension is always a builtin operator. 15075 if (Opc == UO_Extension) 15076 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15077 15078 // & gets special logic for several kinds of placeholder. 15079 // The builtin code knows what to do. 15080 if (Opc == UO_AddrOf && 15081 (pty->getKind() == BuiltinType::Overload || 15082 pty->getKind() == BuiltinType::UnknownAny || 15083 pty->getKind() == BuiltinType::BoundMember)) 15084 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15085 15086 // Anything else needs to be handled now. 15087 ExprResult Result = CheckPlaceholderExpr(Input); 15088 if (Result.isInvalid()) return ExprError(); 15089 Input = Result.get(); 15090 } 15091 15092 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 15093 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 15094 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 15095 // Find all of the overloaded operators visible from this point. 15096 UnresolvedSet<16> Functions; 15097 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 15098 if (S && OverOp != OO_None) 15099 LookupOverloadedOperatorName(OverOp, S, Functions); 15100 15101 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 15102 } 15103 15104 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15105 } 15106 15107 // Unary Operators. 'Tok' is the token for the operator. 15108 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 15109 tok::TokenKind Op, Expr *Input) { 15110 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 15111 } 15112 15113 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 15114 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 15115 LabelDecl *TheDecl) { 15116 TheDecl->markUsed(Context); 15117 // Create the AST node. The address of a label always has type 'void*'. 15118 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 15119 Context.getPointerType(Context.VoidTy)); 15120 } 15121 15122 void Sema::ActOnStartStmtExpr() { 15123 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15124 } 15125 15126 void Sema::ActOnStmtExprError() { 15127 // Note that function is also called by TreeTransform when leaving a 15128 // StmtExpr scope without rebuilding anything. 15129 15130 DiscardCleanupsInEvaluationContext(); 15131 PopExpressionEvaluationContext(); 15132 } 15133 15134 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15135 SourceLocation RPLoc) { 15136 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15137 } 15138 15139 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15140 SourceLocation RPLoc, unsigned TemplateDepth) { 15141 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15142 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15143 15144 if (hasAnyUnrecoverableErrorsInThisFunction()) 15145 DiscardCleanupsInEvaluationContext(); 15146 assert(!Cleanup.exprNeedsCleanups() && 15147 "cleanups within StmtExpr not correctly bound!"); 15148 PopExpressionEvaluationContext(); 15149 15150 // FIXME: there are a variety of strange constraints to enforce here, for 15151 // example, it is not possible to goto into a stmt expression apparently. 15152 // More semantic analysis is needed. 15153 15154 // If there are sub-stmts in the compound stmt, take the type of the last one 15155 // as the type of the stmtexpr. 15156 QualType Ty = Context.VoidTy; 15157 bool StmtExprMayBindToTemp = false; 15158 if (!Compound->body_empty()) { 15159 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15160 if (const auto *LastStmt = 15161 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15162 if (const Expr *Value = LastStmt->getExprStmt()) { 15163 StmtExprMayBindToTemp = true; 15164 Ty = Value->getType(); 15165 } 15166 } 15167 } 15168 15169 // FIXME: Check that expression type is complete/non-abstract; statement 15170 // expressions are not lvalues. 15171 Expr *ResStmtExpr = 15172 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15173 if (StmtExprMayBindToTemp) 15174 return MaybeBindToTemporary(ResStmtExpr); 15175 return ResStmtExpr; 15176 } 15177 15178 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15179 if (ER.isInvalid()) 15180 return ExprError(); 15181 15182 // Do function/array conversion on the last expression, but not 15183 // lvalue-to-rvalue. However, initialize an unqualified type. 15184 ER = DefaultFunctionArrayConversion(ER.get()); 15185 if (ER.isInvalid()) 15186 return ExprError(); 15187 Expr *E = ER.get(); 15188 15189 if (E->isTypeDependent()) 15190 return E; 15191 15192 // In ARC, if the final expression ends in a consume, splice 15193 // the consume out and bind it later. In the alternate case 15194 // (when dealing with a retainable type), the result 15195 // initialization will create a produce. In both cases the 15196 // result will be +1, and we'll need to balance that out with 15197 // a bind. 15198 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15199 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15200 return Cast->getSubExpr(); 15201 15202 // FIXME: Provide a better location for the initialization. 15203 return PerformCopyInitialization( 15204 InitializedEntity::InitializeStmtExprResult( 15205 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15206 SourceLocation(), E); 15207 } 15208 15209 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15210 TypeSourceInfo *TInfo, 15211 ArrayRef<OffsetOfComponent> Components, 15212 SourceLocation RParenLoc) { 15213 QualType ArgTy = TInfo->getType(); 15214 bool Dependent = ArgTy->isDependentType(); 15215 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15216 15217 // We must have at least one component that refers to the type, and the first 15218 // one is known to be a field designator. Verify that the ArgTy represents 15219 // a struct/union/class. 15220 if (!Dependent && !ArgTy->isRecordType()) 15221 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15222 << ArgTy << TypeRange); 15223 15224 // Type must be complete per C99 7.17p3 because a declaring a variable 15225 // with an incomplete type would be ill-formed. 15226 if (!Dependent 15227 && RequireCompleteType(BuiltinLoc, ArgTy, 15228 diag::err_offsetof_incomplete_type, TypeRange)) 15229 return ExprError(); 15230 15231 bool DidWarnAboutNonPOD = false; 15232 QualType CurrentType = ArgTy; 15233 SmallVector<OffsetOfNode, 4> Comps; 15234 SmallVector<Expr*, 4> Exprs; 15235 for (const OffsetOfComponent &OC : Components) { 15236 if (OC.isBrackets) { 15237 // Offset of an array sub-field. TODO: Should we allow vector elements? 15238 if (!CurrentType->isDependentType()) { 15239 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15240 if(!AT) 15241 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15242 << CurrentType); 15243 CurrentType = AT->getElementType(); 15244 } else 15245 CurrentType = Context.DependentTy; 15246 15247 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15248 if (IdxRval.isInvalid()) 15249 return ExprError(); 15250 Expr *Idx = IdxRval.get(); 15251 15252 // The expression must be an integral expression. 15253 // FIXME: An integral constant expression? 15254 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15255 !Idx->getType()->isIntegerType()) 15256 return ExprError( 15257 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15258 << Idx->getSourceRange()); 15259 15260 // Record this array index. 15261 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15262 Exprs.push_back(Idx); 15263 continue; 15264 } 15265 15266 // Offset of a field. 15267 if (CurrentType->isDependentType()) { 15268 // We have the offset of a field, but we can't look into the dependent 15269 // type. Just record the identifier of the field. 15270 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15271 CurrentType = Context.DependentTy; 15272 continue; 15273 } 15274 15275 // We need to have a complete type to look into. 15276 if (RequireCompleteType(OC.LocStart, CurrentType, 15277 diag::err_offsetof_incomplete_type)) 15278 return ExprError(); 15279 15280 // Look for the designated field. 15281 const RecordType *RC = CurrentType->getAs<RecordType>(); 15282 if (!RC) 15283 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15284 << CurrentType); 15285 RecordDecl *RD = RC->getDecl(); 15286 15287 // C++ [lib.support.types]p5: 15288 // The macro offsetof accepts a restricted set of type arguments in this 15289 // International Standard. type shall be a POD structure or a POD union 15290 // (clause 9). 15291 // C++11 [support.types]p4: 15292 // If type is not a standard-layout class (Clause 9), the results are 15293 // undefined. 15294 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15295 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15296 unsigned DiagID = 15297 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15298 : diag::ext_offsetof_non_pod_type; 15299 15300 if (!IsSafe && !DidWarnAboutNonPOD && 15301 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15302 PDiag(DiagID) 15303 << SourceRange(Components[0].LocStart, OC.LocEnd) 15304 << CurrentType)) 15305 DidWarnAboutNonPOD = true; 15306 } 15307 15308 // Look for the field. 15309 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15310 LookupQualifiedName(R, RD); 15311 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15312 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15313 if (!MemberDecl) { 15314 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15315 MemberDecl = IndirectMemberDecl->getAnonField(); 15316 } 15317 15318 if (!MemberDecl) 15319 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15320 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15321 OC.LocEnd)); 15322 15323 // C99 7.17p3: 15324 // (If the specified member is a bit-field, the behavior is undefined.) 15325 // 15326 // We diagnose this as an error. 15327 if (MemberDecl->isBitField()) { 15328 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15329 << MemberDecl->getDeclName() 15330 << SourceRange(BuiltinLoc, RParenLoc); 15331 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15332 return ExprError(); 15333 } 15334 15335 RecordDecl *Parent = MemberDecl->getParent(); 15336 if (IndirectMemberDecl) 15337 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15338 15339 // If the member was found in a base class, introduce OffsetOfNodes for 15340 // the base class indirections. 15341 CXXBasePaths Paths; 15342 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15343 Paths)) { 15344 if (Paths.getDetectedVirtual()) { 15345 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15346 << MemberDecl->getDeclName() 15347 << SourceRange(BuiltinLoc, RParenLoc); 15348 return ExprError(); 15349 } 15350 15351 CXXBasePath &Path = Paths.front(); 15352 for (const CXXBasePathElement &B : Path) 15353 Comps.push_back(OffsetOfNode(B.Base)); 15354 } 15355 15356 if (IndirectMemberDecl) { 15357 for (auto *FI : IndirectMemberDecl->chain()) { 15358 assert(isa<FieldDecl>(FI)); 15359 Comps.push_back(OffsetOfNode(OC.LocStart, 15360 cast<FieldDecl>(FI), OC.LocEnd)); 15361 } 15362 } else 15363 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15364 15365 CurrentType = MemberDecl->getType().getNonReferenceType(); 15366 } 15367 15368 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15369 Comps, Exprs, RParenLoc); 15370 } 15371 15372 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15373 SourceLocation BuiltinLoc, 15374 SourceLocation TypeLoc, 15375 ParsedType ParsedArgTy, 15376 ArrayRef<OffsetOfComponent> Components, 15377 SourceLocation RParenLoc) { 15378 15379 TypeSourceInfo *ArgTInfo; 15380 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15381 if (ArgTy.isNull()) 15382 return ExprError(); 15383 15384 if (!ArgTInfo) 15385 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15386 15387 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15388 } 15389 15390 15391 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15392 Expr *CondExpr, 15393 Expr *LHSExpr, Expr *RHSExpr, 15394 SourceLocation RPLoc) { 15395 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15396 15397 ExprValueKind VK = VK_PRValue; 15398 ExprObjectKind OK = OK_Ordinary; 15399 QualType resType; 15400 bool CondIsTrue = false; 15401 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15402 resType = Context.DependentTy; 15403 } else { 15404 // The conditional expression is required to be a constant expression. 15405 llvm::APSInt condEval(32); 15406 ExprResult CondICE = VerifyIntegerConstantExpression( 15407 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15408 if (CondICE.isInvalid()) 15409 return ExprError(); 15410 CondExpr = CondICE.get(); 15411 CondIsTrue = condEval.getZExtValue(); 15412 15413 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15414 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15415 15416 resType = ActiveExpr->getType(); 15417 VK = ActiveExpr->getValueKind(); 15418 OK = ActiveExpr->getObjectKind(); 15419 } 15420 15421 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15422 resType, VK, OK, RPLoc, CondIsTrue); 15423 } 15424 15425 //===----------------------------------------------------------------------===// 15426 // Clang Extensions. 15427 //===----------------------------------------------------------------------===// 15428 15429 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15430 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15431 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15432 15433 if (LangOpts.CPlusPlus) { 15434 MangleNumberingContext *MCtx; 15435 Decl *ManglingContextDecl; 15436 std::tie(MCtx, ManglingContextDecl) = 15437 getCurrentMangleNumberContext(Block->getDeclContext()); 15438 if (MCtx) { 15439 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15440 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15441 } 15442 } 15443 15444 PushBlockScope(CurScope, Block); 15445 CurContext->addDecl(Block); 15446 if (CurScope) 15447 PushDeclContext(CurScope, Block); 15448 else 15449 CurContext = Block; 15450 15451 getCurBlock()->HasImplicitReturnType = true; 15452 15453 // Enter a new evaluation context to insulate the block from any 15454 // cleanups from the enclosing full-expression. 15455 PushExpressionEvaluationContext( 15456 ExpressionEvaluationContext::PotentiallyEvaluated); 15457 } 15458 15459 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15460 Scope *CurScope) { 15461 assert(ParamInfo.getIdentifier() == nullptr && 15462 "block-id should have no identifier!"); 15463 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15464 BlockScopeInfo *CurBlock = getCurBlock(); 15465 15466 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15467 QualType T = Sig->getType(); 15468 15469 // FIXME: We should allow unexpanded parameter packs here, but that would, 15470 // in turn, make the block expression contain unexpanded parameter packs. 15471 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15472 // Drop the parameters. 15473 FunctionProtoType::ExtProtoInfo EPI; 15474 EPI.HasTrailingReturn = false; 15475 EPI.TypeQuals.addConst(); 15476 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15477 Sig = Context.getTrivialTypeSourceInfo(T); 15478 } 15479 15480 // GetTypeForDeclarator always produces a function type for a block 15481 // literal signature. Furthermore, it is always a FunctionProtoType 15482 // unless the function was written with a typedef. 15483 assert(T->isFunctionType() && 15484 "GetTypeForDeclarator made a non-function block signature"); 15485 15486 // Look for an explicit signature in that function type. 15487 FunctionProtoTypeLoc ExplicitSignature; 15488 15489 if ((ExplicitSignature = Sig->getTypeLoc() 15490 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15491 15492 // Check whether that explicit signature was synthesized by 15493 // GetTypeForDeclarator. If so, don't save that as part of the 15494 // written signature. 15495 if (ExplicitSignature.getLocalRangeBegin() == 15496 ExplicitSignature.getLocalRangeEnd()) { 15497 // This would be much cheaper if we stored TypeLocs instead of 15498 // TypeSourceInfos. 15499 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15500 unsigned Size = Result.getFullDataSize(); 15501 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15502 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15503 15504 ExplicitSignature = FunctionProtoTypeLoc(); 15505 } 15506 } 15507 15508 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15509 CurBlock->FunctionType = T; 15510 15511 const auto *Fn = T->castAs<FunctionType>(); 15512 QualType RetTy = Fn->getReturnType(); 15513 bool isVariadic = 15514 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15515 15516 CurBlock->TheDecl->setIsVariadic(isVariadic); 15517 15518 // Context.DependentTy is used as a placeholder for a missing block 15519 // return type. TODO: what should we do with declarators like: 15520 // ^ * { ... } 15521 // If the answer is "apply template argument deduction".... 15522 if (RetTy != Context.DependentTy) { 15523 CurBlock->ReturnType = RetTy; 15524 CurBlock->TheDecl->setBlockMissingReturnType(false); 15525 CurBlock->HasImplicitReturnType = false; 15526 } 15527 15528 // Push block parameters from the declarator if we had them. 15529 SmallVector<ParmVarDecl*, 8> Params; 15530 if (ExplicitSignature) { 15531 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15532 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15533 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15534 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15535 // Diagnose this as an extension in C17 and earlier. 15536 if (!getLangOpts().C2x) 15537 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15538 } 15539 Params.push_back(Param); 15540 } 15541 15542 // Fake up parameter variables if we have a typedef, like 15543 // ^ fntype { ... } 15544 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15545 for (const auto &I : Fn->param_types()) { 15546 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15547 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15548 Params.push_back(Param); 15549 } 15550 } 15551 15552 // Set the parameters on the block decl. 15553 if (!Params.empty()) { 15554 CurBlock->TheDecl->setParams(Params); 15555 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15556 /*CheckParameterNames=*/false); 15557 } 15558 15559 // Finally we can process decl attributes. 15560 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15561 15562 // Put the parameter variables in scope. 15563 for (auto AI : CurBlock->TheDecl->parameters()) { 15564 AI->setOwningFunction(CurBlock->TheDecl); 15565 15566 // If this has an identifier, add it to the scope stack. 15567 if (AI->getIdentifier()) { 15568 CheckShadow(CurBlock->TheScope, AI); 15569 15570 PushOnScopeChains(AI, CurBlock->TheScope); 15571 } 15572 } 15573 } 15574 15575 /// ActOnBlockError - If there is an error parsing a block, this callback 15576 /// is invoked to pop the information about the block from the action impl. 15577 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15578 // Leave the expression-evaluation context. 15579 DiscardCleanupsInEvaluationContext(); 15580 PopExpressionEvaluationContext(); 15581 15582 // Pop off CurBlock, handle nested blocks. 15583 PopDeclContext(); 15584 PopFunctionScopeInfo(); 15585 } 15586 15587 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15588 /// literal was successfully completed. ^(int x){...} 15589 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15590 Stmt *Body, Scope *CurScope) { 15591 // If blocks are disabled, emit an error. 15592 if (!LangOpts.Blocks) 15593 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15594 15595 // Leave the expression-evaluation context. 15596 if (hasAnyUnrecoverableErrorsInThisFunction()) 15597 DiscardCleanupsInEvaluationContext(); 15598 assert(!Cleanup.exprNeedsCleanups() && 15599 "cleanups within block not correctly bound!"); 15600 PopExpressionEvaluationContext(); 15601 15602 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15603 BlockDecl *BD = BSI->TheDecl; 15604 15605 if (BSI->HasImplicitReturnType) 15606 deduceClosureReturnType(*BSI); 15607 15608 QualType RetTy = Context.VoidTy; 15609 if (!BSI->ReturnType.isNull()) 15610 RetTy = BSI->ReturnType; 15611 15612 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15613 QualType BlockTy; 15614 15615 // If the user wrote a function type in some form, try to use that. 15616 if (!BSI->FunctionType.isNull()) { 15617 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15618 15619 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15620 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15621 15622 // Turn protoless block types into nullary block types. 15623 if (isa<FunctionNoProtoType>(FTy)) { 15624 FunctionProtoType::ExtProtoInfo EPI; 15625 EPI.ExtInfo = Ext; 15626 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15627 15628 // Otherwise, if we don't need to change anything about the function type, 15629 // preserve its sugar structure. 15630 } else if (FTy->getReturnType() == RetTy && 15631 (!NoReturn || FTy->getNoReturnAttr())) { 15632 BlockTy = BSI->FunctionType; 15633 15634 // Otherwise, make the minimal modifications to the function type. 15635 } else { 15636 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15637 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15638 EPI.TypeQuals = Qualifiers(); 15639 EPI.ExtInfo = Ext; 15640 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15641 } 15642 15643 // If we don't have a function type, just build one from nothing. 15644 } else { 15645 FunctionProtoType::ExtProtoInfo EPI; 15646 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15647 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15648 } 15649 15650 DiagnoseUnusedParameters(BD->parameters()); 15651 BlockTy = Context.getBlockPointerType(BlockTy); 15652 15653 // If needed, diagnose invalid gotos and switches in the block. 15654 if (getCurFunction()->NeedsScopeChecking() && 15655 !PP.isCodeCompletionEnabled()) 15656 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15657 15658 BD->setBody(cast<CompoundStmt>(Body)); 15659 15660 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15661 DiagnoseUnguardedAvailabilityViolations(BD); 15662 15663 // Try to apply the named return value optimization. We have to check again 15664 // if we can do this, though, because blocks keep return statements around 15665 // to deduce an implicit return type. 15666 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15667 !BD->isDependentContext()) 15668 computeNRVO(Body, BSI); 15669 15670 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15671 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15672 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15673 NTCUK_Destruct|NTCUK_Copy); 15674 15675 PopDeclContext(); 15676 15677 // Set the captured variables on the block. 15678 SmallVector<BlockDecl::Capture, 4> Captures; 15679 for (Capture &Cap : BSI->Captures) { 15680 if (Cap.isInvalid() || Cap.isThisCapture()) 15681 continue; 15682 15683 VarDecl *Var = Cap.getVariable(); 15684 Expr *CopyExpr = nullptr; 15685 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15686 if (const RecordType *Record = 15687 Cap.getCaptureType()->getAs<RecordType>()) { 15688 // The capture logic needs the destructor, so make sure we mark it. 15689 // Usually this is unnecessary because most local variables have 15690 // their destructors marked at declaration time, but parameters are 15691 // an exception because it's technically only the call site that 15692 // actually requires the destructor. 15693 if (isa<ParmVarDecl>(Var)) 15694 FinalizeVarWithDestructor(Var, Record); 15695 15696 // Enter a separate potentially-evaluated context while building block 15697 // initializers to isolate their cleanups from those of the block 15698 // itself. 15699 // FIXME: Is this appropriate even when the block itself occurs in an 15700 // unevaluated operand? 15701 EnterExpressionEvaluationContext EvalContext( 15702 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15703 15704 SourceLocation Loc = Cap.getLocation(); 15705 15706 ExprResult Result = BuildDeclarationNameExpr( 15707 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15708 15709 // According to the blocks spec, the capture of a variable from 15710 // the stack requires a const copy constructor. This is not true 15711 // of the copy/move done to move a __block variable to the heap. 15712 if (!Result.isInvalid() && 15713 !Result.get()->getType().isConstQualified()) { 15714 Result = ImpCastExprToType(Result.get(), 15715 Result.get()->getType().withConst(), 15716 CK_NoOp, VK_LValue); 15717 } 15718 15719 if (!Result.isInvalid()) { 15720 Result = PerformCopyInitialization( 15721 InitializedEntity::InitializeBlock(Var->getLocation(), 15722 Cap.getCaptureType()), 15723 Loc, Result.get()); 15724 } 15725 15726 // Build a full-expression copy expression if initialization 15727 // succeeded and used a non-trivial constructor. Recover from 15728 // errors by pretending that the copy isn't necessary. 15729 if (!Result.isInvalid() && 15730 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15731 ->isTrivial()) { 15732 Result = MaybeCreateExprWithCleanups(Result); 15733 CopyExpr = Result.get(); 15734 } 15735 } 15736 } 15737 15738 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15739 CopyExpr); 15740 Captures.push_back(NewCap); 15741 } 15742 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15743 15744 // Pop the block scope now but keep it alive to the end of this function. 15745 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15746 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15747 15748 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15749 15750 // If the block isn't obviously global, i.e. it captures anything at 15751 // all, then we need to do a few things in the surrounding context: 15752 if (Result->getBlockDecl()->hasCaptures()) { 15753 // First, this expression has a new cleanup object. 15754 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15755 Cleanup.setExprNeedsCleanups(true); 15756 15757 // It also gets a branch-protected scope if any of the captured 15758 // variables needs destruction. 15759 for (const auto &CI : Result->getBlockDecl()->captures()) { 15760 const VarDecl *var = CI.getVariable(); 15761 if (var->getType().isDestructedType() != QualType::DK_none) { 15762 setFunctionHasBranchProtectedScope(); 15763 break; 15764 } 15765 } 15766 } 15767 15768 if (getCurFunction()) 15769 getCurFunction()->addBlock(BD); 15770 15771 return Result; 15772 } 15773 15774 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15775 SourceLocation RPLoc) { 15776 TypeSourceInfo *TInfo; 15777 GetTypeFromParser(Ty, &TInfo); 15778 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15779 } 15780 15781 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15782 Expr *E, TypeSourceInfo *TInfo, 15783 SourceLocation RPLoc) { 15784 Expr *OrigExpr = E; 15785 bool IsMS = false; 15786 15787 // CUDA device code does not support varargs. 15788 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15789 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15790 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15791 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15792 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15793 } 15794 } 15795 15796 // NVPTX does not support va_arg expression. 15797 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15798 Context.getTargetInfo().getTriple().isNVPTX()) 15799 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15800 15801 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15802 // as Microsoft ABI on an actual Microsoft platform, where 15803 // __builtin_ms_va_list and __builtin_va_list are the same.) 15804 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15805 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15806 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15807 if (Context.hasSameType(MSVaListType, E->getType())) { 15808 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15809 return ExprError(); 15810 IsMS = true; 15811 } 15812 } 15813 15814 // Get the va_list type 15815 QualType VaListType = Context.getBuiltinVaListType(); 15816 if (!IsMS) { 15817 if (VaListType->isArrayType()) { 15818 // Deal with implicit array decay; for example, on x86-64, 15819 // va_list is an array, but it's supposed to decay to 15820 // a pointer for va_arg. 15821 VaListType = Context.getArrayDecayedType(VaListType); 15822 // Make sure the input expression also decays appropriately. 15823 ExprResult Result = UsualUnaryConversions(E); 15824 if (Result.isInvalid()) 15825 return ExprError(); 15826 E = Result.get(); 15827 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15828 // If va_list is a record type and we are compiling in C++ mode, 15829 // check the argument using reference binding. 15830 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15831 Context, Context.getLValueReferenceType(VaListType), false); 15832 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15833 if (Init.isInvalid()) 15834 return ExprError(); 15835 E = Init.getAs<Expr>(); 15836 } else { 15837 // Otherwise, the va_list argument must be an l-value because 15838 // it is modified by va_arg. 15839 if (!E->isTypeDependent() && 15840 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15841 return ExprError(); 15842 } 15843 } 15844 15845 if (!IsMS && !E->isTypeDependent() && 15846 !Context.hasSameType(VaListType, E->getType())) 15847 return ExprError( 15848 Diag(E->getBeginLoc(), 15849 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15850 << OrigExpr->getType() << E->getSourceRange()); 15851 15852 if (!TInfo->getType()->isDependentType()) { 15853 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15854 diag::err_second_parameter_to_va_arg_incomplete, 15855 TInfo->getTypeLoc())) 15856 return ExprError(); 15857 15858 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15859 TInfo->getType(), 15860 diag::err_second_parameter_to_va_arg_abstract, 15861 TInfo->getTypeLoc())) 15862 return ExprError(); 15863 15864 if (!TInfo->getType().isPODType(Context)) { 15865 Diag(TInfo->getTypeLoc().getBeginLoc(), 15866 TInfo->getType()->isObjCLifetimeType() 15867 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15868 : diag::warn_second_parameter_to_va_arg_not_pod) 15869 << TInfo->getType() 15870 << TInfo->getTypeLoc().getSourceRange(); 15871 } 15872 15873 // Check for va_arg where arguments of the given type will be promoted 15874 // (i.e. this va_arg is guaranteed to have undefined behavior). 15875 QualType PromoteType; 15876 if (TInfo->getType()->isPromotableIntegerType()) { 15877 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15878 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 15879 // and C2x 7.16.1.1p2 says, in part: 15880 // If type is not compatible with the type of the actual next argument 15881 // (as promoted according to the default argument promotions), the 15882 // behavior is undefined, except for the following cases: 15883 // - both types are pointers to qualified or unqualified versions of 15884 // compatible types; 15885 // - one type is a signed integer type, the other type is the 15886 // corresponding unsigned integer type, and the value is 15887 // representable in both types; 15888 // - one type is pointer to qualified or unqualified void and the 15889 // other is a pointer to a qualified or unqualified character type. 15890 // Given that type compatibility is the primary requirement (ignoring 15891 // qualifications), you would think we could call typesAreCompatible() 15892 // directly to test this. However, in C++, that checks for *same type*, 15893 // which causes false positives when passing an enumeration type to 15894 // va_arg. Instead, get the underlying type of the enumeration and pass 15895 // that. 15896 QualType UnderlyingType = TInfo->getType(); 15897 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 15898 UnderlyingType = ET->getDecl()->getIntegerType(); 15899 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15900 /*CompareUnqualified*/ true)) 15901 PromoteType = QualType(); 15902 15903 // If the types are still not compatible, we need to test whether the 15904 // promoted type and the underlying type are the same except for 15905 // signedness. Ask the AST for the correctly corresponding type and see 15906 // if that's compatible. 15907 if (!PromoteType.isNull() && 15908 PromoteType->isUnsignedIntegerType() != 15909 UnderlyingType->isUnsignedIntegerType()) { 15910 UnderlyingType = 15911 UnderlyingType->isUnsignedIntegerType() 15912 ? Context.getCorrespondingSignedType(UnderlyingType) 15913 : Context.getCorrespondingUnsignedType(UnderlyingType); 15914 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15915 /*CompareUnqualified*/ true)) 15916 PromoteType = QualType(); 15917 } 15918 } 15919 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15920 PromoteType = Context.DoubleTy; 15921 if (!PromoteType.isNull()) 15922 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15923 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15924 << TInfo->getType() 15925 << PromoteType 15926 << TInfo->getTypeLoc().getSourceRange()); 15927 } 15928 15929 QualType T = TInfo->getType().getNonLValueExprType(Context); 15930 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15931 } 15932 15933 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15934 // The type of __null will be int or long, depending on the size of 15935 // pointers on the target. 15936 QualType Ty; 15937 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15938 if (pw == Context.getTargetInfo().getIntWidth()) 15939 Ty = Context.IntTy; 15940 else if (pw == Context.getTargetInfo().getLongWidth()) 15941 Ty = Context.LongTy; 15942 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15943 Ty = Context.LongLongTy; 15944 else { 15945 llvm_unreachable("I don't know size of pointer!"); 15946 } 15947 15948 return new (Context) GNUNullExpr(Ty, TokenLoc); 15949 } 15950 15951 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15952 SourceLocation BuiltinLoc, 15953 SourceLocation RPLoc) { 15954 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15955 } 15956 15957 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15958 SourceLocation BuiltinLoc, 15959 SourceLocation RPLoc, 15960 DeclContext *ParentContext) { 15961 return new (Context) 15962 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15963 } 15964 15965 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15966 bool Diagnose) { 15967 if (!getLangOpts().ObjC) 15968 return false; 15969 15970 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15971 if (!PT) 15972 return false; 15973 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15974 15975 // Ignore any parens, implicit casts (should only be 15976 // array-to-pointer decays), and not-so-opaque values. The last is 15977 // important for making this trigger for property assignments. 15978 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15979 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15980 if (OV->getSourceExpr()) 15981 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15982 15983 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15984 if (!PT->isObjCIdType() && 15985 !(ID && ID->getIdentifier()->isStr("NSString"))) 15986 return false; 15987 if (!SL->isAscii()) 15988 return false; 15989 15990 if (Diagnose) { 15991 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15992 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15993 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15994 } 15995 return true; 15996 } 15997 15998 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15999 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 16000 isa<CXXBoolLiteralExpr>(SrcExpr)) && 16001 !SrcExpr->isNullPointerConstant( 16002 getASTContext(), Expr::NPC_NeverValueDependent)) { 16003 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 16004 return false; 16005 if (Diagnose) { 16006 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 16007 << /*number*/1 16008 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 16009 Expr *NumLit = 16010 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 16011 if (NumLit) 16012 Exp = NumLit; 16013 } 16014 return true; 16015 } 16016 16017 return false; 16018 } 16019 16020 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 16021 const Expr *SrcExpr) { 16022 if (!DstType->isFunctionPointerType() || 16023 !SrcExpr->getType()->isFunctionType()) 16024 return false; 16025 16026 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 16027 if (!DRE) 16028 return false; 16029 16030 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 16031 if (!FD) 16032 return false; 16033 16034 return !S.checkAddressOfFunctionIsAvailable(FD, 16035 /*Complain=*/true, 16036 SrcExpr->getBeginLoc()); 16037 } 16038 16039 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 16040 SourceLocation Loc, 16041 QualType DstType, QualType SrcType, 16042 Expr *SrcExpr, AssignmentAction Action, 16043 bool *Complained) { 16044 if (Complained) 16045 *Complained = false; 16046 16047 // Decode the result (notice that AST's are still created for extensions). 16048 bool CheckInferredResultType = false; 16049 bool isInvalid = false; 16050 unsigned DiagKind = 0; 16051 ConversionFixItGenerator ConvHints; 16052 bool MayHaveConvFixit = false; 16053 bool MayHaveFunctionDiff = false; 16054 const ObjCInterfaceDecl *IFace = nullptr; 16055 const ObjCProtocolDecl *PDecl = nullptr; 16056 16057 switch (ConvTy) { 16058 case Compatible: 16059 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 16060 return false; 16061 16062 case PointerToInt: 16063 if (getLangOpts().CPlusPlus) { 16064 DiagKind = diag::err_typecheck_convert_pointer_int; 16065 isInvalid = true; 16066 } else { 16067 DiagKind = diag::ext_typecheck_convert_pointer_int; 16068 } 16069 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16070 MayHaveConvFixit = true; 16071 break; 16072 case IntToPointer: 16073 if (getLangOpts().CPlusPlus) { 16074 DiagKind = diag::err_typecheck_convert_int_pointer; 16075 isInvalid = true; 16076 } else { 16077 DiagKind = diag::ext_typecheck_convert_int_pointer; 16078 } 16079 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16080 MayHaveConvFixit = true; 16081 break; 16082 case IncompatibleFunctionPointer: 16083 if (getLangOpts().CPlusPlus) { 16084 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 16085 isInvalid = true; 16086 } else { 16087 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 16088 } 16089 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16090 MayHaveConvFixit = true; 16091 break; 16092 case IncompatiblePointer: 16093 if (Action == AA_Passing_CFAudited) { 16094 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 16095 } else if (getLangOpts().CPlusPlus) { 16096 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 16097 isInvalid = true; 16098 } else { 16099 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 16100 } 16101 CheckInferredResultType = DstType->isObjCObjectPointerType() && 16102 SrcType->isObjCObjectPointerType(); 16103 if (!CheckInferredResultType) { 16104 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16105 } else if (CheckInferredResultType) { 16106 SrcType = SrcType.getUnqualifiedType(); 16107 DstType = DstType.getUnqualifiedType(); 16108 } 16109 MayHaveConvFixit = true; 16110 break; 16111 case IncompatiblePointerSign: 16112 if (getLangOpts().CPlusPlus) { 16113 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 16114 isInvalid = true; 16115 } else { 16116 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 16117 } 16118 break; 16119 case FunctionVoidPointer: 16120 if (getLangOpts().CPlusPlus) { 16121 DiagKind = diag::err_typecheck_convert_pointer_void_func; 16122 isInvalid = true; 16123 } else { 16124 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 16125 } 16126 break; 16127 case IncompatiblePointerDiscardsQualifiers: { 16128 // Perform array-to-pointer decay if necessary. 16129 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 16130 16131 isInvalid = true; 16132 16133 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 16134 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 16135 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 16136 DiagKind = diag::err_typecheck_incompatible_address_space; 16137 break; 16138 16139 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 16140 DiagKind = diag::err_typecheck_incompatible_ownership; 16141 break; 16142 } 16143 16144 llvm_unreachable("unknown error case for discarding qualifiers!"); 16145 // fallthrough 16146 } 16147 case CompatiblePointerDiscardsQualifiers: 16148 // If the qualifiers lost were because we were applying the 16149 // (deprecated) C++ conversion from a string literal to a char* 16150 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 16151 // Ideally, this check would be performed in 16152 // checkPointerTypesForAssignment. However, that would require a 16153 // bit of refactoring (so that the second argument is an 16154 // expression, rather than a type), which should be done as part 16155 // of a larger effort to fix checkPointerTypesForAssignment for 16156 // C++ semantics. 16157 if (getLangOpts().CPlusPlus && 16158 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 16159 return false; 16160 if (getLangOpts().CPlusPlus) { 16161 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 16162 isInvalid = true; 16163 } else { 16164 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 16165 } 16166 16167 break; 16168 case IncompatibleNestedPointerQualifiers: 16169 if (getLangOpts().CPlusPlus) { 16170 isInvalid = true; 16171 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 16172 } else { 16173 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16174 } 16175 break; 16176 case IncompatibleNestedPointerAddressSpaceMismatch: 16177 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16178 isInvalid = true; 16179 break; 16180 case IntToBlockPointer: 16181 DiagKind = diag::err_int_to_block_pointer; 16182 isInvalid = true; 16183 break; 16184 case IncompatibleBlockPointer: 16185 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16186 isInvalid = true; 16187 break; 16188 case IncompatibleObjCQualifiedId: { 16189 if (SrcType->isObjCQualifiedIdType()) { 16190 const ObjCObjectPointerType *srcOPT = 16191 SrcType->castAs<ObjCObjectPointerType>(); 16192 for (auto *srcProto : srcOPT->quals()) { 16193 PDecl = srcProto; 16194 break; 16195 } 16196 if (const ObjCInterfaceType *IFaceT = 16197 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16198 IFace = IFaceT->getDecl(); 16199 } 16200 else if (DstType->isObjCQualifiedIdType()) { 16201 const ObjCObjectPointerType *dstOPT = 16202 DstType->castAs<ObjCObjectPointerType>(); 16203 for (auto *dstProto : dstOPT->quals()) { 16204 PDecl = dstProto; 16205 break; 16206 } 16207 if (const ObjCInterfaceType *IFaceT = 16208 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16209 IFace = IFaceT->getDecl(); 16210 } 16211 if (getLangOpts().CPlusPlus) { 16212 DiagKind = diag::err_incompatible_qualified_id; 16213 isInvalid = true; 16214 } else { 16215 DiagKind = diag::warn_incompatible_qualified_id; 16216 } 16217 break; 16218 } 16219 case IncompatibleVectors: 16220 if (getLangOpts().CPlusPlus) { 16221 DiagKind = diag::err_incompatible_vectors; 16222 isInvalid = true; 16223 } else { 16224 DiagKind = diag::warn_incompatible_vectors; 16225 } 16226 break; 16227 case IncompatibleObjCWeakRef: 16228 DiagKind = diag::err_arc_weak_unavailable_assign; 16229 isInvalid = true; 16230 break; 16231 case Incompatible: 16232 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16233 if (Complained) 16234 *Complained = true; 16235 return true; 16236 } 16237 16238 DiagKind = diag::err_typecheck_convert_incompatible; 16239 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16240 MayHaveConvFixit = true; 16241 isInvalid = true; 16242 MayHaveFunctionDiff = true; 16243 break; 16244 } 16245 16246 QualType FirstType, SecondType; 16247 switch (Action) { 16248 case AA_Assigning: 16249 case AA_Initializing: 16250 // The destination type comes first. 16251 FirstType = DstType; 16252 SecondType = SrcType; 16253 break; 16254 16255 case AA_Returning: 16256 case AA_Passing: 16257 case AA_Passing_CFAudited: 16258 case AA_Converting: 16259 case AA_Sending: 16260 case AA_Casting: 16261 // The source type comes first. 16262 FirstType = SrcType; 16263 SecondType = DstType; 16264 break; 16265 } 16266 16267 PartialDiagnostic FDiag = PDiag(DiagKind); 16268 if (Action == AA_Passing_CFAudited) 16269 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16270 else 16271 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16272 16273 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16274 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16275 auto isPlainChar = [](const clang::Type *Type) { 16276 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16277 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16278 }; 16279 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16280 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16281 } 16282 16283 // If we can fix the conversion, suggest the FixIts. 16284 if (!ConvHints.isNull()) { 16285 for (FixItHint &H : ConvHints.Hints) 16286 FDiag << H; 16287 } 16288 16289 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16290 16291 if (MayHaveFunctionDiff) 16292 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16293 16294 Diag(Loc, FDiag); 16295 if ((DiagKind == diag::warn_incompatible_qualified_id || 16296 DiagKind == diag::err_incompatible_qualified_id) && 16297 PDecl && IFace && !IFace->hasDefinition()) 16298 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16299 << IFace << PDecl; 16300 16301 if (SecondType == Context.OverloadTy) 16302 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16303 FirstType, /*TakingAddress=*/true); 16304 16305 if (CheckInferredResultType) 16306 EmitRelatedResultTypeNote(SrcExpr); 16307 16308 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16309 EmitRelatedResultTypeNoteForReturn(DstType); 16310 16311 if (Complained) 16312 *Complained = true; 16313 return isInvalid; 16314 } 16315 16316 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16317 llvm::APSInt *Result, 16318 AllowFoldKind CanFold) { 16319 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16320 public: 16321 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16322 QualType T) override { 16323 return S.Diag(Loc, diag::err_ice_not_integral) 16324 << T << S.LangOpts.CPlusPlus; 16325 } 16326 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16327 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16328 } 16329 } Diagnoser; 16330 16331 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16332 } 16333 16334 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16335 llvm::APSInt *Result, 16336 unsigned DiagID, 16337 AllowFoldKind CanFold) { 16338 class IDDiagnoser : public VerifyICEDiagnoser { 16339 unsigned DiagID; 16340 16341 public: 16342 IDDiagnoser(unsigned DiagID) 16343 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16344 16345 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16346 return S.Diag(Loc, DiagID); 16347 } 16348 } Diagnoser(DiagID); 16349 16350 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16351 } 16352 16353 Sema::SemaDiagnosticBuilder 16354 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16355 QualType T) { 16356 return diagnoseNotICE(S, Loc); 16357 } 16358 16359 Sema::SemaDiagnosticBuilder 16360 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16361 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16362 } 16363 16364 ExprResult 16365 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16366 VerifyICEDiagnoser &Diagnoser, 16367 AllowFoldKind CanFold) { 16368 SourceLocation DiagLoc = E->getBeginLoc(); 16369 16370 if (getLangOpts().CPlusPlus11) { 16371 // C++11 [expr.const]p5: 16372 // If an expression of literal class type is used in a context where an 16373 // integral constant expression is required, then that class type shall 16374 // have a single non-explicit conversion function to an integral or 16375 // unscoped enumeration type 16376 ExprResult Converted; 16377 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16378 VerifyICEDiagnoser &BaseDiagnoser; 16379 public: 16380 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16381 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16382 BaseDiagnoser.Suppress, true), 16383 BaseDiagnoser(BaseDiagnoser) {} 16384 16385 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16386 QualType T) override { 16387 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16388 } 16389 16390 SemaDiagnosticBuilder diagnoseIncomplete( 16391 Sema &S, SourceLocation Loc, QualType T) override { 16392 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16393 } 16394 16395 SemaDiagnosticBuilder diagnoseExplicitConv( 16396 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16397 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16398 } 16399 16400 SemaDiagnosticBuilder noteExplicitConv( 16401 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16402 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16403 << ConvTy->isEnumeralType() << ConvTy; 16404 } 16405 16406 SemaDiagnosticBuilder diagnoseAmbiguous( 16407 Sema &S, SourceLocation Loc, QualType T) override { 16408 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16409 } 16410 16411 SemaDiagnosticBuilder noteAmbiguous( 16412 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16413 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16414 << ConvTy->isEnumeralType() << ConvTy; 16415 } 16416 16417 SemaDiagnosticBuilder diagnoseConversion( 16418 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16419 llvm_unreachable("conversion functions are permitted"); 16420 } 16421 } ConvertDiagnoser(Diagnoser); 16422 16423 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16424 ConvertDiagnoser); 16425 if (Converted.isInvalid()) 16426 return Converted; 16427 E = Converted.get(); 16428 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16429 return ExprError(); 16430 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16431 // An ICE must be of integral or unscoped enumeration type. 16432 if (!Diagnoser.Suppress) 16433 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16434 << E->getSourceRange(); 16435 return ExprError(); 16436 } 16437 16438 ExprResult RValueExpr = DefaultLvalueConversion(E); 16439 if (RValueExpr.isInvalid()) 16440 return ExprError(); 16441 16442 E = RValueExpr.get(); 16443 16444 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16445 // in the non-ICE case. 16446 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16447 if (Result) 16448 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16449 if (!isa<ConstantExpr>(E)) 16450 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16451 : ConstantExpr::Create(Context, E); 16452 return E; 16453 } 16454 16455 Expr::EvalResult EvalResult; 16456 SmallVector<PartialDiagnosticAt, 8> Notes; 16457 EvalResult.Diag = &Notes; 16458 16459 // Try to evaluate the expression, and produce diagnostics explaining why it's 16460 // not a constant expression as a side-effect. 16461 bool Folded = 16462 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16463 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16464 16465 if (!isa<ConstantExpr>(E)) 16466 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16467 16468 // In C++11, we can rely on diagnostics being produced for any expression 16469 // which is not a constant expression. If no diagnostics were produced, then 16470 // this is a constant expression. 16471 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16472 if (Result) 16473 *Result = EvalResult.Val.getInt(); 16474 return E; 16475 } 16476 16477 // If our only note is the usual "invalid subexpression" note, just point 16478 // the caret at its location rather than producing an essentially 16479 // redundant note. 16480 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16481 diag::note_invalid_subexpr_in_const_expr) { 16482 DiagLoc = Notes[0].first; 16483 Notes.clear(); 16484 } 16485 16486 if (!Folded || !CanFold) { 16487 if (!Diagnoser.Suppress) { 16488 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16489 for (const PartialDiagnosticAt &Note : Notes) 16490 Diag(Note.first, Note.second); 16491 } 16492 16493 return ExprError(); 16494 } 16495 16496 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16497 for (const PartialDiagnosticAt &Note : Notes) 16498 Diag(Note.first, Note.second); 16499 16500 if (Result) 16501 *Result = EvalResult.Val.getInt(); 16502 return E; 16503 } 16504 16505 namespace { 16506 // Handle the case where we conclude a expression which we speculatively 16507 // considered to be unevaluated is actually evaluated. 16508 class TransformToPE : public TreeTransform<TransformToPE> { 16509 typedef TreeTransform<TransformToPE> BaseTransform; 16510 16511 public: 16512 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16513 16514 // Make sure we redo semantic analysis 16515 bool AlwaysRebuild() { return true; } 16516 bool ReplacingOriginal() { return true; } 16517 16518 // We need to special-case DeclRefExprs referring to FieldDecls which 16519 // are not part of a member pointer formation; normal TreeTransforming 16520 // doesn't catch this case because of the way we represent them in the AST. 16521 // FIXME: This is a bit ugly; is it really the best way to handle this 16522 // case? 16523 // 16524 // Error on DeclRefExprs referring to FieldDecls. 16525 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16526 if (isa<FieldDecl>(E->getDecl()) && 16527 !SemaRef.isUnevaluatedContext()) 16528 return SemaRef.Diag(E->getLocation(), 16529 diag::err_invalid_non_static_member_use) 16530 << E->getDecl() << E->getSourceRange(); 16531 16532 return BaseTransform::TransformDeclRefExpr(E); 16533 } 16534 16535 // Exception: filter out member pointer formation 16536 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16537 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16538 return E; 16539 16540 return BaseTransform::TransformUnaryOperator(E); 16541 } 16542 16543 // The body of a lambda-expression is in a separate expression evaluation 16544 // context so never needs to be transformed. 16545 // FIXME: Ideally we wouldn't transform the closure type either, and would 16546 // just recreate the capture expressions and lambda expression. 16547 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16548 return SkipLambdaBody(E, Body); 16549 } 16550 }; 16551 } 16552 16553 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16554 assert(isUnevaluatedContext() && 16555 "Should only transform unevaluated expressions"); 16556 ExprEvalContexts.back().Context = 16557 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16558 if (isUnevaluatedContext()) 16559 return E; 16560 return TransformToPE(*this).TransformExpr(E); 16561 } 16562 16563 void 16564 Sema::PushExpressionEvaluationContext( 16565 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16566 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16567 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16568 LambdaContextDecl, ExprContext); 16569 Cleanup.reset(); 16570 if (!MaybeODRUseExprs.empty()) 16571 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16572 } 16573 16574 void 16575 Sema::PushExpressionEvaluationContext( 16576 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16577 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16578 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16579 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16580 } 16581 16582 namespace { 16583 16584 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16585 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16586 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16587 if (E->getOpcode() == UO_Deref) 16588 return CheckPossibleDeref(S, E->getSubExpr()); 16589 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16590 return CheckPossibleDeref(S, E->getBase()); 16591 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16592 return CheckPossibleDeref(S, E->getBase()); 16593 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16594 QualType Inner; 16595 QualType Ty = E->getType(); 16596 if (const auto *Ptr = Ty->getAs<PointerType>()) 16597 Inner = Ptr->getPointeeType(); 16598 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16599 Inner = Arr->getElementType(); 16600 else 16601 return nullptr; 16602 16603 if (Inner->hasAttr(attr::NoDeref)) 16604 return E; 16605 } 16606 return nullptr; 16607 } 16608 16609 } // namespace 16610 16611 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16612 for (const Expr *E : Rec.PossibleDerefs) { 16613 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16614 if (DeclRef) { 16615 const ValueDecl *Decl = DeclRef->getDecl(); 16616 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16617 << Decl->getName() << E->getSourceRange(); 16618 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16619 } else { 16620 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16621 << E->getSourceRange(); 16622 } 16623 } 16624 Rec.PossibleDerefs.clear(); 16625 } 16626 16627 /// Check whether E, which is either a discarded-value expression or an 16628 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16629 /// and if so, remove it from the list of volatile-qualified assignments that 16630 /// we are going to warn are deprecated. 16631 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16632 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16633 return; 16634 16635 // Note: ignoring parens here is not justified by the standard rules, but 16636 // ignoring parentheses seems like a more reasonable approach, and this only 16637 // drives a deprecation warning so doesn't affect conformance. 16638 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16639 if (BO->getOpcode() == BO_Assign) { 16640 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16641 llvm::erase_value(LHSs, BO->getLHS()); 16642 } 16643 } 16644 } 16645 16646 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16647 if (isUnevaluatedContext() || !E.isUsable() || !Decl || 16648 !Decl->isConsteval() || isConstantEvaluated() || 16649 RebuildingImmediateInvocation || isImmediateFunctionContext()) 16650 return E; 16651 16652 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16653 /// It's OK if this fails; we'll also remove this in 16654 /// HandleImmediateInvocations, but catching it here allows us to avoid 16655 /// walking the AST looking for it in simple cases. 16656 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16657 if (auto *DeclRef = 16658 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16659 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16660 16661 E = MaybeCreateExprWithCleanups(E); 16662 16663 ConstantExpr *Res = ConstantExpr::Create( 16664 getASTContext(), E.get(), 16665 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16666 getASTContext()), 16667 /*IsImmediateInvocation*/ true); 16668 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16669 return Res; 16670 } 16671 16672 static void EvaluateAndDiagnoseImmediateInvocation( 16673 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16674 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16675 Expr::EvalResult Eval; 16676 Eval.Diag = &Notes; 16677 ConstantExpr *CE = Candidate.getPointer(); 16678 bool Result = CE->EvaluateAsConstantExpr( 16679 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16680 if (!Result || !Notes.empty()) { 16681 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16682 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16683 InnerExpr = FunctionalCast->getSubExpr(); 16684 FunctionDecl *FD = nullptr; 16685 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16686 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16687 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16688 FD = Call->getConstructor(); 16689 else 16690 llvm_unreachable("unhandled decl kind"); 16691 assert(FD->isConsteval()); 16692 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16693 for (auto &Note : Notes) 16694 SemaRef.Diag(Note.first, Note.second); 16695 return; 16696 } 16697 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16698 } 16699 16700 static void RemoveNestedImmediateInvocation( 16701 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16702 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16703 struct ComplexRemove : TreeTransform<ComplexRemove> { 16704 using Base = TreeTransform<ComplexRemove>; 16705 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16706 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16707 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16708 CurrentII; 16709 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16710 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16711 SmallVector<Sema::ImmediateInvocationCandidate, 16712 4>::reverse_iterator Current) 16713 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16714 void RemoveImmediateInvocation(ConstantExpr* E) { 16715 auto It = std::find_if(CurrentII, IISet.rend(), 16716 [E](Sema::ImmediateInvocationCandidate Elem) { 16717 return Elem.getPointer() == E; 16718 }); 16719 assert(It != IISet.rend() && 16720 "ConstantExpr marked IsImmediateInvocation should " 16721 "be present"); 16722 It->setInt(1); // Mark as deleted 16723 } 16724 ExprResult TransformConstantExpr(ConstantExpr *E) { 16725 if (!E->isImmediateInvocation()) 16726 return Base::TransformConstantExpr(E); 16727 RemoveImmediateInvocation(E); 16728 return Base::TransformExpr(E->getSubExpr()); 16729 } 16730 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16731 /// we need to remove its DeclRefExpr from the DRSet. 16732 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16733 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16734 return Base::TransformCXXOperatorCallExpr(E); 16735 } 16736 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16737 /// here. 16738 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16739 if (!Init) 16740 return Init; 16741 /// ConstantExpr are the first layer of implicit node to be removed so if 16742 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16743 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16744 if (CE->isImmediateInvocation()) 16745 RemoveImmediateInvocation(CE); 16746 return Base::TransformInitializer(Init, NotCopyInit); 16747 } 16748 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16749 DRSet.erase(E); 16750 return E; 16751 } 16752 bool AlwaysRebuild() { return false; } 16753 bool ReplacingOriginal() { return true; } 16754 bool AllowSkippingCXXConstructExpr() { 16755 bool Res = AllowSkippingFirstCXXConstructExpr; 16756 AllowSkippingFirstCXXConstructExpr = true; 16757 return Res; 16758 } 16759 bool AllowSkippingFirstCXXConstructExpr = true; 16760 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16761 Rec.ImmediateInvocationCandidates, It); 16762 16763 /// CXXConstructExpr with a single argument are getting skipped by 16764 /// TreeTransform in some situtation because they could be implicit. This 16765 /// can only occur for the top-level CXXConstructExpr because it is used 16766 /// nowhere in the expression being transformed therefore will not be rebuilt. 16767 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16768 /// skipping the first CXXConstructExpr. 16769 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16770 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16771 16772 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16773 assert(Res.isUsable()); 16774 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16775 It->getPointer()->setSubExpr(Res.get()); 16776 } 16777 16778 static void 16779 HandleImmediateInvocations(Sema &SemaRef, 16780 Sema::ExpressionEvaluationContextRecord &Rec) { 16781 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16782 Rec.ReferenceToConsteval.size() == 0) || 16783 SemaRef.RebuildingImmediateInvocation) 16784 return; 16785 16786 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16787 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16788 /// need to remove ReferenceToConsteval in the immediate invocation. 16789 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16790 16791 /// Prevent sema calls during the tree transform from adding pointers that 16792 /// are already in the sets. 16793 llvm::SaveAndRestore<bool> DisableIITracking( 16794 SemaRef.RebuildingImmediateInvocation, true); 16795 16796 /// Prevent diagnostic during tree transfrom as they are duplicates 16797 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16798 16799 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16800 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16801 if (!It->getInt()) 16802 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16803 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16804 Rec.ReferenceToConsteval.size()) { 16805 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16806 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16807 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16808 bool VisitDeclRefExpr(DeclRefExpr *E) { 16809 DRSet.erase(E); 16810 return DRSet.size(); 16811 } 16812 } Visitor(Rec.ReferenceToConsteval); 16813 Visitor.TraverseStmt( 16814 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16815 } 16816 for (auto CE : Rec.ImmediateInvocationCandidates) 16817 if (!CE.getInt()) 16818 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16819 for (auto DR : Rec.ReferenceToConsteval) { 16820 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16821 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16822 << FD; 16823 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16824 } 16825 } 16826 16827 void Sema::PopExpressionEvaluationContext() { 16828 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16829 unsigned NumTypos = Rec.NumTypos; 16830 16831 if (!Rec.Lambdas.empty()) { 16832 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16833 if (!getLangOpts().CPlusPlus20 && 16834 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 16835 Rec.isUnevaluated() || 16836 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 16837 unsigned D; 16838 if (Rec.isUnevaluated()) { 16839 // C++11 [expr.prim.lambda]p2: 16840 // A lambda-expression shall not appear in an unevaluated operand 16841 // (Clause 5). 16842 D = diag::err_lambda_unevaluated_operand; 16843 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16844 // C++1y [expr.const]p2: 16845 // A conditional-expression e is a core constant expression unless the 16846 // evaluation of e, following the rules of the abstract machine, would 16847 // evaluate [...] a lambda-expression. 16848 D = diag::err_lambda_in_constant_expression; 16849 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16850 // C++17 [expr.prim.lamda]p2: 16851 // A lambda-expression shall not appear [...] in a template-argument. 16852 D = diag::err_lambda_in_invalid_context; 16853 } else 16854 llvm_unreachable("Couldn't infer lambda error message."); 16855 16856 for (const auto *L : Rec.Lambdas) 16857 Diag(L->getBeginLoc(), D); 16858 } 16859 } 16860 16861 WarnOnPendingNoDerefs(Rec); 16862 HandleImmediateInvocations(*this, Rec); 16863 16864 // Warn on any volatile-qualified simple-assignments that are not discarded- 16865 // value expressions nor unevaluated operands (those cases get removed from 16866 // this list by CheckUnusedVolatileAssignment). 16867 for (auto *BO : Rec.VolatileAssignmentLHSs) 16868 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16869 << BO->getType(); 16870 16871 // When are coming out of an unevaluated context, clear out any 16872 // temporaries that we may have created as part of the evaluation of 16873 // the expression in that context: they aren't relevant because they 16874 // will never be constructed. 16875 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16876 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16877 ExprCleanupObjects.end()); 16878 Cleanup = Rec.ParentCleanup; 16879 CleanupVarDeclMarking(); 16880 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16881 // Otherwise, merge the contexts together. 16882 } else { 16883 Cleanup.mergeFrom(Rec.ParentCleanup); 16884 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16885 Rec.SavedMaybeODRUseExprs.end()); 16886 } 16887 16888 // Pop the current expression evaluation context off the stack. 16889 ExprEvalContexts.pop_back(); 16890 16891 // The global expression evaluation context record is never popped. 16892 ExprEvalContexts.back().NumTypos += NumTypos; 16893 } 16894 16895 void Sema::DiscardCleanupsInEvaluationContext() { 16896 ExprCleanupObjects.erase( 16897 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16898 ExprCleanupObjects.end()); 16899 Cleanup.reset(); 16900 MaybeODRUseExprs.clear(); 16901 } 16902 16903 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16904 ExprResult Result = CheckPlaceholderExpr(E); 16905 if (Result.isInvalid()) 16906 return ExprError(); 16907 E = Result.get(); 16908 if (!E->getType()->isVariablyModifiedType()) 16909 return E; 16910 return TransformToPotentiallyEvaluated(E); 16911 } 16912 16913 /// Are we in a context that is potentially constant evaluated per C++20 16914 /// [expr.const]p12? 16915 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16916 /// C++2a [expr.const]p12: 16917 // An expression or conversion is potentially constant evaluated if it is 16918 switch (SemaRef.ExprEvalContexts.back().Context) { 16919 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16920 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 16921 16922 // -- a manifestly constant-evaluated expression, 16923 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16924 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16925 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16926 // -- a potentially-evaluated expression, 16927 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16928 // -- an immediate subexpression of a braced-init-list, 16929 16930 // -- [FIXME] an expression of the form & cast-expression that occurs 16931 // within a templated entity 16932 // -- a subexpression of one of the above that is not a subexpression of 16933 // a nested unevaluated operand. 16934 return true; 16935 16936 case Sema::ExpressionEvaluationContext::Unevaluated: 16937 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16938 // Expressions in this context are never evaluated. 16939 return false; 16940 } 16941 llvm_unreachable("Invalid context"); 16942 } 16943 16944 /// Return true if this function has a calling convention that requires mangling 16945 /// in the size of the parameter pack. 16946 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16947 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16948 // we don't need parameter type sizes. 16949 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16950 if (!TT.isOSWindows() || !TT.isX86()) 16951 return false; 16952 16953 // If this is C++ and this isn't an extern "C" function, parameters do not 16954 // need to be complete. In this case, C++ mangling will apply, which doesn't 16955 // use the size of the parameters. 16956 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16957 return false; 16958 16959 // Stdcall, fastcall, and vectorcall need this special treatment. 16960 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16961 switch (CC) { 16962 case CC_X86StdCall: 16963 case CC_X86FastCall: 16964 case CC_X86VectorCall: 16965 return true; 16966 default: 16967 break; 16968 } 16969 return false; 16970 } 16971 16972 /// Require that all of the parameter types of function be complete. Normally, 16973 /// parameter types are only required to be complete when a function is called 16974 /// or defined, but to mangle functions with certain calling conventions, the 16975 /// mangler needs to know the size of the parameter list. In this situation, 16976 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16977 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16978 /// result in a linker error. Clang doesn't implement this behavior, and instead 16979 /// attempts to error at compile time. 16980 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16981 SourceLocation Loc) { 16982 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16983 FunctionDecl *FD; 16984 ParmVarDecl *Param; 16985 16986 public: 16987 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16988 : FD(FD), Param(Param) {} 16989 16990 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16991 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16992 StringRef CCName; 16993 switch (CC) { 16994 case CC_X86StdCall: 16995 CCName = "stdcall"; 16996 break; 16997 case CC_X86FastCall: 16998 CCName = "fastcall"; 16999 break; 17000 case CC_X86VectorCall: 17001 CCName = "vectorcall"; 17002 break; 17003 default: 17004 llvm_unreachable("CC does not need mangling"); 17005 } 17006 17007 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 17008 << Param->getDeclName() << FD->getDeclName() << CCName; 17009 } 17010 }; 17011 17012 for (ParmVarDecl *Param : FD->parameters()) { 17013 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 17014 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 17015 } 17016 } 17017 17018 namespace { 17019 enum class OdrUseContext { 17020 /// Declarations in this context are not odr-used. 17021 None, 17022 /// Declarations in this context are formally odr-used, but this is a 17023 /// dependent context. 17024 Dependent, 17025 /// Declarations in this context are odr-used but not actually used (yet). 17026 FormallyOdrUsed, 17027 /// Declarations in this context are used. 17028 Used 17029 }; 17030 } 17031 17032 /// Are we within a context in which references to resolved functions or to 17033 /// variables result in odr-use? 17034 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 17035 OdrUseContext Result; 17036 17037 switch (SemaRef.ExprEvalContexts.back().Context) { 17038 case Sema::ExpressionEvaluationContext::Unevaluated: 17039 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17040 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17041 return OdrUseContext::None; 17042 17043 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17044 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 17045 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17046 Result = OdrUseContext::Used; 17047 break; 17048 17049 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17050 Result = OdrUseContext::FormallyOdrUsed; 17051 break; 17052 17053 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17054 // A default argument formally results in odr-use, but doesn't actually 17055 // result in a use in any real sense until it itself is used. 17056 Result = OdrUseContext::FormallyOdrUsed; 17057 break; 17058 } 17059 17060 if (SemaRef.CurContext->isDependentContext()) 17061 return OdrUseContext::Dependent; 17062 17063 return Result; 17064 } 17065 17066 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 17067 if (!Func->isConstexpr()) 17068 return false; 17069 17070 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 17071 return true; 17072 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 17073 return CCD && CCD->getInheritedConstructor(); 17074 } 17075 17076 /// Mark a function referenced, and check whether it is odr-used 17077 /// (C++ [basic.def.odr]p2, C99 6.9p3) 17078 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 17079 bool MightBeOdrUse) { 17080 assert(Func && "No function?"); 17081 17082 Func->setReferenced(); 17083 17084 // Recursive functions aren't really used until they're used from some other 17085 // context. 17086 bool IsRecursiveCall = CurContext == Func; 17087 17088 // C++11 [basic.def.odr]p3: 17089 // A function whose name appears as a potentially-evaluated expression is 17090 // odr-used if it is the unique lookup result or the selected member of a 17091 // set of overloaded functions [...]. 17092 // 17093 // We (incorrectly) mark overload resolution as an unevaluated context, so we 17094 // can just check that here. 17095 OdrUseContext OdrUse = 17096 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 17097 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 17098 OdrUse = OdrUseContext::FormallyOdrUsed; 17099 17100 // Trivial default constructors and destructors are never actually used. 17101 // FIXME: What about other special members? 17102 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 17103 OdrUse == OdrUseContext::Used) { 17104 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 17105 if (Constructor->isDefaultConstructor()) 17106 OdrUse = OdrUseContext::FormallyOdrUsed; 17107 if (isa<CXXDestructorDecl>(Func)) 17108 OdrUse = OdrUseContext::FormallyOdrUsed; 17109 } 17110 17111 // C++20 [expr.const]p12: 17112 // A function [...] is needed for constant evaluation if it is [...] a 17113 // constexpr function that is named by an expression that is potentially 17114 // constant evaluated 17115 bool NeededForConstantEvaluation = 17116 isPotentiallyConstantEvaluatedContext(*this) && 17117 isImplicitlyDefinableConstexprFunction(Func); 17118 17119 // Determine whether we require a function definition to exist, per 17120 // C++11 [temp.inst]p3: 17121 // Unless a function template specialization has been explicitly 17122 // instantiated or explicitly specialized, the function template 17123 // specialization is implicitly instantiated when the specialization is 17124 // referenced in a context that requires a function definition to exist. 17125 // C++20 [temp.inst]p7: 17126 // The existence of a definition of a [...] function is considered to 17127 // affect the semantics of the program if the [...] function is needed for 17128 // constant evaluation by an expression 17129 // C++20 [basic.def.odr]p10: 17130 // Every program shall contain exactly one definition of every non-inline 17131 // function or variable that is odr-used in that program outside of a 17132 // discarded statement 17133 // C++20 [special]p1: 17134 // The implementation will implicitly define [defaulted special members] 17135 // if they are odr-used or needed for constant evaluation. 17136 // 17137 // Note that we skip the implicit instantiation of templates that are only 17138 // used in unused default arguments or by recursive calls to themselves. 17139 // This is formally non-conforming, but seems reasonable in practice. 17140 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 17141 NeededForConstantEvaluation); 17142 17143 // C++14 [temp.expl.spec]p6: 17144 // If a template [...] is explicitly specialized then that specialization 17145 // shall be declared before the first use of that specialization that would 17146 // cause an implicit instantiation to take place, in every translation unit 17147 // in which such a use occurs 17148 if (NeedDefinition && 17149 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 17150 Func->getMemberSpecializationInfo())) 17151 checkSpecializationVisibility(Loc, Func); 17152 17153 if (getLangOpts().CUDA) 17154 CheckCUDACall(Loc, Func); 17155 17156 if (getLangOpts().SYCLIsDevice) 17157 checkSYCLDeviceFunction(Loc, Func); 17158 17159 // If we need a definition, try to create one. 17160 if (NeedDefinition && !Func->getBody()) { 17161 runWithSufficientStackSpace(Loc, [&] { 17162 if (CXXConstructorDecl *Constructor = 17163 dyn_cast<CXXConstructorDecl>(Func)) { 17164 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 17165 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 17166 if (Constructor->isDefaultConstructor()) { 17167 if (Constructor->isTrivial() && 17168 !Constructor->hasAttr<DLLExportAttr>()) 17169 return; 17170 DefineImplicitDefaultConstructor(Loc, Constructor); 17171 } else if (Constructor->isCopyConstructor()) { 17172 DefineImplicitCopyConstructor(Loc, Constructor); 17173 } else if (Constructor->isMoveConstructor()) { 17174 DefineImplicitMoveConstructor(Loc, Constructor); 17175 } 17176 } else if (Constructor->getInheritedConstructor()) { 17177 DefineInheritingConstructor(Loc, Constructor); 17178 } 17179 } else if (CXXDestructorDecl *Destructor = 17180 dyn_cast<CXXDestructorDecl>(Func)) { 17181 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17182 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17183 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17184 return; 17185 DefineImplicitDestructor(Loc, Destructor); 17186 } 17187 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17188 MarkVTableUsed(Loc, Destructor->getParent()); 17189 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17190 if (MethodDecl->isOverloadedOperator() && 17191 MethodDecl->getOverloadedOperator() == OO_Equal) { 17192 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17193 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17194 if (MethodDecl->isCopyAssignmentOperator()) 17195 DefineImplicitCopyAssignment(Loc, MethodDecl); 17196 else if (MethodDecl->isMoveAssignmentOperator()) 17197 DefineImplicitMoveAssignment(Loc, MethodDecl); 17198 } 17199 } else if (isa<CXXConversionDecl>(MethodDecl) && 17200 MethodDecl->getParent()->isLambda()) { 17201 CXXConversionDecl *Conversion = 17202 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17203 if (Conversion->isLambdaToBlockPointerConversion()) 17204 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17205 else 17206 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17207 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17208 MarkVTableUsed(Loc, MethodDecl->getParent()); 17209 } 17210 17211 if (Func->isDefaulted() && !Func->isDeleted()) { 17212 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17213 if (DCK != DefaultedComparisonKind::None) 17214 DefineDefaultedComparison(Loc, Func, DCK); 17215 } 17216 17217 // Implicit instantiation of function templates and member functions of 17218 // class templates. 17219 if (Func->isImplicitlyInstantiable()) { 17220 TemplateSpecializationKind TSK = 17221 Func->getTemplateSpecializationKindForInstantiation(); 17222 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17223 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17224 if (FirstInstantiation) { 17225 PointOfInstantiation = Loc; 17226 if (auto *MSI = Func->getMemberSpecializationInfo()) 17227 MSI->setPointOfInstantiation(Loc); 17228 // FIXME: Notify listener. 17229 else 17230 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17231 } else if (TSK != TSK_ImplicitInstantiation) { 17232 // Use the point of use as the point of instantiation, instead of the 17233 // point of explicit instantiation (which we track as the actual point 17234 // of instantiation). This gives better backtraces in diagnostics. 17235 PointOfInstantiation = Loc; 17236 } 17237 17238 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17239 Func->isConstexpr()) { 17240 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17241 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17242 CodeSynthesisContexts.size()) 17243 PendingLocalImplicitInstantiations.push_back( 17244 std::make_pair(Func, PointOfInstantiation)); 17245 else if (Func->isConstexpr()) 17246 // Do not defer instantiations of constexpr functions, to avoid the 17247 // expression evaluator needing to call back into Sema if it sees a 17248 // call to such a function. 17249 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17250 else { 17251 Func->setInstantiationIsPending(true); 17252 PendingInstantiations.push_back( 17253 std::make_pair(Func, PointOfInstantiation)); 17254 // Notify the consumer that a function was implicitly instantiated. 17255 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17256 } 17257 } 17258 } else { 17259 // Walk redefinitions, as some of them may be instantiable. 17260 for (auto i : Func->redecls()) { 17261 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17262 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17263 } 17264 } 17265 }); 17266 } 17267 17268 // C++14 [except.spec]p17: 17269 // An exception-specification is considered to be needed when: 17270 // - the function is odr-used or, if it appears in an unevaluated operand, 17271 // would be odr-used if the expression were potentially-evaluated; 17272 // 17273 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17274 // function is a pure virtual function we're calling, and in that case the 17275 // function was selected by overload resolution and we need to resolve its 17276 // exception specification for a different reason. 17277 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17278 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17279 ResolveExceptionSpec(Loc, FPT); 17280 17281 // If this is the first "real" use, act on that. 17282 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17283 // Keep track of used but undefined functions. 17284 if (!Func->isDefined()) { 17285 if (mightHaveNonExternalLinkage(Func)) 17286 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17287 else if (Func->getMostRecentDecl()->isInlined() && 17288 !LangOpts.GNUInline && 17289 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17290 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17291 else if (isExternalWithNoLinkageType(Func)) 17292 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17293 } 17294 17295 // Some x86 Windows calling conventions mangle the size of the parameter 17296 // pack into the name. Computing the size of the parameters requires the 17297 // parameter types to be complete. Check that now. 17298 if (funcHasParameterSizeMangling(*this, Func)) 17299 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17300 17301 // In the MS C++ ABI, the compiler emits destructor variants where they are 17302 // used. If the destructor is used here but defined elsewhere, mark the 17303 // virtual base destructors referenced. If those virtual base destructors 17304 // are inline, this will ensure they are defined when emitting the complete 17305 // destructor variant. This checking may be redundant if the destructor is 17306 // provided later in this TU. 17307 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17308 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17309 CXXRecordDecl *Parent = Dtor->getParent(); 17310 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17311 CheckCompleteDestructorVariant(Loc, Dtor); 17312 } 17313 } 17314 17315 Func->markUsed(Context); 17316 } 17317 } 17318 17319 /// Directly mark a variable odr-used. Given a choice, prefer to use 17320 /// MarkVariableReferenced since it does additional checks and then 17321 /// calls MarkVarDeclODRUsed. 17322 /// If the variable must be captured: 17323 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17324 /// - else capture it in the DeclContext that maps to the 17325 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17326 static void 17327 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17328 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17329 // Keep track of used but undefined variables. 17330 // FIXME: We shouldn't suppress this warning for static data members. 17331 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17332 (!Var->isExternallyVisible() || Var->isInline() || 17333 SemaRef.isExternalWithNoLinkageType(Var)) && 17334 !(Var->isStaticDataMember() && Var->hasInit())) { 17335 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17336 if (old.isInvalid()) 17337 old = Loc; 17338 } 17339 QualType CaptureType, DeclRefType; 17340 if (SemaRef.LangOpts.OpenMP) 17341 SemaRef.tryCaptureOpenMPLambdas(Var); 17342 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17343 /*EllipsisLoc*/ SourceLocation(), 17344 /*BuildAndDiagnose*/ true, 17345 CaptureType, DeclRefType, 17346 FunctionScopeIndexToStopAt); 17347 17348 if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) { 17349 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 17350 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 17351 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 17352 if (VarTarget == Sema::CVT_Host && 17353 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 17354 UserTarget == Sema::CFT_Global)) { 17355 // Diagnose ODR-use of host global variables in device functions. 17356 // Reference of device global variables in host functions is allowed 17357 // through shadow variables therefore it is not diagnosed. 17358 if (SemaRef.LangOpts.CUDAIsDevice) { 17359 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 17360 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 17361 SemaRef.targetDiag(Var->getLocation(), 17362 Var->getType().isConstQualified() 17363 ? diag::note_cuda_const_var_unpromoted 17364 : diag::note_cuda_host_var); 17365 } 17366 } else if (VarTarget == Sema::CVT_Device && 17367 (UserTarget == Sema::CFT_Host || 17368 UserTarget == Sema::CFT_HostDevice) && 17369 !Var->hasExternalStorage()) { 17370 // Record a CUDA/HIP device side variable if it is ODR-used 17371 // by host code. This is done conservatively, when the variable is 17372 // referenced in any of the following contexts: 17373 // - a non-function context 17374 // - a host function 17375 // - a host device function 17376 // This makes the ODR-use of the device side variable by host code to 17377 // be visible in the device compilation for the compiler to be able to 17378 // emit template variables instantiated by host code only and to 17379 // externalize the static device side variable ODR-used by host code. 17380 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 17381 } 17382 } 17383 17384 Var->markUsed(SemaRef.Context); 17385 } 17386 17387 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17388 SourceLocation Loc, 17389 unsigned CapturingScopeIndex) { 17390 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17391 } 17392 17393 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17394 ValueDecl *var) { 17395 DeclContext *VarDC = var->getDeclContext(); 17396 17397 // If the parameter still belongs to the translation unit, then 17398 // we're actually just using one parameter in the declaration of 17399 // the next. 17400 if (isa<ParmVarDecl>(var) && 17401 isa<TranslationUnitDecl>(VarDC)) 17402 return; 17403 17404 // For C code, don't diagnose about capture if we're not actually in code 17405 // right now; it's impossible to write a non-constant expression outside of 17406 // function context, so we'll get other (more useful) diagnostics later. 17407 // 17408 // For C++, things get a bit more nasty... it would be nice to suppress this 17409 // diagnostic for certain cases like using a local variable in an array bound 17410 // for a member of a local class, but the correct predicate is not obvious. 17411 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17412 return; 17413 17414 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17415 unsigned ContextKind = 3; // unknown 17416 if (isa<CXXMethodDecl>(VarDC) && 17417 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17418 ContextKind = 2; 17419 } else if (isa<FunctionDecl>(VarDC)) { 17420 ContextKind = 0; 17421 } else if (isa<BlockDecl>(VarDC)) { 17422 ContextKind = 1; 17423 } 17424 17425 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17426 << var << ValueKind << ContextKind << VarDC; 17427 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17428 << var; 17429 17430 // FIXME: Add additional diagnostic info about class etc. which prevents 17431 // capture. 17432 } 17433 17434 17435 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17436 bool &SubCapturesAreNested, 17437 QualType &CaptureType, 17438 QualType &DeclRefType) { 17439 // Check whether we've already captured it. 17440 if (CSI->CaptureMap.count(Var)) { 17441 // If we found a capture, any subcaptures are nested. 17442 SubCapturesAreNested = true; 17443 17444 // Retrieve the capture type for this variable. 17445 CaptureType = CSI->getCapture(Var).getCaptureType(); 17446 17447 // Compute the type of an expression that refers to this variable. 17448 DeclRefType = CaptureType.getNonReferenceType(); 17449 17450 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17451 // are mutable in the sense that user can change their value - they are 17452 // private instances of the captured declarations. 17453 const Capture &Cap = CSI->getCapture(Var); 17454 if (Cap.isCopyCapture() && 17455 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17456 !(isa<CapturedRegionScopeInfo>(CSI) && 17457 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17458 DeclRefType.addConst(); 17459 return true; 17460 } 17461 return false; 17462 } 17463 17464 // Only block literals, captured statements, and lambda expressions can 17465 // capture; other scopes don't work. 17466 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17467 SourceLocation Loc, 17468 const bool Diagnose, Sema &S) { 17469 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17470 return getLambdaAwareParentOfDeclContext(DC); 17471 else if (Var->hasLocalStorage()) { 17472 if (Diagnose) 17473 diagnoseUncapturableValueReference(S, Loc, Var); 17474 } 17475 return nullptr; 17476 } 17477 17478 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17479 // certain types of variables (unnamed, variably modified types etc.) 17480 // so check for eligibility. 17481 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17482 SourceLocation Loc, 17483 const bool Diagnose, Sema &S) { 17484 17485 bool IsBlock = isa<BlockScopeInfo>(CSI); 17486 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17487 17488 // Lambdas are not allowed to capture unnamed variables 17489 // (e.g. anonymous unions). 17490 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17491 // assuming that's the intent. 17492 if (IsLambda && !Var->getDeclName()) { 17493 if (Diagnose) { 17494 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17495 S.Diag(Var->getLocation(), diag::note_declared_at); 17496 } 17497 return false; 17498 } 17499 17500 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17501 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17502 if (Diagnose) { 17503 S.Diag(Loc, diag::err_ref_vm_type); 17504 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17505 } 17506 return false; 17507 } 17508 // Prohibit structs with flexible array members too. 17509 // We cannot capture what is in the tail end of the struct. 17510 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17511 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17512 if (Diagnose) { 17513 if (IsBlock) 17514 S.Diag(Loc, diag::err_ref_flexarray_type); 17515 else 17516 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17517 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17518 } 17519 return false; 17520 } 17521 } 17522 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17523 // Lambdas and captured statements are not allowed to capture __block 17524 // variables; they don't support the expected semantics. 17525 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17526 if (Diagnose) { 17527 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17528 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17529 } 17530 return false; 17531 } 17532 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17533 if (S.getLangOpts().OpenCL && IsBlock && 17534 Var->getType()->isBlockPointerType()) { 17535 if (Diagnose) 17536 S.Diag(Loc, diag::err_opencl_block_ref_block); 17537 return false; 17538 } 17539 17540 return true; 17541 } 17542 17543 // Returns true if the capture by block was successful. 17544 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17545 SourceLocation Loc, 17546 const bool BuildAndDiagnose, 17547 QualType &CaptureType, 17548 QualType &DeclRefType, 17549 const bool Nested, 17550 Sema &S, bool Invalid) { 17551 bool ByRef = false; 17552 17553 // Blocks are not allowed to capture arrays, excepting OpenCL. 17554 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17555 // (decayed to pointers). 17556 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17557 if (BuildAndDiagnose) { 17558 S.Diag(Loc, diag::err_ref_array_type); 17559 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17560 Invalid = true; 17561 } else { 17562 return false; 17563 } 17564 } 17565 17566 // Forbid the block-capture of autoreleasing variables. 17567 if (!Invalid && 17568 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17569 if (BuildAndDiagnose) { 17570 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17571 << /*block*/ 0; 17572 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17573 Invalid = true; 17574 } else { 17575 return false; 17576 } 17577 } 17578 17579 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17580 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17581 QualType PointeeTy = PT->getPointeeType(); 17582 17583 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17584 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17585 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17586 if (BuildAndDiagnose) { 17587 SourceLocation VarLoc = Var->getLocation(); 17588 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17589 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17590 } 17591 } 17592 } 17593 17594 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17595 if (HasBlocksAttr || CaptureType->isReferenceType() || 17596 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17597 // Block capture by reference does not change the capture or 17598 // declaration reference types. 17599 ByRef = true; 17600 } else { 17601 // Block capture by copy introduces 'const'. 17602 CaptureType = CaptureType.getNonReferenceType().withConst(); 17603 DeclRefType = CaptureType; 17604 } 17605 17606 // Actually capture the variable. 17607 if (BuildAndDiagnose) 17608 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17609 CaptureType, Invalid); 17610 17611 return !Invalid; 17612 } 17613 17614 17615 /// Capture the given variable in the captured region. 17616 static bool captureInCapturedRegion( 17617 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 17618 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 17619 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 17620 bool IsTopScope, Sema &S, bool Invalid) { 17621 // By default, capture variables by reference. 17622 bool ByRef = true; 17623 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17624 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17625 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17626 // Using an LValue reference type is consistent with Lambdas (see below). 17627 if (S.isOpenMPCapturedDecl(Var)) { 17628 bool HasConst = DeclRefType.isConstQualified(); 17629 DeclRefType = DeclRefType.getUnqualifiedType(); 17630 // Don't lose diagnostics about assignments to const. 17631 if (HasConst) 17632 DeclRefType.addConst(); 17633 } 17634 // Do not capture firstprivates in tasks. 17635 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17636 OMPC_unknown) 17637 return true; 17638 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17639 RSI->OpenMPCaptureLevel); 17640 } 17641 17642 if (ByRef) 17643 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17644 else 17645 CaptureType = DeclRefType; 17646 17647 // Actually capture the variable. 17648 if (BuildAndDiagnose) 17649 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17650 Loc, SourceLocation(), CaptureType, Invalid); 17651 17652 return !Invalid; 17653 } 17654 17655 /// Capture the given variable in the lambda. 17656 static bool captureInLambda(LambdaScopeInfo *LSI, 17657 VarDecl *Var, 17658 SourceLocation Loc, 17659 const bool BuildAndDiagnose, 17660 QualType &CaptureType, 17661 QualType &DeclRefType, 17662 const bool RefersToCapturedVariable, 17663 const Sema::TryCaptureKind Kind, 17664 SourceLocation EllipsisLoc, 17665 const bool IsTopScope, 17666 Sema &S, bool Invalid) { 17667 // Determine whether we are capturing by reference or by value. 17668 bool ByRef = false; 17669 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17670 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17671 } else { 17672 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17673 } 17674 17675 // Compute the type of the field that will capture this variable. 17676 if (ByRef) { 17677 // C++11 [expr.prim.lambda]p15: 17678 // An entity is captured by reference if it is implicitly or 17679 // explicitly captured but not captured by copy. It is 17680 // unspecified whether additional unnamed non-static data 17681 // members are declared in the closure type for entities 17682 // captured by reference. 17683 // 17684 // FIXME: It is not clear whether we want to build an lvalue reference 17685 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17686 // to do the former, while EDG does the latter. Core issue 1249 will 17687 // clarify, but for now we follow GCC because it's a more permissive and 17688 // easily defensible position. 17689 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17690 } else { 17691 // C++11 [expr.prim.lambda]p14: 17692 // For each entity captured by copy, an unnamed non-static 17693 // data member is declared in the closure type. The 17694 // declaration order of these members is unspecified. The type 17695 // of such a data member is the type of the corresponding 17696 // captured entity if the entity is not a reference to an 17697 // object, or the referenced type otherwise. [Note: If the 17698 // captured entity is a reference to a function, the 17699 // corresponding data member is also a reference to a 17700 // function. - end note ] 17701 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17702 if (!RefType->getPointeeType()->isFunctionType()) 17703 CaptureType = RefType->getPointeeType(); 17704 } 17705 17706 // Forbid the lambda copy-capture of autoreleasing variables. 17707 if (!Invalid && 17708 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17709 if (BuildAndDiagnose) { 17710 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17711 S.Diag(Var->getLocation(), diag::note_previous_decl) 17712 << Var->getDeclName(); 17713 Invalid = true; 17714 } else { 17715 return false; 17716 } 17717 } 17718 17719 // Make sure that by-copy captures are of a complete and non-abstract type. 17720 if (!Invalid && BuildAndDiagnose) { 17721 if (!CaptureType->isDependentType() && 17722 S.RequireCompleteSizedType( 17723 Loc, CaptureType, 17724 diag::err_capture_of_incomplete_or_sizeless_type, 17725 Var->getDeclName())) 17726 Invalid = true; 17727 else if (S.RequireNonAbstractType(Loc, CaptureType, 17728 diag::err_capture_of_abstract_type)) 17729 Invalid = true; 17730 } 17731 } 17732 17733 // Compute the type of a reference to this captured variable. 17734 if (ByRef) 17735 DeclRefType = CaptureType.getNonReferenceType(); 17736 else { 17737 // C++ [expr.prim.lambda]p5: 17738 // The closure type for a lambda-expression has a public inline 17739 // function call operator [...]. This function call operator is 17740 // declared const (9.3.1) if and only if the lambda-expression's 17741 // parameter-declaration-clause is not followed by mutable. 17742 DeclRefType = CaptureType.getNonReferenceType(); 17743 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17744 DeclRefType.addConst(); 17745 } 17746 17747 // Add the capture. 17748 if (BuildAndDiagnose) 17749 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17750 Loc, EllipsisLoc, CaptureType, Invalid); 17751 17752 return !Invalid; 17753 } 17754 17755 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 17756 // Offer a Copy fix even if the type is dependent. 17757 if (Var->getType()->isDependentType()) 17758 return true; 17759 QualType T = Var->getType().getNonReferenceType(); 17760 if (T.isTriviallyCopyableType(Context)) 17761 return true; 17762 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 17763 17764 if (!(RD = RD->getDefinition())) 17765 return false; 17766 if (RD->hasSimpleCopyConstructor()) 17767 return true; 17768 if (RD->hasUserDeclaredCopyConstructor()) 17769 for (CXXConstructorDecl *Ctor : RD->ctors()) 17770 if (Ctor->isCopyConstructor()) 17771 return !Ctor->isDeleted(); 17772 } 17773 return false; 17774 } 17775 17776 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 17777 /// default capture. Fixes may be omitted if they aren't allowed by the 17778 /// standard, for example we can't emit a default copy capture fix-it if we 17779 /// already explicitly copy capture capture another variable. 17780 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 17781 VarDecl *Var) { 17782 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 17783 // Don't offer Capture by copy of default capture by copy fixes if Var is 17784 // known not to be copy constructible. 17785 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 17786 17787 SmallString<32> FixBuffer; 17788 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 17789 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 17790 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 17791 if (ShouldOfferCopyFix) { 17792 // Offer fixes to insert an explicit capture for the variable. 17793 // [] -> [VarName] 17794 // [OtherCapture] -> [OtherCapture, VarName] 17795 FixBuffer.assign({Separator, Var->getName()}); 17796 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17797 << Var << /*value*/ 0 17798 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17799 } 17800 // As above but capture by reference. 17801 FixBuffer.assign({Separator, "&", Var->getName()}); 17802 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17803 << Var << /*reference*/ 1 17804 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17805 } 17806 17807 // Only try to offer default capture if there are no captures excluding this 17808 // and init captures. 17809 // [this]: OK. 17810 // [X = Y]: OK. 17811 // [&A, &B]: Don't offer. 17812 // [A, B]: Don't offer. 17813 if (llvm::any_of(LSI->Captures, [](Capture &C) { 17814 return !C.isThisCapture() && !C.isInitCapture(); 17815 })) 17816 return; 17817 17818 // The default capture specifiers, '=' or '&', must appear first in the 17819 // capture body. 17820 SourceLocation DefaultInsertLoc = 17821 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 17822 17823 if (ShouldOfferCopyFix) { 17824 bool CanDefaultCopyCapture = true; 17825 // [=, *this] OK since c++17 17826 // [=, this] OK since c++20 17827 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 17828 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 17829 ? LSI->getCXXThisCapture().isCopyCapture() 17830 : false; 17831 // We can't use default capture by copy if any captures already specified 17832 // capture by copy. 17833 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 17834 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 17835 })) { 17836 FixBuffer.assign({"=", Separator}); 17837 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17838 << /*value*/ 0 17839 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17840 } 17841 } 17842 17843 // We can't use default capture by reference if any captures already specified 17844 // capture by reference. 17845 if (llvm::none_of(LSI->Captures, [](Capture &C) { 17846 return !C.isInitCapture() && C.isReferenceCapture() && 17847 !C.isThisCapture(); 17848 })) { 17849 FixBuffer.assign({"&", Separator}); 17850 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17851 << /*reference*/ 1 17852 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17853 } 17854 } 17855 17856 bool Sema::tryCaptureVariable( 17857 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17858 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17859 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17860 // An init-capture is notionally from the context surrounding its 17861 // declaration, but its parent DC is the lambda class. 17862 DeclContext *VarDC = Var->getDeclContext(); 17863 if (Var->isInitCapture()) 17864 VarDC = VarDC->getParent(); 17865 17866 DeclContext *DC = CurContext; 17867 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17868 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17869 // We need to sync up the Declaration Context with the 17870 // FunctionScopeIndexToStopAt 17871 if (FunctionScopeIndexToStopAt) { 17872 unsigned FSIndex = FunctionScopes.size() - 1; 17873 while (FSIndex != MaxFunctionScopesIndex) { 17874 DC = getLambdaAwareParentOfDeclContext(DC); 17875 --FSIndex; 17876 } 17877 } 17878 17879 17880 // If the variable is declared in the current context, there is no need to 17881 // capture it. 17882 if (VarDC == DC) return true; 17883 17884 // Capture global variables if it is required to use private copy of this 17885 // variable. 17886 bool IsGlobal = !Var->hasLocalStorage(); 17887 if (IsGlobal && 17888 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17889 MaxFunctionScopesIndex))) 17890 return true; 17891 Var = Var->getCanonicalDecl(); 17892 17893 // Walk up the stack to determine whether we can capture the variable, 17894 // performing the "simple" checks that don't depend on type. We stop when 17895 // we've either hit the declared scope of the variable or find an existing 17896 // capture of that variable. We start from the innermost capturing-entity 17897 // (the DC) and ensure that all intervening capturing-entities 17898 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17899 // declcontext can either capture the variable or have already captured 17900 // the variable. 17901 CaptureType = Var->getType(); 17902 DeclRefType = CaptureType.getNonReferenceType(); 17903 bool Nested = false; 17904 bool Explicit = (Kind != TryCapture_Implicit); 17905 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17906 do { 17907 // Only block literals, captured statements, and lambda expressions can 17908 // capture; other scopes don't work. 17909 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17910 ExprLoc, 17911 BuildAndDiagnose, 17912 *this); 17913 // We need to check for the parent *first* because, if we *have* 17914 // private-captured a global variable, we need to recursively capture it in 17915 // intermediate blocks, lambdas, etc. 17916 if (!ParentDC) { 17917 if (IsGlobal) { 17918 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17919 break; 17920 } 17921 return true; 17922 } 17923 17924 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17925 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17926 17927 17928 // Check whether we've already captured it. 17929 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17930 DeclRefType)) { 17931 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17932 break; 17933 } 17934 // If we are instantiating a generic lambda call operator body, 17935 // we do not want to capture new variables. What was captured 17936 // during either a lambdas transformation or initial parsing 17937 // should be used. 17938 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17939 if (BuildAndDiagnose) { 17940 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17941 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17942 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17943 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17944 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17945 buildLambdaCaptureFixit(*this, LSI, Var); 17946 } else 17947 diagnoseUncapturableValueReference(*this, ExprLoc, Var); 17948 } 17949 return true; 17950 } 17951 17952 // Try to capture variable-length arrays types. 17953 if (Var->getType()->isVariablyModifiedType()) { 17954 // We're going to walk down into the type and look for VLA 17955 // expressions. 17956 QualType QTy = Var->getType(); 17957 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17958 QTy = PVD->getOriginalType(); 17959 captureVariablyModifiedType(Context, QTy, CSI); 17960 } 17961 17962 if (getLangOpts().OpenMP) { 17963 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17964 // OpenMP private variables should not be captured in outer scope, so 17965 // just break here. Similarly, global variables that are captured in a 17966 // target region should not be captured outside the scope of the region. 17967 if (RSI->CapRegionKind == CR_OpenMP) { 17968 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17969 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17970 // If the variable is private (i.e. not captured) and has variably 17971 // modified type, we still need to capture the type for correct 17972 // codegen in all regions, associated with the construct. Currently, 17973 // it is captured in the innermost captured region only. 17974 if (IsOpenMPPrivateDecl != OMPC_unknown && 17975 Var->getType()->isVariablyModifiedType()) { 17976 QualType QTy = Var->getType(); 17977 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17978 QTy = PVD->getOriginalType(); 17979 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17980 I < E; ++I) { 17981 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17982 FunctionScopes[FunctionScopesIndex - I]); 17983 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17984 "Wrong number of captured regions associated with the " 17985 "OpenMP construct."); 17986 captureVariablyModifiedType(Context, QTy, OuterRSI); 17987 } 17988 } 17989 bool IsTargetCap = 17990 IsOpenMPPrivateDecl != OMPC_private && 17991 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17992 RSI->OpenMPCaptureLevel); 17993 // Do not capture global if it is not privatized in outer regions. 17994 bool IsGlobalCap = 17995 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17996 RSI->OpenMPCaptureLevel); 17997 17998 // When we detect target captures we are looking from inside the 17999 // target region, therefore we need to propagate the capture from the 18000 // enclosing region. Therefore, the capture is not initially nested. 18001 if (IsTargetCap) 18002 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 18003 18004 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 18005 (IsGlobal && !IsGlobalCap)) { 18006 Nested = !IsTargetCap; 18007 bool HasConst = DeclRefType.isConstQualified(); 18008 DeclRefType = DeclRefType.getUnqualifiedType(); 18009 // Don't lose diagnostics about assignments to const. 18010 if (HasConst) 18011 DeclRefType.addConst(); 18012 CaptureType = Context.getLValueReferenceType(DeclRefType); 18013 break; 18014 } 18015 } 18016 } 18017 } 18018 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 18019 // No capture-default, and this is not an explicit capture 18020 // so cannot capture this variable. 18021 if (BuildAndDiagnose) { 18022 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18023 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18024 auto *LSI = cast<LambdaScopeInfo>(CSI); 18025 if (LSI->Lambda) { 18026 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18027 buildLambdaCaptureFixit(*this, LSI, Var); 18028 } 18029 // FIXME: If we error out because an outer lambda can not implicitly 18030 // capture a variable that an inner lambda explicitly captures, we 18031 // should have the inner lambda do the explicit capture - because 18032 // it makes for cleaner diagnostics later. This would purely be done 18033 // so that the diagnostic does not misleadingly claim that a variable 18034 // can not be captured by a lambda implicitly even though it is captured 18035 // explicitly. Suggestion: 18036 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 18037 // at the function head 18038 // - cache the StartingDeclContext - this must be a lambda 18039 // - captureInLambda in the innermost lambda the variable. 18040 } 18041 return true; 18042 } 18043 18044 FunctionScopesIndex--; 18045 DC = ParentDC; 18046 Explicit = false; 18047 } while (!VarDC->Equals(DC)); 18048 18049 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 18050 // computing the type of the capture at each step, checking type-specific 18051 // requirements, and adding captures if requested. 18052 // If the variable had already been captured previously, we start capturing 18053 // at the lambda nested within that one. 18054 bool Invalid = false; 18055 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 18056 ++I) { 18057 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 18058 18059 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18060 // certain types of variables (unnamed, variably modified types etc.) 18061 // so check for eligibility. 18062 if (!Invalid) 18063 Invalid = 18064 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 18065 18066 // After encountering an error, if we're actually supposed to capture, keep 18067 // capturing in nested contexts to suppress any follow-on diagnostics. 18068 if (Invalid && !BuildAndDiagnose) 18069 return true; 18070 18071 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 18072 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18073 DeclRefType, Nested, *this, Invalid); 18074 Nested = true; 18075 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18076 Invalid = !captureInCapturedRegion( 18077 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 18078 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 18079 Nested = true; 18080 } else { 18081 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18082 Invalid = 18083 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18084 DeclRefType, Nested, Kind, EllipsisLoc, 18085 /*IsTopScope*/ I == N - 1, *this, Invalid); 18086 Nested = true; 18087 } 18088 18089 if (Invalid && !BuildAndDiagnose) 18090 return true; 18091 } 18092 return Invalid; 18093 } 18094 18095 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 18096 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 18097 QualType CaptureType; 18098 QualType DeclRefType; 18099 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 18100 /*BuildAndDiagnose=*/true, CaptureType, 18101 DeclRefType, nullptr); 18102 } 18103 18104 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 18105 QualType CaptureType; 18106 QualType DeclRefType; 18107 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18108 /*BuildAndDiagnose=*/false, CaptureType, 18109 DeclRefType, nullptr); 18110 } 18111 18112 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 18113 QualType CaptureType; 18114 QualType DeclRefType; 18115 18116 // Determine whether we can capture this variable. 18117 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18118 /*BuildAndDiagnose=*/false, CaptureType, 18119 DeclRefType, nullptr)) 18120 return QualType(); 18121 18122 return DeclRefType; 18123 } 18124 18125 namespace { 18126 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 18127 // The produced TemplateArgumentListInfo* points to data stored within this 18128 // object, so should only be used in contexts where the pointer will not be 18129 // used after the CopiedTemplateArgs object is destroyed. 18130 class CopiedTemplateArgs { 18131 bool HasArgs; 18132 TemplateArgumentListInfo TemplateArgStorage; 18133 public: 18134 template<typename RefExpr> 18135 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 18136 if (HasArgs) 18137 E->copyTemplateArgumentsInto(TemplateArgStorage); 18138 } 18139 operator TemplateArgumentListInfo*() 18140 #ifdef __has_cpp_attribute 18141 #if __has_cpp_attribute(clang::lifetimebound) 18142 [[clang::lifetimebound]] 18143 #endif 18144 #endif 18145 { 18146 return HasArgs ? &TemplateArgStorage : nullptr; 18147 } 18148 }; 18149 } 18150 18151 /// Walk the set of potential results of an expression and mark them all as 18152 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 18153 /// 18154 /// \return A new expression if we found any potential results, ExprEmpty() if 18155 /// not, and ExprError() if we diagnosed an error. 18156 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 18157 NonOdrUseReason NOUR) { 18158 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 18159 // an object that satisfies the requirements for appearing in a 18160 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 18161 // is immediately applied." This function handles the lvalue-to-rvalue 18162 // conversion part. 18163 // 18164 // If we encounter a node that claims to be an odr-use but shouldn't be, we 18165 // transform it into the relevant kind of non-odr-use node and rebuild the 18166 // tree of nodes leading to it. 18167 // 18168 // This is a mini-TreeTransform that only transforms a restricted subset of 18169 // nodes (and only certain operands of them). 18170 18171 // Rebuild a subexpression. 18172 auto Rebuild = [&](Expr *Sub) { 18173 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 18174 }; 18175 18176 // Check whether a potential result satisfies the requirements of NOUR. 18177 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 18178 // Any entity other than a VarDecl is always odr-used whenever it's named 18179 // in a potentially-evaluated expression. 18180 auto *VD = dyn_cast<VarDecl>(D); 18181 if (!VD) 18182 return true; 18183 18184 // C++2a [basic.def.odr]p4: 18185 // A variable x whose name appears as a potentially-evalauted expression 18186 // e is odr-used by e unless 18187 // -- x is a reference that is usable in constant expressions, or 18188 // -- x is a variable of non-reference type that is usable in constant 18189 // expressions and has no mutable subobjects, and e is an element of 18190 // the set of potential results of an expression of 18191 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18192 // conversion is applied, or 18193 // -- x is a variable of non-reference type, and e is an element of the 18194 // set of potential results of a discarded-value expression to which 18195 // the lvalue-to-rvalue conversion is not applied 18196 // 18197 // We check the first bullet and the "potentially-evaluated" condition in 18198 // BuildDeclRefExpr. We check the type requirements in the second bullet 18199 // in CheckLValueToRValueConversionOperand below. 18200 switch (NOUR) { 18201 case NOUR_None: 18202 case NOUR_Unevaluated: 18203 llvm_unreachable("unexpected non-odr-use-reason"); 18204 18205 case NOUR_Constant: 18206 // Constant references were handled when they were built. 18207 if (VD->getType()->isReferenceType()) 18208 return true; 18209 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18210 if (RD->hasMutableFields()) 18211 return true; 18212 if (!VD->isUsableInConstantExpressions(S.Context)) 18213 return true; 18214 break; 18215 18216 case NOUR_Discarded: 18217 if (VD->getType()->isReferenceType()) 18218 return true; 18219 break; 18220 } 18221 return false; 18222 }; 18223 18224 // Mark that this expression does not constitute an odr-use. 18225 auto MarkNotOdrUsed = [&] { 18226 S.MaybeODRUseExprs.remove(E); 18227 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18228 LSI->markVariableExprAsNonODRUsed(E); 18229 }; 18230 18231 // C++2a [basic.def.odr]p2: 18232 // The set of potential results of an expression e is defined as follows: 18233 switch (E->getStmtClass()) { 18234 // -- If e is an id-expression, ... 18235 case Expr::DeclRefExprClass: { 18236 auto *DRE = cast<DeclRefExpr>(E); 18237 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18238 break; 18239 18240 // Rebuild as a non-odr-use DeclRefExpr. 18241 MarkNotOdrUsed(); 18242 return DeclRefExpr::Create( 18243 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18244 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18245 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18246 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18247 } 18248 18249 case Expr::FunctionParmPackExprClass: { 18250 auto *FPPE = cast<FunctionParmPackExpr>(E); 18251 // If any of the declarations in the pack is odr-used, then the expression 18252 // as a whole constitutes an odr-use. 18253 for (VarDecl *D : *FPPE) 18254 if (IsPotentialResultOdrUsed(D)) 18255 return ExprEmpty(); 18256 18257 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18258 // nothing cares about whether we marked this as an odr-use, but it might 18259 // be useful for non-compiler tools. 18260 MarkNotOdrUsed(); 18261 break; 18262 } 18263 18264 // -- If e is a subscripting operation with an array operand... 18265 case Expr::ArraySubscriptExprClass: { 18266 auto *ASE = cast<ArraySubscriptExpr>(E); 18267 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18268 if (!OldBase->getType()->isArrayType()) 18269 break; 18270 ExprResult Base = Rebuild(OldBase); 18271 if (!Base.isUsable()) 18272 return Base; 18273 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18274 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18275 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18276 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18277 ASE->getRBracketLoc()); 18278 } 18279 18280 case Expr::MemberExprClass: { 18281 auto *ME = cast<MemberExpr>(E); 18282 // -- If e is a class member access expression [...] naming a non-static 18283 // data member... 18284 if (isa<FieldDecl>(ME->getMemberDecl())) { 18285 ExprResult Base = Rebuild(ME->getBase()); 18286 if (!Base.isUsable()) 18287 return Base; 18288 return MemberExpr::Create( 18289 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18290 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18291 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18292 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18293 ME->getObjectKind(), ME->isNonOdrUse()); 18294 } 18295 18296 if (ME->getMemberDecl()->isCXXInstanceMember()) 18297 break; 18298 18299 // -- If e is a class member access expression naming a static data member, 18300 // ... 18301 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18302 break; 18303 18304 // Rebuild as a non-odr-use MemberExpr. 18305 MarkNotOdrUsed(); 18306 return MemberExpr::Create( 18307 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 18308 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 18309 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 18310 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 18311 } 18312 18313 case Expr::BinaryOperatorClass: { 18314 auto *BO = cast<BinaryOperator>(E); 18315 Expr *LHS = BO->getLHS(); 18316 Expr *RHS = BO->getRHS(); 18317 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18318 if (BO->getOpcode() == BO_PtrMemD) { 18319 ExprResult Sub = Rebuild(LHS); 18320 if (!Sub.isUsable()) 18321 return Sub; 18322 LHS = Sub.get(); 18323 // -- If e is a comma expression, ... 18324 } else if (BO->getOpcode() == BO_Comma) { 18325 ExprResult Sub = Rebuild(RHS); 18326 if (!Sub.isUsable()) 18327 return Sub; 18328 RHS = Sub.get(); 18329 } else { 18330 break; 18331 } 18332 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18333 LHS, RHS); 18334 } 18335 18336 // -- If e has the form (e1)... 18337 case Expr::ParenExprClass: { 18338 auto *PE = cast<ParenExpr>(E); 18339 ExprResult Sub = Rebuild(PE->getSubExpr()); 18340 if (!Sub.isUsable()) 18341 return Sub; 18342 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18343 } 18344 18345 // -- If e is a glvalue conditional expression, ... 18346 // We don't apply this to a binary conditional operator. FIXME: Should we? 18347 case Expr::ConditionalOperatorClass: { 18348 auto *CO = cast<ConditionalOperator>(E); 18349 ExprResult LHS = Rebuild(CO->getLHS()); 18350 if (LHS.isInvalid()) 18351 return ExprError(); 18352 ExprResult RHS = Rebuild(CO->getRHS()); 18353 if (RHS.isInvalid()) 18354 return ExprError(); 18355 if (!LHS.isUsable() && !RHS.isUsable()) 18356 return ExprEmpty(); 18357 if (!LHS.isUsable()) 18358 LHS = CO->getLHS(); 18359 if (!RHS.isUsable()) 18360 RHS = CO->getRHS(); 18361 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18362 CO->getCond(), LHS.get(), RHS.get()); 18363 } 18364 18365 // [Clang extension] 18366 // -- If e has the form __extension__ e1... 18367 case Expr::UnaryOperatorClass: { 18368 auto *UO = cast<UnaryOperator>(E); 18369 if (UO->getOpcode() != UO_Extension) 18370 break; 18371 ExprResult Sub = Rebuild(UO->getSubExpr()); 18372 if (!Sub.isUsable()) 18373 return Sub; 18374 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18375 Sub.get()); 18376 } 18377 18378 // [Clang extension] 18379 // -- If e has the form _Generic(...), the set of potential results is the 18380 // union of the sets of potential results of the associated expressions. 18381 case Expr::GenericSelectionExprClass: { 18382 auto *GSE = cast<GenericSelectionExpr>(E); 18383 18384 SmallVector<Expr *, 4> AssocExprs; 18385 bool AnyChanged = false; 18386 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18387 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18388 if (AssocExpr.isInvalid()) 18389 return ExprError(); 18390 if (AssocExpr.isUsable()) { 18391 AssocExprs.push_back(AssocExpr.get()); 18392 AnyChanged = true; 18393 } else { 18394 AssocExprs.push_back(OrigAssocExpr); 18395 } 18396 } 18397 18398 return AnyChanged ? S.CreateGenericSelectionExpr( 18399 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18400 GSE->getRParenLoc(), GSE->getControllingExpr(), 18401 GSE->getAssocTypeSourceInfos(), AssocExprs) 18402 : ExprEmpty(); 18403 } 18404 18405 // [Clang extension] 18406 // -- If e has the form __builtin_choose_expr(...), the set of potential 18407 // results is the union of the sets of potential results of the 18408 // second and third subexpressions. 18409 case Expr::ChooseExprClass: { 18410 auto *CE = cast<ChooseExpr>(E); 18411 18412 ExprResult LHS = Rebuild(CE->getLHS()); 18413 if (LHS.isInvalid()) 18414 return ExprError(); 18415 18416 ExprResult RHS = Rebuild(CE->getLHS()); 18417 if (RHS.isInvalid()) 18418 return ExprError(); 18419 18420 if (!LHS.get() && !RHS.get()) 18421 return ExprEmpty(); 18422 if (!LHS.isUsable()) 18423 LHS = CE->getLHS(); 18424 if (!RHS.isUsable()) 18425 RHS = CE->getRHS(); 18426 18427 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18428 RHS.get(), CE->getRParenLoc()); 18429 } 18430 18431 // Step through non-syntactic nodes. 18432 case Expr::ConstantExprClass: { 18433 auto *CE = cast<ConstantExpr>(E); 18434 ExprResult Sub = Rebuild(CE->getSubExpr()); 18435 if (!Sub.isUsable()) 18436 return Sub; 18437 return ConstantExpr::Create(S.Context, Sub.get()); 18438 } 18439 18440 // We could mostly rely on the recursive rebuilding to rebuild implicit 18441 // casts, but not at the top level, so rebuild them here. 18442 case Expr::ImplicitCastExprClass: { 18443 auto *ICE = cast<ImplicitCastExpr>(E); 18444 // Only step through the narrow set of cast kinds we expect to encounter. 18445 // Anything else suggests we've left the region in which potential results 18446 // can be found. 18447 switch (ICE->getCastKind()) { 18448 case CK_NoOp: 18449 case CK_DerivedToBase: 18450 case CK_UncheckedDerivedToBase: { 18451 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18452 if (!Sub.isUsable()) 18453 return Sub; 18454 CXXCastPath Path(ICE->path()); 18455 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18456 ICE->getValueKind(), &Path); 18457 } 18458 18459 default: 18460 break; 18461 } 18462 break; 18463 } 18464 18465 default: 18466 break; 18467 } 18468 18469 // Can't traverse through this node. Nothing to do. 18470 return ExprEmpty(); 18471 } 18472 18473 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18474 // Check whether the operand is or contains an object of non-trivial C union 18475 // type. 18476 if (E->getType().isVolatileQualified() && 18477 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18478 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18479 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18480 Sema::NTCUC_LValueToRValueVolatile, 18481 NTCUK_Destruct|NTCUK_Copy); 18482 18483 // C++2a [basic.def.odr]p4: 18484 // [...] an expression of non-volatile-qualified non-class type to which 18485 // the lvalue-to-rvalue conversion is applied [...] 18486 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18487 return E; 18488 18489 ExprResult Result = 18490 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18491 if (Result.isInvalid()) 18492 return ExprError(); 18493 return Result.get() ? Result : E; 18494 } 18495 18496 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18497 Res = CorrectDelayedTyposInExpr(Res); 18498 18499 if (!Res.isUsable()) 18500 return Res; 18501 18502 // If a constant-expression is a reference to a variable where we delay 18503 // deciding whether it is an odr-use, just assume we will apply the 18504 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18505 // (a non-type template argument), we have special handling anyway. 18506 return CheckLValueToRValueConversionOperand(Res.get()); 18507 } 18508 18509 void Sema::CleanupVarDeclMarking() { 18510 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18511 // call. 18512 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18513 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18514 18515 for (Expr *E : LocalMaybeODRUseExprs) { 18516 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18517 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18518 DRE->getLocation(), *this); 18519 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18520 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18521 *this); 18522 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18523 for (VarDecl *VD : *FP) 18524 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18525 } else { 18526 llvm_unreachable("Unexpected expression"); 18527 } 18528 } 18529 18530 assert(MaybeODRUseExprs.empty() && 18531 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18532 } 18533 18534 static void DoMarkVarDeclReferenced( 18535 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 18536 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18537 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18538 isa<FunctionParmPackExpr>(E)) && 18539 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18540 Var->setReferenced(); 18541 18542 if (Var->isInvalidDecl()) 18543 return; 18544 18545 auto *MSI = Var->getMemberSpecializationInfo(); 18546 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18547 : Var->getTemplateSpecializationKind(); 18548 18549 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18550 bool UsableInConstantExpr = 18551 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18552 18553 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 18554 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 18555 } 18556 18557 // C++20 [expr.const]p12: 18558 // A variable [...] is needed for constant evaluation if it is [...] a 18559 // variable whose name appears as a potentially constant evaluated 18560 // expression that is either a contexpr variable or is of non-volatile 18561 // const-qualified integral type or of reference type 18562 bool NeededForConstantEvaluation = 18563 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18564 18565 bool NeedDefinition = 18566 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18567 18568 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18569 "Can't instantiate a partial template specialization."); 18570 18571 // If this might be a member specialization of a static data member, check 18572 // the specialization is visible. We already did the checks for variable 18573 // template specializations when we created them. 18574 if (NeedDefinition && TSK != TSK_Undeclared && 18575 !isa<VarTemplateSpecializationDecl>(Var)) 18576 SemaRef.checkSpecializationVisibility(Loc, Var); 18577 18578 // Perform implicit instantiation of static data members, static data member 18579 // templates of class templates, and variable template specializations. Delay 18580 // instantiations of variable templates, except for those that could be used 18581 // in a constant expression. 18582 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18583 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18584 // instantiation declaration if a variable is usable in a constant 18585 // expression (among other cases). 18586 bool TryInstantiating = 18587 TSK == TSK_ImplicitInstantiation || 18588 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18589 18590 if (TryInstantiating) { 18591 SourceLocation PointOfInstantiation = 18592 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18593 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18594 if (FirstInstantiation) { 18595 PointOfInstantiation = Loc; 18596 if (MSI) 18597 MSI->setPointOfInstantiation(PointOfInstantiation); 18598 // FIXME: Notify listener. 18599 else 18600 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18601 } 18602 18603 if (UsableInConstantExpr) { 18604 // Do not defer instantiations of variables that could be used in a 18605 // constant expression. 18606 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18607 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18608 }); 18609 18610 // Re-set the member to trigger a recomputation of the dependence bits 18611 // for the expression. 18612 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18613 DRE->setDecl(DRE->getDecl()); 18614 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18615 ME->setMemberDecl(ME->getMemberDecl()); 18616 } else if (FirstInstantiation || 18617 isa<VarTemplateSpecializationDecl>(Var)) { 18618 // FIXME: For a specialization of a variable template, we don't 18619 // distinguish between "declaration and type implicitly instantiated" 18620 // and "implicit instantiation of definition requested", so we have 18621 // no direct way to avoid enqueueing the pending instantiation 18622 // multiple times. 18623 SemaRef.PendingInstantiations 18624 .push_back(std::make_pair(Var, PointOfInstantiation)); 18625 } 18626 } 18627 } 18628 18629 // C++2a [basic.def.odr]p4: 18630 // A variable x whose name appears as a potentially-evaluated expression e 18631 // is odr-used by e unless 18632 // -- x is a reference that is usable in constant expressions 18633 // -- x is a variable of non-reference type that is usable in constant 18634 // expressions and has no mutable subobjects [FIXME], and e is an 18635 // element of the set of potential results of an expression of 18636 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18637 // conversion is applied 18638 // -- x is a variable of non-reference type, and e is an element of the set 18639 // of potential results of a discarded-value expression to which the 18640 // lvalue-to-rvalue conversion is not applied [FIXME] 18641 // 18642 // We check the first part of the second bullet here, and 18643 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18644 // FIXME: To get the third bullet right, we need to delay this even for 18645 // variables that are not usable in constant expressions. 18646 18647 // If we already know this isn't an odr-use, there's nothing more to do. 18648 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18649 if (DRE->isNonOdrUse()) 18650 return; 18651 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18652 if (ME->isNonOdrUse()) 18653 return; 18654 18655 switch (OdrUse) { 18656 case OdrUseContext::None: 18657 assert((!E || isa<FunctionParmPackExpr>(E)) && 18658 "missing non-odr-use marking for unevaluated decl ref"); 18659 break; 18660 18661 case OdrUseContext::FormallyOdrUsed: 18662 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18663 // behavior. 18664 break; 18665 18666 case OdrUseContext::Used: 18667 // If we might later find that this expression isn't actually an odr-use, 18668 // delay the marking. 18669 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18670 SemaRef.MaybeODRUseExprs.insert(E); 18671 else 18672 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18673 break; 18674 18675 case OdrUseContext::Dependent: 18676 // If this is a dependent context, we don't need to mark variables as 18677 // odr-used, but we may still need to track them for lambda capture. 18678 // FIXME: Do we also need to do this inside dependent typeid expressions 18679 // (which are modeled as unevaluated at this point)? 18680 const bool RefersToEnclosingScope = 18681 (SemaRef.CurContext != Var->getDeclContext() && 18682 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18683 if (RefersToEnclosingScope) { 18684 LambdaScopeInfo *const LSI = 18685 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18686 if (LSI && (!LSI->CallOperator || 18687 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18688 // If a variable could potentially be odr-used, defer marking it so 18689 // until we finish analyzing the full expression for any 18690 // lvalue-to-rvalue 18691 // or discarded value conversions that would obviate odr-use. 18692 // Add it to the list of potential captures that will be analyzed 18693 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18694 // unless the variable is a reference that was initialized by a constant 18695 // expression (this will never need to be captured or odr-used). 18696 // 18697 // FIXME: We can simplify this a lot after implementing P0588R1. 18698 assert(E && "Capture variable should be used in an expression."); 18699 if (!Var->getType()->isReferenceType() || 18700 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18701 LSI->addPotentialCapture(E->IgnoreParens()); 18702 } 18703 } 18704 break; 18705 } 18706 } 18707 18708 /// Mark a variable referenced, and check whether it is odr-used 18709 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18710 /// used directly for normal expressions referring to VarDecl. 18711 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18712 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 18713 } 18714 18715 static void 18716 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 18717 bool MightBeOdrUse, 18718 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18719 if (SemaRef.isInOpenMPDeclareTargetContext()) 18720 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18721 18722 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18723 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 18724 return; 18725 } 18726 18727 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18728 18729 // If this is a call to a method via a cast, also mark the method in the 18730 // derived class used in case codegen can devirtualize the call. 18731 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18732 if (!ME) 18733 return; 18734 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18735 if (!MD) 18736 return; 18737 // Only attempt to devirtualize if this is truly a virtual call. 18738 bool IsVirtualCall = MD->isVirtual() && 18739 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18740 if (!IsVirtualCall) 18741 return; 18742 18743 // If it's possible to devirtualize the call, mark the called function 18744 // referenced. 18745 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18746 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18747 if (DM) 18748 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18749 } 18750 18751 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18752 /// 18753 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18754 /// handled with care if the DeclRefExpr is not newly-created. 18755 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18756 // TODO: update this with DR# once a defect report is filed. 18757 // C++11 defect. The address of a pure member should not be an ODR use, even 18758 // if it's a qualified reference. 18759 bool OdrUse = true; 18760 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18761 if (Method->isVirtual() && 18762 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18763 OdrUse = false; 18764 18765 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18766 if (!isUnevaluatedContext() && !isConstantEvaluated() && 18767 FD->isConsteval() && !RebuildingImmediateInvocation) 18768 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18769 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 18770 RefsMinusAssignments); 18771 } 18772 18773 /// Perform reference-marking and odr-use handling for a MemberExpr. 18774 void Sema::MarkMemberReferenced(MemberExpr *E) { 18775 // C++11 [basic.def.odr]p2: 18776 // A non-overloaded function whose name appears as a potentially-evaluated 18777 // expression or a member of a set of candidate functions, if selected by 18778 // overload resolution when referred to from a potentially-evaluated 18779 // expression, is odr-used, unless it is a pure virtual function and its 18780 // name is not explicitly qualified. 18781 bool MightBeOdrUse = true; 18782 if (E->performsVirtualDispatch(getLangOpts())) { 18783 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18784 if (Method->isPure()) 18785 MightBeOdrUse = false; 18786 } 18787 SourceLocation Loc = 18788 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18789 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 18790 RefsMinusAssignments); 18791 } 18792 18793 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18794 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18795 for (VarDecl *VD : *E) 18796 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 18797 RefsMinusAssignments); 18798 } 18799 18800 /// Perform marking for a reference to an arbitrary declaration. It 18801 /// marks the declaration referenced, and performs odr-use checking for 18802 /// functions and variables. This method should not be used when building a 18803 /// normal expression which refers to a variable. 18804 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18805 bool MightBeOdrUse) { 18806 if (MightBeOdrUse) { 18807 if (auto *VD = dyn_cast<VarDecl>(D)) { 18808 MarkVariableReferenced(Loc, VD); 18809 return; 18810 } 18811 } 18812 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18813 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18814 return; 18815 } 18816 D->setReferenced(); 18817 } 18818 18819 namespace { 18820 // Mark all of the declarations used by a type as referenced. 18821 // FIXME: Not fully implemented yet! We need to have a better understanding 18822 // of when we're entering a context we should not recurse into. 18823 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18824 // TreeTransforms rebuilding the type in a new context. Rather than 18825 // duplicating the TreeTransform logic, we should consider reusing it here. 18826 // Currently that causes problems when rebuilding LambdaExprs. 18827 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18828 Sema &S; 18829 SourceLocation Loc; 18830 18831 public: 18832 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18833 18834 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18835 18836 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18837 }; 18838 } 18839 18840 bool MarkReferencedDecls::TraverseTemplateArgument( 18841 const TemplateArgument &Arg) { 18842 { 18843 // A non-type template argument is a constant-evaluated context. 18844 EnterExpressionEvaluationContext Evaluated( 18845 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18846 if (Arg.getKind() == TemplateArgument::Declaration) { 18847 if (Decl *D = Arg.getAsDecl()) 18848 S.MarkAnyDeclReferenced(Loc, D, true); 18849 } else if (Arg.getKind() == TemplateArgument::Expression) { 18850 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18851 } 18852 } 18853 18854 return Inherited::TraverseTemplateArgument(Arg); 18855 } 18856 18857 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18858 MarkReferencedDecls Marker(*this, Loc); 18859 Marker.TraverseType(T); 18860 } 18861 18862 namespace { 18863 /// Helper class that marks all of the declarations referenced by 18864 /// potentially-evaluated subexpressions as "referenced". 18865 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18866 public: 18867 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18868 bool SkipLocalVariables; 18869 ArrayRef<const Expr *> StopAt; 18870 18871 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables, 18872 ArrayRef<const Expr *> StopAt) 18873 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {} 18874 18875 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18876 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18877 } 18878 18879 void Visit(Expr *E) { 18880 if (std::find(StopAt.begin(), StopAt.end(), E) != StopAt.end()) 18881 return; 18882 Inherited::Visit(E); 18883 } 18884 18885 void VisitDeclRefExpr(DeclRefExpr *E) { 18886 // If we were asked not to visit local variables, don't. 18887 if (SkipLocalVariables) { 18888 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18889 if (VD->hasLocalStorage()) 18890 return; 18891 } 18892 18893 // FIXME: This can trigger the instantiation of the initializer of a 18894 // variable, which can cause the expression to become value-dependent 18895 // or error-dependent. Do we need to propagate the new dependence bits? 18896 S.MarkDeclRefReferenced(E); 18897 } 18898 18899 void VisitMemberExpr(MemberExpr *E) { 18900 S.MarkMemberReferenced(E); 18901 Visit(E->getBase()); 18902 } 18903 }; 18904 } // namespace 18905 18906 /// Mark any declarations that appear within this expression or any 18907 /// potentially-evaluated subexpressions as "referenced". 18908 /// 18909 /// \param SkipLocalVariables If true, don't mark local variables as 18910 /// 'referenced'. 18911 /// \param StopAt Subexpressions that we shouldn't recurse into. 18912 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18913 bool SkipLocalVariables, 18914 ArrayRef<const Expr*> StopAt) { 18915 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E); 18916 } 18917 18918 /// Emit a diagnostic when statements are reachable. 18919 /// FIXME: check for reachability even in expressions for which we don't build a 18920 /// CFG (eg, in the initializer of a global or in a constant expression). 18921 /// For example, 18922 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; } 18923 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, 18924 const PartialDiagnostic &PD) { 18925 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18926 if (!FunctionScopes.empty()) 18927 FunctionScopes.back()->PossiblyUnreachableDiags.push_back( 18928 sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18929 return true; 18930 } 18931 18932 // The initializer of a constexpr variable or of the first declaration of a 18933 // static data member is not syntactically a constant evaluated constant, 18934 // but nonetheless is always required to be a constant expression, so we 18935 // can skip diagnosing. 18936 // FIXME: Using the mangling context here is a hack. 18937 if (auto *VD = dyn_cast_or_null<VarDecl>( 18938 ExprEvalContexts.back().ManglingContextDecl)) { 18939 if (VD->isConstexpr() || 18940 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18941 return false; 18942 // FIXME: For any other kind of variable, we should build a CFG for its 18943 // initializer and check whether the context in question is reachable. 18944 } 18945 18946 Diag(Loc, PD); 18947 return true; 18948 } 18949 18950 /// Emit a diagnostic that describes an effect on the run-time behavior 18951 /// of the program being compiled. 18952 /// 18953 /// This routine emits the given diagnostic when the code currently being 18954 /// type-checked is "potentially evaluated", meaning that there is a 18955 /// possibility that the code will actually be executable. Code in sizeof() 18956 /// expressions, code used only during overload resolution, etc., are not 18957 /// potentially evaluated. This routine will suppress such diagnostics or, 18958 /// in the absolutely nutty case of potentially potentially evaluated 18959 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18960 /// later. 18961 /// 18962 /// This routine should be used for all diagnostics that describe the run-time 18963 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18964 /// Failure to do so will likely result in spurious diagnostics or failures 18965 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18966 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18967 const PartialDiagnostic &PD) { 18968 switch (ExprEvalContexts.back().Context) { 18969 case ExpressionEvaluationContext::Unevaluated: 18970 case ExpressionEvaluationContext::UnevaluatedList: 18971 case ExpressionEvaluationContext::UnevaluatedAbstract: 18972 case ExpressionEvaluationContext::DiscardedStatement: 18973 // The argument will never be evaluated, so don't complain. 18974 break; 18975 18976 case ExpressionEvaluationContext::ConstantEvaluated: 18977 case ExpressionEvaluationContext::ImmediateFunctionContext: 18978 // Relevant diagnostics should be produced by constant evaluation. 18979 break; 18980 18981 case ExpressionEvaluationContext::PotentiallyEvaluated: 18982 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18983 return DiagIfReachable(Loc, Stmts, PD); 18984 } 18985 18986 return false; 18987 } 18988 18989 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18990 const PartialDiagnostic &PD) { 18991 return DiagRuntimeBehavior( 18992 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18993 } 18994 18995 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18996 CallExpr *CE, FunctionDecl *FD) { 18997 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18998 return false; 18999 19000 // If we're inside a decltype's expression, don't check for a valid return 19001 // type or construct temporaries until we know whether this is the last call. 19002 if (ExprEvalContexts.back().ExprContext == 19003 ExpressionEvaluationContextRecord::EK_Decltype) { 19004 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 19005 return false; 19006 } 19007 19008 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 19009 FunctionDecl *FD; 19010 CallExpr *CE; 19011 19012 public: 19013 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 19014 : FD(FD), CE(CE) { } 19015 19016 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 19017 if (!FD) { 19018 S.Diag(Loc, diag::err_call_incomplete_return) 19019 << T << CE->getSourceRange(); 19020 return; 19021 } 19022 19023 S.Diag(Loc, diag::err_call_function_incomplete_return) 19024 << CE->getSourceRange() << FD << T; 19025 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 19026 << FD->getDeclName(); 19027 } 19028 } Diagnoser(FD, CE); 19029 19030 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 19031 return true; 19032 19033 return false; 19034 } 19035 19036 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 19037 // will prevent this condition from triggering, which is what we want. 19038 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 19039 SourceLocation Loc; 19040 19041 unsigned diagnostic = diag::warn_condition_is_assignment; 19042 bool IsOrAssign = false; 19043 19044 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 19045 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 19046 return; 19047 19048 IsOrAssign = Op->getOpcode() == BO_OrAssign; 19049 19050 // Greylist some idioms by putting them into a warning subcategory. 19051 if (ObjCMessageExpr *ME 19052 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 19053 Selector Sel = ME->getSelector(); 19054 19055 // self = [<foo> init...] 19056 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 19057 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19058 19059 // <foo> = [<bar> nextObject] 19060 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 19061 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19062 } 19063 19064 Loc = Op->getOperatorLoc(); 19065 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 19066 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 19067 return; 19068 19069 IsOrAssign = Op->getOperator() == OO_PipeEqual; 19070 Loc = Op->getOperatorLoc(); 19071 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 19072 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 19073 else { 19074 // Not an assignment. 19075 return; 19076 } 19077 19078 Diag(Loc, diagnostic) << E->getSourceRange(); 19079 19080 SourceLocation Open = E->getBeginLoc(); 19081 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 19082 Diag(Loc, diag::note_condition_assign_silence) 19083 << FixItHint::CreateInsertion(Open, "(") 19084 << FixItHint::CreateInsertion(Close, ")"); 19085 19086 if (IsOrAssign) 19087 Diag(Loc, diag::note_condition_or_assign_to_comparison) 19088 << FixItHint::CreateReplacement(Loc, "!="); 19089 else 19090 Diag(Loc, diag::note_condition_assign_to_comparison) 19091 << FixItHint::CreateReplacement(Loc, "=="); 19092 } 19093 19094 /// Redundant parentheses over an equality comparison can indicate 19095 /// that the user intended an assignment used as condition. 19096 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 19097 // Don't warn if the parens came from a macro. 19098 SourceLocation parenLoc = ParenE->getBeginLoc(); 19099 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 19100 return; 19101 // Don't warn for dependent expressions. 19102 if (ParenE->isTypeDependent()) 19103 return; 19104 19105 Expr *E = ParenE->IgnoreParens(); 19106 19107 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 19108 if (opE->getOpcode() == BO_EQ && 19109 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 19110 == Expr::MLV_Valid) { 19111 SourceLocation Loc = opE->getOperatorLoc(); 19112 19113 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 19114 SourceRange ParenERange = ParenE->getSourceRange(); 19115 Diag(Loc, diag::note_equality_comparison_silence) 19116 << FixItHint::CreateRemoval(ParenERange.getBegin()) 19117 << FixItHint::CreateRemoval(ParenERange.getEnd()); 19118 Diag(Loc, diag::note_equality_comparison_to_assign) 19119 << FixItHint::CreateReplacement(Loc, "="); 19120 } 19121 } 19122 19123 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 19124 bool IsConstexpr) { 19125 DiagnoseAssignmentAsCondition(E); 19126 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 19127 DiagnoseEqualityWithExtraParens(parenE); 19128 19129 ExprResult result = CheckPlaceholderExpr(E); 19130 if (result.isInvalid()) return ExprError(); 19131 E = result.get(); 19132 19133 if (!E->isTypeDependent()) { 19134 if (getLangOpts().CPlusPlus) 19135 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 19136 19137 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 19138 if (ERes.isInvalid()) 19139 return ExprError(); 19140 E = ERes.get(); 19141 19142 QualType T = E->getType(); 19143 if (!T->isScalarType()) { // C99 6.8.4.1p1 19144 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 19145 << T << E->getSourceRange(); 19146 return ExprError(); 19147 } 19148 CheckBoolLikeConversion(E, Loc); 19149 } 19150 19151 return E; 19152 } 19153 19154 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 19155 Expr *SubExpr, ConditionKind CK) { 19156 // Empty conditions are valid in for-statements. 19157 if (!SubExpr) 19158 return ConditionResult(); 19159 19160 ExprResult Cond; 19161 switch (CK) { 19162 case ConditionKind::Boolean: 19163 Cond = CheckBooleanCondition(Loc, SubExpr); 19164 break; 19165 19166 case ConditionKind::ConstexprIf: 19167 Cond = CheckBooleanCondition(Loc, SubExpr, true); 19168 break; 19169 19170 case ConditionKind::Switch: 19171 Cond = CheckSwitchCondition(Loc, SubExpr); 19172 break; 19173 } 19174 if (Cond.isInvalid()) { 19175 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 19176 {SubExpr}); 19177 if (!Cond.get()) 19178 return ConditionError(); 19179 } 19180 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 19181 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 19182 if (!FullExpr.get()) 19183 return ConditionError(); 19184 19185 return ConditionResult(*this, nullptr, FullExpr, 19186 CK == ConditionKind::ConstexprIf); 19187 } 19188 19189 namespace { 19190 /// A visitor for rebuilding a call to an __unknown_any expression 19191 /// to have an appropriate type. 19192 struct RebuildUnknownAnyFunction 19193 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 19194 19195 Sema &S; 19196 19197 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 19198 19199 ExprResult VisitStmt(Stmt *S) { 19200 llvm_unreachable("unexpected statement!"); 19201 } 19202 19203 ExprResult VisitExpr(Expr *E) { 19204 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 19205 << E->getSourceRange(); 19206 return ExprError(); 19207 } 19208 19209 /// Rebuild an expression which simply semantically wraps another 19210 /// expression which it shares the type and value kind of. 19211 template <class T> ExprResult rebuildSugarExpr(T *E) { 19212 ExprResult SubResult = Visit(E->getSubExpr()); 19213 if (SubResult.isInvalid()) return ExprError(); 19214 19215 Expr *SubExpr = SubResult.get(); 19216 E->setSubExpr(SubExpr); 19217 E->setType(SubExpr->getType()); 19218 E->setValueKind(SubExpr->getValueKind()); 19219 assert(E->getObjectKind() == OK_Ordinary); 19220 return E; 19221 } 19222 19223 ExprResult VisitParenExpr(ParenExpr *E) { 19224 return rebuildSugarExpr(E); 19225 } 19226 19227 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19228 return rebuildSugarExpr(E); 19229 } 19230 19231 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19232 ExprResult SubResult = Visit(E->getSubExpr()); 19233 if (SubResult.isInvalid()) return ExprError(); 19234 19235 Expr *SubExpr = SubResult.get(); 19236 E->setSubExpr(SubExpr); 19237 E->setType(S.Context.getPointerType(SubExpr->getType())); 19238 assert(E->isPRValue()); 19239 assert(E->getObjectKind() == OK_Ordinary); 19240 return E; 19241 } 19242 19243 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19244 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19245 19246 E->setType(VD->getType()); 19247 19248 assert(E->isPRValue()); 19249 if (S.getLangOpts().CPlusPlus && 19250 !(isa<CXXMethodDecl>(VD) && 19251 cast<CXXMethodDecl>(VD)->isInstance())) 19252 E->setValueKind(VK_LValue); 19253 19254 return E; 19255 } 19256 19257 ExprResult VisitMemberExpr(MemberExpr *E) { 19258 return resolveDecl(E, E->getMemberDecl()); 19259 } 19260 19261 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19262 return resolveDecl(E, E->getDecl()); 19263 } 19264 }; 19265 } 19266 19267 /// Given a function expression of unknown-any type, try to rebuild it 19268 /// to have a function type. 19269 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19270 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19271 if (Result.isInvalid()) return ExprError(); 19272 return S.DefaultFunctionArrayConversion(Result.get()); 19273 } 19274 19275 namespace { 19276 /// A visitor for rebuilding an expression of type __unknown_anytype 19277 /// into one which resolves the type directly on the referring 19278 /// expression. Strict preservation of the original source 19279 /// structure is not a goal. 19280 struct RebuildUnknownAnyExpr 19281 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19282 19283 Sema &S; 19284 19285 /// The current destination type. 19286 QualType DestType; 19287 19288 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19289 : S(S), DestType(CastType) {} 19290 19291 ExprResult VisitStmt(Stmt *S) { 19292 llvm_unreachable("unexpected statement!"); 19293 } 19294 19295 ExprResult VisitExpr(Expr *E) { 19296 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19297 << E->getSourceRange(); 19298 return ExprError(); 19299 } 19300 19301 ExprResult VisitCallExpr(CallExpr *E); 19302 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 19303 19304 /// Rebuild an expression which simply semantically wraps another 19305 /// expression which it shares the type and value kind of. 19306 template <class T> ExprResult rebuildSugarExpr(T *E) { 19307 ExprResult SubResult = Visit(E->getSubExpr()); 19308 if (SubResult.isInvalid()) return ExprError(); 19309 Expr *SubExpr = SubResult.get(); 19310 E->setSubExpr(SubExpr); 19311 E->setType(SubExpr->getType()); 19312 E->setValueKind(SubExpr->getValueKind()); 19313 assert(E->getObjectKind() == OK_Ordinary); 19314 return E; 19315 } 19316 19317 ExprResult VisitParenExpr(ParenExpr *E) { 19318 return rebuildSugarExpr(E); 19319 } 19320 19321 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19322 return rebuildSugarExpr(E); 19323 } 19324 19325 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19326 const PointerType *Ptr = DestType->getAs<PointerType>(); 19327 if (!Ptr) { 19328 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19329 << E->getSourceRange(); 19330 return ExprError(); 19331 } 19332 19333 if (isa<CallExpr>(E->getSubExpr())) { 19334 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19335 << E->getSourceRange(); 19336 return ExprError(); 19337 } 19338 19339 assert(E->isPRValue()); 19340 assert(E->getObjectKind() == OK_Ordinary); 19341 E->setType(DestType); 19342 19343 // Build the sub-expression as if it were an object of the pointee type. 19344 DestType = Ptr->getPointeeType(); 19345 ExprResult SubResult = Visit(E->getSubExpr()); 19346 if (SubResult.isInvalid()) return ExprError(); 19347 E->setSubExpr(SubResult.get()); 19348 return E; 19349 } 19350 19351 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19352 19353 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19354 19355 ExprResult VisitMemberExpr(MemberExpr *E) { 19356 return resolveDecl(E, E->getMemberDecl()); 19357 } 19358 19359 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19360 return resolveDecl(E, E->getDecl()); 19361 } 19362 }; 19363 } 19364 19365 /// Rebuilds a call expression which yielded __unknown_anytype. 19366 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19367 Expr *CalleeExpr = E->getCallee(); 19368 19369 enum FnKind { 19370 FK_MemberFunction, 19371 FK_FunctionPointer, 19372 FK_BlockPointer 19373 }; 19374 19375 FnKind Kind; 19376 QualType CalleeType = CalleeExpr->getType(); 19377 if (CalleeType == S.Context.BoundMemberTy) { 19378 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19379 Kind = FK_MemberFunction; 19380 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19381 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19382 CalleeType = Ptr->getPointeeType(); 19383 Kind = FK_FunctionPointer; 19384 } else { 19385 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19386 Kind = FK_BlockPointer; 19387 } 19388 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19389 19390 // Verify that this is a legal result type of a function. 19391 if (DestType->isArrayType() || DestType->isFunctionType()) { 19392 unsigned diagID = diag::err_func_returning_array_function; 19393 if (Kind == FK_BlockPointer) 19394 diagID = diag::err_block_returning_array_function; 19395 19396 S.Diag(E->getExprLoc(), diagID) 19397 << DestType->isFunctionType() << DestType; 19398 return ExprError(); 19399 } 19400 19401 // Otherwise, go ahead and set DestType as the call's result. 19402 E->setType(DestType.getNonLValueExprType(S.Context)); 19403 E->setValueKind(Expr::getValueKindForType(DestType)); 19404 assert(E->getObjectKind() == OK_Ordinary); 19405 19406 // Rebuild the function type, replacing the result type with DestType. 19407 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19408 if (Proto) { 19409 // __unknown_anytype(...) is a special case used by the debugger when 19410 // it has no idea what a function's signature is. 19411 // 19412 // We want to build this call essentially under the K&R 19413 // unprototyped rules, but making a FunctionNoProtoType in C++ 19414 // would foul up all sorts of assumptions. However, we cannot 19415 // simply pass all arguments as variadic arguments, nor can we 19416 // portably just call the function under a non-variadic type; see 19417 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19418 // However, it turns out that in practice it is generally safe to 19419 // call a function declared as "A foo(B,C,D);" under the prototype 19420 // "A foo(B,C,D,...);". The only known exception is with the 19421 // Windows ABI, where any variadic function is implicitly cdecl 19422 // regardless of its normal CC. Therefore we change the parameter 19423 // types to match the types of the arguments. 19424 // 19425 // This is a hack, but it is far superior to moving the 19426 // corresponding target-specific code from IR-gen to Sema/AST. 19427 19428 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19429 SmallVector<QualType, 8> ArgTypes; 19430 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19431 ArgTypes.reserve(E->getNumArgs()); 19432 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19433 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); 19434 } 19435 ParamTypes = ArgTypes; 19436 } 19437 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19438 Proto->getExtProtoInfo()); 19439 } else { 19440 DestType = S.Context.getFunctionNoProtoType(DestType, 19441 FnType->getExtInfo()); 19442 } 19443 19444 // Rebuild the appropriate pointer-to-function type. 19445 switch (Kind) { 19446 case FK_MemberFunction: 19447 // Nothing to do. 19448 break; 19449 19450 case FK_FunctionPointer: 19451 DestType = S.Context.getPointerType(DestType); 19452 break; 19453 19454 case FK_BlockPointer: 19455 DestType = S.Context.getBlockPointerType(DestType); 19456 break; 19457 } 19458 19459 // Finally, we can recurse. 19460 ExprResult CalleeResult = Visit(CalleeExpr); 19461 if (!CalleeResult.isUsable()) return ExprError(); 19462 E->setCallee(CalleeResult.get()); 19463 19464 // Bind a temporary if necessary. 19465 return S.MaybeBindToTemporary(E); 19466 } 19467 19468 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19469 // Verify that this is a legal result type of a call. 19470 if (DestType->isArrayType() || DestType->isFunctionType()) { 19471 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19472 << DestType->isFunctionType() << DestType; 19473 return ExprError(); 19474 } 19475 19476 // Rewrite the method result type if available. 19477 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19478 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19479 Method->setReturnType(DestType); 19480 } 19481 19482 // Change the type of the message. 19483 E->setType(DestType.getNonReferenceType()); 19484 E->setValueKind(Expr::getValueKindForType(DestType)); 19485 19486 return S.MaybeBindToTemporary(E); 19487 } 19488 19489 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19490 // The only case we should ever see here is a function-to-pointer decay. 19491 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19492 assert(E->isPRValue()); 19493 assert(E->getObjectKind() == OK_Ordinary); 19494 19495 E->setType(DestType); 19496 19497 // Rebuild the sub-expression as the pointee (function) type. 19498 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19499 19500 ExprResult Result = Visit(E->getSubExpr()); 19501 if (!Result.isUsable()) return ExprError(); 19502 19503 E->setSubExpr(Result.get()); 19504 return E; 19505 } else if (E->getCastKind() == CK_LValueToRValue) { 19506 assert(E->isPRValue()); 19507 assert(E->getObjectKind() == OK_Ordinary); 19508 19509 assert(isa<BlockPointerType>(E->getType())); 19510 19511 E->setType(DestType); 19512 19513 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19514 DestType = S.Context.getLValueReferenceType(DestType); 19515 19516 ExprResult Result = Visit(E->getSubExpr()); 19517 if (!Result.isUsable()) return ExprError(); 19518 19519 E->setSubExpr(Result.get()); 19520 return E; 19521 } else { 19522 llvm_unreachable("Unhandled cast type!"); 19523 } 19524 } 19525 19526 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19527 ExprValueKind ValueKind = VK_LValue; 19528 QualType Type = DestType; 19529 19530 // We know how to make this work for certain kinds of decls: 19531 19532 // - functions 19533 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19534 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19535 DestType = Ptr->getPointeeType(); 19536 ExprResult Result = resolveDecl(E, VD); 19537 if (Result.isInvalid()) return ExprError(); 19538 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 19539 VK_PRValue); 19540 } 19541 19542 if (!Type->isFunctionType()) { 19543 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19544 << VD << E->getSourceRange(); 19545 return ExprError(); 19546 } 19547 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19548 // We must match the FunctionDecl's type to the hack introduced in 19549 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19550 // type. See the lengthy commentary in that routine. 19551 QualType FDT = FD->getType(); 19552 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19553 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19554 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19555 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19556 SourceLocation Loc = FD->getLocation(); 19557 FunctionDecl *NewFD = FunctionDecl::Create( 19558 S.Context, FD->getDeclContext(), Loc, Loc, 19559 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19560 SC_None, S.getCurFPFeatures().isFPConstrained(), 19561 false /*isInlineSpecified*/, FD->hasPrototype(), 19562 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19563 19564 if (FD->getQualifier()) 19565 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19566 19567 SmallVector<ParmVarDecl*, 16> Params; 19568 for (const auto &AI : FT->param_types()) { 19569 ParmVarDecl *Param = 19570 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19571 Param->setScopeInfo(0, Params.size()); 19572 Params.push_back(Param); 19573 } 19574 NewFD->setParams(Params); 19575 DRE->setDecl(NewFD); 19576 VD = DRE->getDecl(); 19577 } 19578 } 19579 19580 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19581 if (MD->isInstance()) { 19582 ValueKind = VK_PRValue; 19583 Type = S.Context.BoundMemberTy; 19584 } 19585 19586 // Function references aren't l-values in C. 19587 if (!S.getLangOpts().CPlusPlus) 19588 ValueKind = VK_PRValue; 19589 19590 // - variables 19591 } else if (isa<VarDecl>(VD)) { 19592 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19593 Type = RefTy->getPointeeType(); 19594 } else if (Type->isFunctionType()) { 19595 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19596 << VD << E->getSourceRange(); 19597 return ExprError(); 19598 } 19599 19600 // - nothing else 19601 } else { 19602 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19603 << VD << E->getSourceRange(); 19604 return ExprError(); 19605 } 19606 19607 // Modifying the declaration like this is friendly to IR-gen but 19608 // also really dangerous. 19609 VD->setType(DestType); 19610 E->setType(Type); 19611 E->setValueKind(ValueKind); 19612 return E; 19613 } 19614 19615 /// Check a cast of an unknown-any type. We intentionally only 19616 /// trigger this for C-style casts. 19617 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19618 Expr *CastExpr, CastKind &CastKind, 19619 ExprValueKind &VK, CXXCastPath &Path) { 19620 // The type we're casting to must be either void or complete. 19621 if (!CastType->isVoidType() && 19622 RequireCompleteType(TypeRange.getBegin(), CastType, 19623 diag::err_typecheck_cast_to_incomplete)) 19624 return ExprError(); 19625 19626 // Rewrite the casted expression from scratch. 19627 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19628 if (!result.isUsable()) return ExprError(); 19629 19630 CastExpr = result.get(); 19631 VK = CastExpr->getValueKind(); 19632 CastKind = CK_NoOp; 19633 19634 return CastExpr; 19635 } 19636 19637 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19638 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19639 } 19640 19641 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19642 Expr *arg, QualType ¶mType) { 19643 // If the syntactic form of the argument is not an explicit cast of 19644 // any sort, just do default argument promotion. 19645 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19646 if (!castArg) { 19647 ExprResult result = DefaultArgumentPromotion(arg); 19648 if (result.isInvalid()) return ExprError(); 19649 paramType = result.get()->getType(); 19650 return result; 19651 } 19652 19653 // Otherwise, use the type that was written in the explicit cast. 19654 assert(!arg->hasPlaceholderType()); 19655 paramType = castArg->getTypeAsWritten(); 19656 19657 // Copy-initialize a parameter of that type. 19658 InitializedEntity entity = 19659 InitializedEntity::InitializeParameter(Context, paramType, 19660 /*consumed*/ false); 19661 return PerformCopyInitialization(entity, callLoc, arg); 19662 } 19663 19664 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19665 Expr *orig = E; 19666 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19667 while (true) { 19668 E = E->IgnoreParenImpCasts(); 19669 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19670 E = call->getCallee(); 19671 diagID = diag::err_uncasted_call_of_unknown_any; 19672 } else { 19673 break; 19674 } 19675 } 19676 19677 SourceLocation loc; 19678 NamedDecl *d; 19679 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19680 loc = ref->getLocation(); 19681 d = ref->getDecl(); 19682 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19683 loc = mem->getMemberLoc(); 19684 d = mem->getMemberDecl(); 19685 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19686 diagID = diag::err_uncasted_call_of_unknown_any; 19687 loc = msg->getSelectorStartLoc(); 19688 d = msg->getMethodDecl(); 19689 if (!d) { 19690 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19691 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19692 << orig->getSourceRange(); 19693 return ExprError(); 19694 } 19695 } else { 19696 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19697 << E->getSourceRange(); 19698 return ExprError(); 19699 } 19700 19701 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19702 19703 // Never recoverable. 19704 return ExprError(); 19705 } 19706 19707 /// Check for operands with placeholder types and complain if found. 19708 /// Returns ExprError() if there was an error and no recovery was possible. 19709 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19710 if (!Context.isDependenceAllowed()) { 19711 // C cannot handle TypoExpr nodes on either side of a binop because it 19712 // doesn't handle dependent types properly, so make sure any TypoExprs have 19713 // been dealt with before checking the operands. 19714 ExprResult Result = CorrectDelayedTyposInExpr(E); 19715 if (!Result.isUsable()) return ExprError(); 19716 E = Result.get(); 19717 } 19718 19719 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19720 if (!placeholderType) return E; 19721 19722 switch (placeholderType->getKind()) { 19723 19724 // Overloaded expressions. 19725 case BuiltinType::Overload: { 19726 // Try to resolve a single function template specialization. 19727 // This is obligatory. 19728 ExprResult Result = E; 19729 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19730 return Result; 19731 19732 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19733 // leaves Result unchanged on failure. 19734 Result = E; 19735 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19736 return Result; 19737 19738 // If that failed, try to recover with a call. 19739 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19740 /*complain*/ true); 19741 return Result; 19742 } 19743 19744 // Bound member functions. 19745 case BuiltinType::BoundMember: { 19746 ExprResult result = E; 19747 const Expr *BME = E->IgnoreParens(); 19748 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19749 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19750 if (isa<CXXPseudoDestructorExpr>(BME)) { 19751 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19752 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19753 if (ME->getMemberNameInfo().getName().getNameKind() == 19754 DeclarationName::CXXDestructorName) 19755 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19756 } 19757 tryToRecoverWithCall(result, PD, 19758 /*complain*/ true); 19759 return result; 19760 } 19761 19762 // ARC unbridged casts. 19763 case BuiltinType::ARCUnbridgedCast: { 19764 Expr *realCast = stripARCUnbridgedCast(E); 19765 diagnoseARCUnbridgedCast(realCast); 19766 return realCast; 19767 } 19768 19769 // Expressions of unknown type. 19770 case BuiltinType::UnknownAny: 19771 return diagnoseUnknownAnyExpr(*this, E); 19772 19773 // Pseudo-objects. 19774 case BuiltinType::PseudoObject: 19775 return checkPseudoObjectRValue(E); 19776 19777 case BuiltinType::BuiltinFn: { 19778 // Accept __noop without parens by implicitly converting it to a call expr. 19779 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19780 if (DRE) { 19781 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19782 if (FD->getBuiltinID() == Builtin::BI__noop) { 19783 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19784 CK_BuiltinFnToFnPtr) 19785 .get(); 19786 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19787 VK_PRValue, SourceLocation(), 19788 FPOptionsOverride()); 19789 } 19790 } 19791 19792 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19793 return ExprError(); 19794 } 19795 19796 case BuiltinType::IncompleteMatrixIdx: 19797 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19798 ->getRowIdx() 19799 ->getBeginLoc(), 19800 diag::err_matrix_incomplete_index); 19801 return ExprError(); 19802 19803 // Expressions of unknown type. 19804 case BuiltinType::OMPArraySection: 19805 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19806 return ExprError(); 19807 19808 // Expressions of unknown type. 19809 case BuiltinType::OMPArrayShaping: 19810 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19811 19812 case BuiltinType::OMPIterator: 19813 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19814 19815 // Everything else should be impossible. 19816 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19817 case BuiltinType::Id: 19818 #include "clang/Basic/OpenCLImageTypes.def" 19819 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19820 case BuiltinType::Id: 19821 #include "clang/Basic/OpenCLExtensionTypes.def" 19822 #define SVE_TYPE(Name, Id, SingletonId) \ 19823 case BuiltinType::Id: 19824 #include "clang/Basic/AArch64SVEACLETypes.def" 19825 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19826 case BuiltinType::Id: 19827 #include "clang/Basic/PPCTypes.def" 19828 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19829 #include "clang/Basic/RISCVVTypes.def" 19830 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19831 #define PLACEHOLDER_TYPE(Id, SingletonId) 19832 #include "clang/AST/BuiltinTypes.def" 19833 break; 19834 } 19835 19836 llvm_unreachable("invalid placeholder type!"); 19837 } 19838 19839 bool Sema::CheckCaseExpression(Expr *E) { 19840 if (E->isTypeDependent()) 19841 return true; 19842 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19843 return E->getType()->isIntegralOrEnumerationType(); 19844 return false; 19845 } 19846 19847 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19848 ExprResult 19849 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19850 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19851 "Unknown Objective-C Boolean value!"); 19852 QualType BoolT = Context.ObjCBuiltinBoolTy; 19853 if (!Context.getBOOLDecl()) { 19854 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19855 Sema::LookupOrdinaryName); 19856 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19857 NamedDecl *ND = Result.getFoundDecl(); 19858 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19859 Context.setBOOLDecl(TD); 19860 } 19861 } 19862 if (Context.getBOOLDecl()) 19863 BoolT = Context.getBOOLType(); 19864 return new (Context) 19865 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19866 } 19867 19868 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19869 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19870 SourceLocation RParen) { 19871 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { 19872 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19873 return Spec.getPlatform() == Platform; 19874 }); 19875 // Transcribe the "ios" availability check to "maccatalyst" when compiling 19876 // for "maccatalyst" if "maccatalyst" is not specified. 19877 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { 19878 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19879 return Spec.getPlatform() == "ios"; 19880 }); 19881 } 19882 if (Spec == AvailSpecs.end()) 19883 return None; 19884 return Spec->getVersion(); 19885 }; 19886 19887 VersionTuple Version; 19888 if (auto MaybeVersion = 19889 FindSpecVersion(Context.getTargetInfo().getPlatformName())) 19890 Version = *MaybeVersion; 19891 19892 // The use of `@available` in the enclosing context should be analyzed to 19893 // warn when it's used inappropriately (i.e. not if(@available)). 19894 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 19895 Context->HasPotentialAvailabilityViolations = true; 19896 19897 return new (Context) 19898 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19899 } 19900 19901 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19902 ArrayRef<Expr *> SubExprs, QualType T) { 19903 if (!Context.getLangOpts().RecoveryAST) 19904 return ExprError(); 19905 19906 if (isSFINAEContext()) 19907 return ExprError(); 19908 19909 if (T.isNull() || T->isUndeducedType() || 19910 !Context.getLangOpts().RecoveryASTType) 19911 // We don't know the concrete type, fallback to dependent type. 19912 T = Context.DependentTy; 19913 19914 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19915 } 19916