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 // Sanity-check shift operands 11189 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11190 11191 // "The type of the result is that of the promoted left operand." 11192 return LHSType; 11193 } 11194 11195 /// Diagnose bad pointer comparisons. 11196 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11197 ExprResult &LHS, ExprResult &RHS, 11198 bool IsError) { 11199 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11200 : diag::ext_typecheck_comparison_of_distinct_pointers) 11201 << LHS.get()->getType() << RHS.get()->getType() 11202 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11203 } 11204 11205 /// Returns false if the pointers are converted to a composite type, 11206 /// true otherwise. 11207 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11208 ExprResult &LHS, ExprResult &RHS) { 11209 // C++ [expr.rel]p2: 11210 // [...] Pointer conversions (4.10) and qualification 11211 // conversions (4.4) are performed on pointer operands (or on 11212 // a pointer operand and a null pointer constant) to bring 11213 // them to their composite pointer type. [...] 11214 // 11215 // C++ [expr.eq]p1 uses the same notion for (in)equality 11216 // comparisons of pointers. 11217 11218 QualType LHSType = LHS.get()->getType(); 11219 QualType RHSType = RHS.get()->getType(); 11220 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11221 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11222 11223 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11224 if (T.isNull()) { 11225 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11226 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11227 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11228 else 11229 S.InvalidOperands(Loc, LHS, RHS); 11230 return true; 11231 } 11232 11233 return false; 11234 } 11235 11236 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11237 ExprResult &LHS, 11238 ExprResult &RHS, 11239 bool IsError) { 11240 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11241 : diag::ext_typecheck_comparison_of_fptr_to_void) 11242 << LHS.get()->getType() << RHS.get()->getType() 11243 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11244 } 11245 11246 static bool isObjCObjectLiteral(ExprResult &E) { 11247 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11248 case Stmt::ObjCArrayLiteralClass: 11249 case Stmt::ObjCDictionaryLiteralClass: 11250 case Stmt::ObjCStringLiteralClass: 11251 case Stmt::ObjCBoxedExprClass: 11252 return true; 11253 default: 11254 // Note that ObjCBoolLiteral is NOT an object literal! 11255 return false; 11256 } 11257 } 11258 11259 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11260 const ObjCObjectPointerType *Type = 11261 LHS->getType()->getAs<ObjCObjectPointerType>(); 11262 11263 // If this is not actually an Objective-C object, bail out. 11264 if (!Type) 11265 return false; 11266 11267 // Get the LHS object's interface type. 11268 QualType InterfaceType = Type->getPointeeType(); 11269 11270 // If the RHS isn't an Objective-C object, bail out. 11271 if (!RHS->getType()->isObjCObjectPointerType()) 11272 return false; 11273 11274 // Try to find the -isEqual: method. 11275 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11276 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11277 InterfaceType, 11278 /*IsInstance=*/true); 11279 if (!Method) { 11280 if (Type->isObjCIdType()) { 11281 // For 'id', just check the global pool. 11282 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11283 /*receiverId=*/true); 11284 } else { 11285 // Check protocols. 11286 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11287 /*IsInstance=*/true); 11288 } 11289 } 11290 11291 if (!Method) 11292 return false; 11293 11294 QualType T = Method->parameters()[0]->getType(); 11295 if (!T->isObjCObjectPointerType()) 11296 return false; 11297 11298 QualType R = Method->getReturnType(); 11299 if (!R->isScalarType()) 11300 return false; 11301 11302 return true; 11303 } 11304 11305 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11306 FromE = FromE->IgnoreParenImpCasts(); 11307 switch (FromE->getStmtClass()) { 11308 default: 11309 break; 11310 case Stmt::ObjCStringLiteralClass: 11311 // "string literal" 11312 return LK_String; 11313 case Stmt::ObjCArrayLiteralClass: 11314 // "array literal" 11315 return LK_Array; 11316 case Stmt::ObjCDictionaryLiteralClass: 11317 // "dictionary literal" 11318 return LK_Dictionary; 11319 case Stmt::BlockExprClass: 11320 return LK_Block; 11321 case Stmt::ObjCBoxedExprClass: { 11322 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11323 switch (Inner->getStmtClass()) { 11324 case Stmt::IntegerLiteralClass: 11325 case Stmt::FloatingLiteralClass: 11326 case Stmt::CharacterLiteralClass: 11327 case Stmt::ObjCBoolLiteralExprClass: 11328 case Stmt::CXXBoolLiteralExprClass: 11329 // "numeric literal" 11330 return LK_Numeric; 11331 case Stmt::ImplicitCastExprClass: { 11332 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11333 // Boolean literals can be represented by implicit casts. 11334 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11335 return LK_Numeric; 11336 break; 11337 } 11338 default: 11339 break; 11340 } 11341 return LK_Boxed; 11342 } 11343 } 11344 return LK_None; 11345 } 11346 11347 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11348 ExprResult &LHS, ExprResult &RHS, 11349 BinaryOperator::Opcode Opc){ 11350 Expr *Literal; 11351 Expr *Other; 11352 if (isObjCObjectLiteral(LHS)) { 11353 Literal = LHS.get(); 11354 Other = RHS.get(); 11355 } else { 11356 Literal = RHS.get(); 11357 Other = LHS.get(); 11358 } 11359 11360 // Don't warn on comparisons against nil. 11361 Other = Other->IgnoreParenCasts(); 11362 if (Other->isNullPointerConstant(S.getASTContext(), 11363 Expr::NPC_ValueDependentIsNotNull)) 11364 return; 11365 11366 // This should be kept in sync with warn_objc_literal_comparison. 11367 // LK_String should always be after the other literals, since it has its own 11368 // warning flag. 11369 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11370 assert(LiteralKind != Sema::LK_Block); 11371 if (LiteralKind == Sema::LK_None) { 11372 llvm_unreachable("Unknown Objective-C object literal kind"); 11373 } 11374 11375 if (LiteralKind == Sema::LK_String) 11376 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11377 << Literal->getSourceRange(); 11378 else 11379 S.Diag(Loc, diag::warn_objc_literal_comparison) 11380 << LiteralKind << Literal->getSourceRange(); 11381 11382 if (BinaryOperator::isEqualityOp(Opc) && 11383 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11384 SourceLocation Start = LHS.get()->getBeginLoc(); 11385 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11386 CharSourceRange OpRange = 11387 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11388 11389 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11390 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11391 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11392 << FixItHint::CreateInsertion(End, "]"); 11393 } 11394 } 11395 11396 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11397 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11398 ExprResult &RHS, SourceLocation Loc, 11399 BinaryOperatorKind Opc) { 11400 // Check that left hand side is !something. 11401 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11402 if (!UO || UO->getOpcode() != UO_LNot) return; 11403 11404 // Only check if the right hand side is non-bool arithmetic type. 11405 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11406 11407 // Make sure that the something in !something is not bool. 11408 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11409 if (SubExpr->isKnownToHaveBooleanValue()) return; 11410 11411 // Emit warning. 11412 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11413 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11414 << Loc << IsBitwiseOp; 11415 11416 // First note suggest !(x < y) 11417 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11418 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11419 FirstClose = S.getLocForEndOfToken(FirstClose); 11420 if (FirstClose.isInvalid()) 11421 FirstOpen = SourceLocation(); 11422 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11423 << IsBitwiseOp 11424 << FixItHint::CreateInsertion(FirstOpen, "(") 11425 << FixItHint::CreateInsertion(FirstClose, ")"); 11426 11427 // Second note suggests (!x) < y 11428 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11429 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11430 SecondClose = S.getLocForEndOfToken(SecondClose); 11431 if (SecondClose.isInvalid()) 11432 SecondOpen = SourceLocation(); 11433 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11434 << FixItHint::CreateInsertion(SecondOpen, "(") 11435 << FixItHint::CreateInsertion(SecondClose, ")"); 11436 } 11437 11438 // Returns true if E refers to a non-weak array. 11439 static bool checkForArray(const Expr *E) { 11440 const ValueDecl *D = nullptr; 11441 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11442 D = DR->getDecl(); 11443 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11444 if (Mem->isImplicitAccess()) 11445 D = Mem->getMemberDecl(); 11446 } 11447 if (!D) 11448 return false; 11449 return D->getType()->isArrayType() && !D->isWeak(); 11450 } 11451 11452 /// Diagnose some forms of syntactically-obvious tautological comparison. 11453 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11454 Expr *LHS, Expr *RHS, 11455 BinaryOperatorKind Opc) { 11456 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11457 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11458 11459 QualType LHSType = LHS->getType(); 11460 QualType RHSType = RHS->getType(); 11461 if (LHSType->hasFloatingRepresentation() || 11462 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11463 S.inTemplateInstantiation()) 11464 return; 11465 11466 // Comparisons between two array types are ill-formed for operator<=>, so 11467 // we shouldn't emit any additional warnings about it. 11468 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11469 return; 11470 11471 // For non-floating point types, check for self-comparisons of the form 11472 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11473 // often indicate logic errors in the program. 11474 // 11475 // NOTE: Don't warn about comparison expressions resulting from macro 11476 // expansion. Also don't warn about comparisons which are only self 11477 // comparisons within a template instantiation. The warnings should catch 11478 // obvious cases in the definition of the template anyways. The idea is to 11479 // warn when the typed comparison operator will always evaluate to the same 11480 // result. 11481 11482 // Used for indexing into %select in warn_comparison_always 11483 enum { 11484 AlwaysConstant, 11485 AlwaysTrue, 11486 AlwaysFalse, 11487 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11488 }; 11489 11490 // C++2a [depr.array.comp]: 11491 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11492 // operands of array type are deprecated. 11493 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11494 RHSStripped->getType()->isArrayType()) { 11495 S.Diag(Loc, diag::warn_depr_array_comparison) 11496 << LHS->getSourceRange() << RHS->getSourceRange() 11497 << LHSStripped->getType() << RHSStripped->getType(); 11498 // Carry on to produce the tautological comparison warning, if this 11499 // expression is potentially-evaluated, we can resolve the array to a 11500 // non-weak declaration, and so on. 11501 } 11502 11503 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11504 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11505 unsigned Result; 11506 switch (Opc) { 11507 case BO_EQ: 11508 case BO_LE: 11509 case BO_GE: 11510 Result = AlwaysTrue; 11511 break; 11512 case BO_NE: 11513 case BO_LT: 11514 case BO_GT: 11515 Result = AlwaysFalse; 11516 break; 11517 case BO_Cmp: 11518 Result = AlwaysEqual; 11519 break; 11520 default: 11521 Result = AlwaysConstant; 11522 break; 11523 } 11524 S.DiagRuntimeBehavior(Loc, nullptr, 11525 S.PDiag(diag::warn_comparison_always) 11526 << 0 /*self-comparison*/ 11527 << Result); 11528 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11529 // What is it always going to evaluate to? 11530 unsigned Result; 11531 switch (Opc) { 11532 case BO_EQ: // e.g. array1 == array2 11533 Result = AlwaysFalse; 11534 break; 11535 case BO_NE: // e.g. array1 != array2 11536 Result = AlwaysTrue; 11537 break; 11538 default: // e.g. array1 <= array2 11539 // The best we can say is 'a constant' 11540 Result = AlwaysConstant; 11541 break; 11542 } 11543 S.DiagRuntimeBehavior(Loc, nullptr, 11544 S.PDiag(diag::warn_comparison_always) 11545 << 1 /*array comparison*/ 11546 << Result); 11547 } 11548 } 11549 11550 if (isa<CastExpr>(LHSStripped)) 11551 LHSStripped = LHSStripped->IgnoreParenCasts(); 11552 if (isa<CastExpr>(RHSStripped)) 11553 RHSStripped = RHSStripped->IgnoreParenCasts(); 11554 11555 // Warn about comparisons against a string constant (unless the other 11556 // operand is null); the user probably wants string comparison function. 11557 Expr *LiteralString = nullptr; 11558 Expr *LiteralStringStripped = nullptr; 11559 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11560 !RHSStripped->isNullPointerConstant(S.Context, 11561 Expr::NPC_ValueDependentIsNull)) { 11562 LiteralString = LHS; 11563 LiteralStringStripped = LHSStripped; 11564 } else if ((isa<StringLiteral>(RHSStripped) || 11565 isa<ObjCEncodeExpr>(RHSStripped)) && 11566 !LHSStripped->isNullPointerConstant(S.Context, 11567 Expr::NPC_ValueDependentIsNull)) { 11568 LiteralString = RHS; 11569 LiteralStringStripped = RHSStripped; 11570 } 11571 11572 if (LiteralString) { 11573 S.DiagRuntimeBehavior(Loc, nullptr, 11574 S.PDiag(diag::warn_stringcompare) 11575 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11576 << LiteralString->getSourceRange()); 11577 } 11578 } 11579 11580 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11581 switch (CK) { 11582 default: { 11583 #ifndef NDEBUG 11584 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11585 << "\n"; 11586 #endif 11587 llvm_unreachable("unhandled cast kind"); 11588 } 11589 case CK_UserDefinedConversion: 11590 return ICK_Identity; 11591 case CK_LValueToRValue: 11592 return ICK_Lvalue_To_Rvalue; 11593 case CK_ArrayToPointerDecay: 11594 return ICK_Array_To_Pointer; 11595 case CK_FunctionToPointerDecay: 11596 return ICK_Function_To_Pointer; 11597 case CK_IntegralCast: 11598 return ICK_Integral_Conversion; 11599 case CK_FloatingCast: 11600 return ICK_Floating_Conversion; 11601 case CK_IntegralToFloating: 11602 case CK_FloatingToIntegral: 11603 return ICK_Floating_Integral; 11604 case CK_IntegralComplexCast: 11605 case CK_FloatingComplexCast: 11606 case CK_FloatingComplexToIntegralComplex: 11607 case CK_IntegralComplexToFloatingComplex: 11608 return ICK_Complex_Conversion; 11609 case CK_FloatingComplexToReal: 11610 case CK_FloatingRealToComplex: 11611 case CK_IntegralComplexToReal: 11612 case CK_IntegralRealToComplex: 11613 return ICK_Complex_Real; 11614 } 11615 } 11616 11617 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11618 QualType FromType, 11619 SourceLocation Loc) { 11620 // Check for a narrowing implicit conversion. 11621 StandardConversionSequence SCS; 11622 SCS.setAsIdentityConversion(); 11623 SCS.setToType(0, FromType); 11624 SCS.setToType(1, ToType); 11625 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11626 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11627 11628 APValue PreNarrowingValue; 11629 QualType PreNarrowingType; 11630 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11631 PreNarrowingType, 11632 /*IgnoreFloatToIntegralConversion*/ true)) { 11633 case NK_Dependent_Narrowing: 11634 // Implicit conversion to a narrower type, but the expression is 11635 // value-dependent so we can't tell whether it's actually narrowing. 11636 case NK_Not_Narrowing: 11637 return false; 11638 11639 case NK_Constant_Narrowing: 11640 // Implicit conversion to a narrower type, and the value is not a constant 11641 // expression. 11642 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11643 << /*Constant*/ 1 11644 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11645 return true; 11646 11647 case NK_Variable_Narrowing: 11648 // Implicit conversion to a narrower type, and the value is not a constant 11649 // expression. 11650 case NK_Type_Narrowing: 11651 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11652 << /*Constant*/ 0 << FromType << ToType; 11653 // TODO: It's not a constant expression, but what if the user intended it 11654 // to be? Can we produce notes to help them figure out why it isn't? 11655 return true; 11656 } 11657 llvm_unreachable("unhandled case in switch"); 11658 } 11659 11660 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11661 ExprResult &LHS, 11662 ExprResult &RHS, 11663 SourceLocation Loc) { 11664 QualType LHSType = LHS.get()->getType(); 11665 QualType RHSType = RHS.get()->getType(); 11666 // Dig out the original argument type and expression before implicit casts 11667 // were applied. These are the types/expressions we need to check the 11668 // [expr.spaceship] requirements against. 11669 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11670 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11671 QualType LHSStrippedType = LHSStripped.get()->getType(); 11672 QualType RHSStrippedType = RHSStripped.get()->getType(); 11673 11674 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11675 // other is not, the program is ill-formed. 11676 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11677 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11678 return QualType(); 11679 } 11680 11681 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11682 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11683 RHSStrippedType->isEnumeralType(); 11684 if (NumEnumArgs == 1) { 11685 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11686 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11687 if (OtherTy->hasFloatingRepresentation()) { 11688 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11689 return QualType(); 11690 } 11691 } 11692 if (NumEnumArgs == 2) { 11693 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11694 // type E, the operator yields the result of converting the operands 11695 // to the underlying type of E and applying <=> to the converted operands. 11696 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11697 S.InvalidOperands(Loc, LHS, RHS); 11698 return QualType(); 11699 } 11700 QualType IntType = 11701 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11702 assert(IntType->isArithmeticType()); 11703 11704 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11705 // promote the boolean type, and all other promotable integer types, to 11706 // avoid this. 11707 if (IntType->isPromotableIntegerType()) 11708 IntType = S.Context.getPromotedIntegerType(IntType); 11709 11710 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11711 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11712 LHSType = RHSType = IntType; 11713 } 11714 11715 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11716 // usual arithmetic conversions are applied to the operands. 11717 QualType Type = 11718 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11719 if (LHS.isInvalid() || RHS.isInvalid()) 11720 return QualType(); 11721 if (Type.isNull()) 11722 return S.InvalidOperands(Loc, LHS, RHS); 11723 11724 Optional<ComparisonCategoryType> CCT = 11725 getComparisonCategoryForBuiltinCmp(Type); 11726 if (!CCT) 11727 return S.InvalidOperands(Loc, LHS, RHS); 11728 11729 bool HasNarrowing = checkThreeWayNarrowingConversion( 11730 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11731 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11732 RHS.get()->getBeginLoc()); 11733 if (HasNarrowing) 11734 return QualType(); 11735 11736 assert(!Type.isNull() && "composite type for <=> has not been set"); 11737 11738 return S.CheckComparisonCategoryType( 11739 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11740 } 11741 11742 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11743 ExprResult &RHS, 11744 SourceLocation Loc, 11745 BinaryOperatorKind Opc) { 11746 if (Opc == BO_Cmp) 11747 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11748 11749 // C99 6.5.8p3 / C99 6.5.9p4 11750 QualType Type = 11751 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11752 if (LHS.isInvalid() || RHS.isInvalid()) 11753 return QualType(); 11754 if (Type.isNull()) 11755 return S.InvalidOperands(Loc, LHS, RHS); 11756 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11757 11758 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11759 return S.InvalidOperands(Loc, LHS, RHS); 11760 11761 // Check for comparisons of floating point operands using != and ==. 11762 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11763 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11764 11765 // The result of comparisons is 'bool' in C++, 'int' in C. 11766 return S.Context.getLogicalOperationType(); 11767 } 11768 11769 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11770 if (!NullE.get()->getType()->isAnyPointerType()) 11771 return; 11772 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11773 if (!E.get()->getType()->isAnyPointerType() && 11774 E.get()->isNullPointerConstant(Context, 11775 Expr::NPC_ValueDependentIsNotNull) == 11776 Expr::NPCK_ZeroExpression) { 11777 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11778 if (CL->getValue() == 0) 11779 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11780 << NullValue 11781 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11782 NullValue ? "NULL" : "(void *)0"); 11783 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11784 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11785 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11786 if (T == Context.CharTy) 11787 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11788 << NullValue 11789 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11790 NullValue ? "NULL" : "(void *)0"); 11791 } 11792 } 11793 } 11794 11795 // C99 6.5.8, C++ [expr.rel] 11796 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11797 SourceLocation Loc, 11798 BinaryOperatorKind Opc) { 11799 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11800 bool IsThreeWay = Opc == BO_Cmp; 11801 bool IsOrdered = IsRelational || IsThreeWay; 11802 auto IsAnyPointerType = [](ExprResult E) { 11803 QualType Ty = E.get()->getType(); 11804 return Ty->isPointerType() || Ty->isMemberPointerType(); 11805 }; 11806 11807 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11808 // type, array-to-pointer, ..., conversions are performed on both operands to 11809 // bring them to their composite type. 11810 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11811 // any type-related checks. 11812 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11813 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11814 if (LHS.isInvalid()) 11815 return QualType(); 11816 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11817 if (RHS.isInvalid()) 11818 return QualType(); 11819 } else { 11820 LHS = DefaultLvalueConversion(LHS.get()); 11821 if (LHS.isInvalid()) 11822 return QualType(); 11823 RHS = DefaultLvalueConversion(RHS.get()); 11824 if (RHS.isInvalid()) 11825 return QualType(); 11826 } 11827 11828 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11829 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11830 CheckPtrComparisonWithNullChar(LHS, RHS); 11831 CheckPtrComparisonWithNullChar(RHS, LHS); 11832 } 11833 11834 // Handle vector comparisons separately. 11835 if (LHS.get()->getType()->isVectorType() || 11836 RHS.get()->getType()->isVectorType()) 11837 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11838 11839 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11840 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11841 11842 QualType LHSType = LHS.get()->getType(); 11843 QualType RHSType = RHS.get()->getType(); 11844 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11845 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11846 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11847 11848 const Expr::NullPointerConstantKind LHSNullKind = 11849 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11850 const Expr::NullPointerConstantKind RHSNullKind = 11851 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11852 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11853 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11854 11855 auto computeResultTy = [&]() { 11856 if (Opc != BO_Cmp) 11857 return Context.getLogicalOperationType(); 11858 assert(getLangOpts().CPlusPlus); 11859 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11860 11861 QualType CompositeTy = LHS.get()->getType(); 11862 assert(!CompositeTy->isReferenceType()); 11863 11864 Optional<ComparisonCategoryType> CCT = 11865 getComparisonCategoryForBuiltinCmp(CompositeTy); 11866 if (!CCT) 11867 return InvalidOperands(Loc, LHS, RHS); 11868 11869 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11870 // P0946R0: Comparisons between a null pointer constant and an object 11871 // pointer result in std::strong_equality, which is ill-formed under 11872 // P1959R0. 11873 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11874 << (LHSIsNull ? LHS.get()->getSourceRange() 11875 : RHS.get()->getSourceRange()); 11876 return QualType(); 11877 } 11878 11879 return CheckComparisonCategoryType( 11880 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11881 }; 11882 11883 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11884 bool IsEquality = Opc == BO_EQ; 11885 if (RHSIsNull) 11886 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11887 RHS.get()->getSourceRange()); 11888 else 11889 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11890 LHS.get()->getSourceRange()); 11891 } 11892 11893 if (IsOrdered && LHSType->isFunctionPointerType() && 11894 RHSType->isFunctionPointerType()) { 11895 // Valid unless a relational comparison of function pointers 11896 bool IsError = Opc == BO_Cmp; 11897 auto DiagID = 11898 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 11899 : getLangOpts().CPlusPlus 11900 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 11901 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 11902 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 11903 << RHS.get()->getSourceRange(); 11904 if (IsError) 11905 return QualType(); 11906 } 11907 11908 if ((LHSType->isIntegerType() && !LHSIsNull) || 11909 (RHSType->isIntegerType() && !RHSIsNull)) { 11910 // Skip normal pointer conversion checks in this case; we have better 11911 // diagnostics for this below. 11912 } else if (getLangOpts().CPlusPlus) { 11913 // Equality comparison of a function pointer to a void pointer is invalid, 11914 // but we allow it as an extension. 11915 // FIXME: If we really want to allow this, should it be part of composite 11916 // pointer type computation so it works in conditionals too? 11917 if (!IsOrdered && 11918 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11919 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11920 // This is a gcc extension compatibility comparison. 11921 // In a SFINAE context, we treat this as a hard error to maintain 11922 // conformance with the C++ standard. 11923 diagnoseFunctionPointerToVoidComparison( 11924 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11925 11926 if (isSFINAEContext()) 11927 return QualType(); 11928 11929 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11930 return computeResultTy(); 11931 } 11932 11933 // C++ [expr.eq]p2: 11934 // If at least one operand is a pointer [...] bring them to their 11935 // composite pointer type. 11936 // C++ [expr.spaceship]p6 11937 // If at least one of the operands is of pointer type, [...] bring them 11938 // to their composite pointer type. 11939 // C++ [expr.rel]p2: 11940 // If both operands are pointers, [...] bring them to their composite 11941 // pointer type. 11942 // For <=>, the only valid non-pointer types are arrays and functions, and 11943 // we already decayed those, so this is really the same as the relational 11944 // comparison rule. 11945 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11946 (IsOrdered ? 2 : 1) && 11947 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11948 RHSType->isObjCObjectPointerType()))) { 11949 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11950 return QualType(); 11951 return computeResultTy(); 11952 } 11953 } else if (LHSType->isPointerType() && 11954 RHSType->isPointerType()) { // C99 6.5.8p2 11955 // All of the following pointer-related warnings are GCC extensions, except 11956 // when handling null pointer constants. 11957 QualType LCanPointeeTy = 11958 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11959 QualType RCanPointeeTy = 11960 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11961 11962 // C99 6.5.9p2 and C99 6.5.8p2 11963 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11964 RCanPointeeTy.getUnqualifiedType())) { 11965 if (IsRelational) { 11966 // Pointers both need to point to complete or incomplete types 11967 if ((LCanPointeeTy->isIncompleteType() != 11968 RCanPointeeTy->isIncompleteType()) && 11969 !getLangOpts().C11) { 11970 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11971 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11972 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11973 << RCanPointeeTy->isIncompleteType(); 11974 } 11975 } 11976 } else if (!IsRelational && 11977 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11978 // Valid unless comparison between non-null pointer and function pointer 11979 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11980 && !LHSIsNull && !RHSIsNull) 11981 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11982 /*isError*/false); 11983 } else { 11984 // Invalid 11985 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11986 } 11987 if (LCanPointeeTy != RCanPointeeTy) { 11988 // Treat NULL constant as a special case in OpenCL. 11989 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11990 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11991 Diag(Loc, 11992 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11993 << LHSType << RHSType << 0 /* comparison */ 11994 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11995 } 11996 } 11997 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11998 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11999 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 12000 : CK_BitCast; 12001 if (LHSIsNull && !RHSIsNull) 12002 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 12003 else 12004 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 12005 } 12006 return computeResultTy(); 12007 } 12008 12009 if (getLangOpts().CPlusPlus) { 12010 // C++ [expr.eq]p4: 12011 // Two operands of type std::nullptr_t or one operand of type 12012 // std::nullptr_t and the other a null pointer constant compare equal. 12013 if (!IsOrdered && LHSIsNull && RHSIsNull) { 12014 if (LHSType->isNullPtrType()) { 12015 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12016 return computeResultTy(); 12017 } 12018 if (RHSType->isNullPtrType()) { 12019 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12020 return computeResultTy(); 12021 } 12022 } 12023 12024 // Comparison of Objective-C pointers and block pointers against nullptr_t. 12025 // These aren't covered by the composite pointer type rules. 12026 if (!IsOrdered && RHSType->isNullPtrType() && 12027 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 12028 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12029 return computeResultTy(); 12030 } 12031 if (!IsOrdered && LHSType->isNullPtrType() && 12032 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 12033 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12034 return computeResultTy(); 12035 } 12036 12037 if (IsRelational && 12038 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 12039 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 12040 // HACK: Relational comparison of nullptr_t against a pointer type is 12041 // invalid per DR583, but we allow it within std::less<> and friends, 12042 // since otherwise common uses of it break. 12043 // FIXME: Consider removing this hack once LWG fixes std::less<> and 12044 // friends to have std::nullptr_t overload candidates. 12045 DeclContext *DC = CurContext; 12046 if (isa<FunctionDecl>(DC)) 12047 DC = DC->getParent(); 12048 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 12049 if (CTSD->isInStdNamespace() && 12050 llvm::StringSwitch<bool>(CTSD->getName()) 12051 .Cases("less", "less_equal", "greater", "greater_equal", true) 12052 .Default(false)) { 12053 if (RHSType->isNullPtrType()) 12054 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12055 else 12056 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12057 return computeResultTy(); 12058 } 12059 } 12060 } 12061 12062 // C++ [expr.eq]p2: 12063 // If at least one operand is a pointer to member, [...] bring them to 12064 // their composite pointer type. 12065 if (!IsOrdered && 12066 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 12067 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12068 return QualType(); 12069 else 12070 return computeResultTy(); 12071 } 12072 } 12073 12074 // Handle block pointer types. 12075 if (!IsOrdered && LHSType->isBlockPointerType() && 12076 RHSType->isBlockPointerType()) { 12077 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 12078 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 12079 12080 if (!LHSIsNull && !RHSIsNull && 12081 !Context.typesAreCompatible(lpointee, rpointee)) { 12082 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12083 << LHSType << RHSType << LHS.get()->getSourceRange() 12084 << RHS.get()->getSourceRange(); 12085 } 12086 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12087 return computeResultTy(); 12088 } 12089 12090 // Allow block pointers to be compared with null pointer constants. 12091 if (!IsOrdered 12092 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 12093 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 12094 if (!LHSIsNull && !RHSIsNull) { 12095 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 12096 ->getPointeeType()->isVoidType()) 12097 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12098 ->getPointeeType()->isVoidType()))) 12099 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12100 << LHSType << RHSType << LHS.get()->getSourceRange() 12101 << RHS.get()->getSourceRange(); 12102 } 12103 if (LHSIsNull && !RHSIsNull) 12104 LHS = ImpCastExprToType(LHS.get(), RHSType, 12105 RHSType->isPointerType() ? CK_BitCast 12106 : CK_AnyPointerToBlockPointerCast); 12107 else 12108 RHS = ImpCastExprToType(RHS.get(), LHSType, 12109 LHSType->isPointerType() ? CK_BitCast 12110 : CK_AnyPointerToBlockPointerCast); 12111 return computeResultTy(); 12112 } 12113 12114 if (LHSType->isObjCObjectPointerType() || 12115 RHSType->isObjCObjectPointerType()) { 12116 const PointerType *LPT = LHSType->getAs<PointerType>(); 12117 const PointerType *RPT = RHSType->getAs<PointerType>(); 12118 if (LPT || RPT) { 12119 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12120 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12121 12122 if (!LPtrToVoid && !RPtrToVoid && 12123 !Context.typesAreCompatible(LHSType, RHSType)) { 12124 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12125 /*isError*/false); 12126 } 12127 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12128 // the RHS, but we have test coverage for this behavior. 12129 // FIXME: Consider using convertPointersToCompositeType in C++. 12130 if (LHSIsNull && !RHSIsNull) { 12131 Expr *E = LHS.get(); 12132 if (getLangOpts().ObjCAutoRefCount) 12133 CheckObjCConversion(SourceRange(), RHSType, E, 12134 CCK_ImplicitConversion); 12135 LHS = ImpCastExprToType(E, RHSType, 12136 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12137 } 12138 else { 12139 Expr *E = RHS.get(); 12140 if (getLangOpts().ObjCAutoRefCount) 12141 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12142 /*Diagnose=*/true, 12143 /*DiagnoseCFAudited=*/false, Opc); 12144 RHS = ImpCastExprToType(E, LHSType, 12145 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12146 } 12147 return computeResultTy(); 12148 } 12149 if (LHSType->isObjCObjectPointerType() && 12150 RHSType->isObjCObjectPointerType()) { 12151 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12152 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12153 /*isError*/false); 12154 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12155 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12156 12157 if (LHSIsNull && !RHSIsNull) 12158 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12159 else 12160 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12161 return computeResultTy(); 12162 } 12163 12164 if (!IsOrdered && LHSType->isBlockPointerType() && 12165 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12166 LHS = ImpCastExprToType(LHS.get(), RHSType, 12167 CK_BlockPointerToObjCPointerCast); 12168 return computeResultTy(); 12169 } else if (!IsOrdered && 12170 LHSType->isBlockCompatibleObjCPointerType(Context) && 12171 RHSType->isBlockPointerType()) { 12172 RHS = ImpCastExprToType(RHS.get(), LHSType, 12173 CK_BlockPointerToObjCPointerCast); 12174 return computeResultTy(); 12175 } 12176 } 12177 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12178 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12179 unsigned DiagID = 0; 12180 bool isError = false; 12181 if (LangOpts.DebuggerSupport) { 12182 // Under a debugger, allow the comparison of pointers to integers, 12183 // since users tend to want to compare addresses. 12184 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12185 (RHSIsNull && RHSType->isIntegerType())) { 12186 if (IsOrdered) { 12187 isError = getLangOpts().CPlusPlus; 12188 DiagID = 12189 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12190 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12191 } 12192 } else if (getLangOpts().CPlusPlus) { 12193 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12194 isError = true; 12195 } else if (IsOrdered) 12196 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12197 else 12198 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12199 12200 if (DiagID) { 12201 Diag(Loc, DiagID) 12202 << LHSType << RHSType << LHS.get()->getSourceRange() 12203 << RHS.get()->getSourceRange(); 12204 if (isError) 12205 return QualType(); 12206 } 12207 12208 if (LHSType->isIntegerType()) 12209 LHS = ImpCastExprToType(LHS.get(), RHSType, 12210 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12211 else 12212 RHS = ImpCastExprToType(RHS.get(), LHSType, 12213 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12214 return computeResultTy(); 12215 } 12216 12217 // Handle block pointers. 12218 if (!IsOrdered && RHSIsNull 12219 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12220 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12221 return computeResultTy(); 12222 } 12223 if (!IsOrdered && LHSIsNull 12224 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12225 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12226 return computeResultTy(); 12227 } 12228 12229 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 12230 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12231 return computeResultTy(); 12232 } 12233 12234 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12235 return computeResultTy(); 12236 } 12237 12238 if (LHSIsNull && RHSType->isQueueT()) { 12239 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12240 return computeResultTy(); 12241 } 12242 12243 if (LHSType->isQueueT() && RHSIsNull) { 12244 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12245 return computeResultTy(); 12246 } 12247 } 12248 12249 return InvalidOperands(Loc, LHS, RHS); 12250 } 12251 12252 // Return a signed ext_vector_type that is of identical size and number of 12253 // elements. For floating point vectors, return an integer type of identical 12254 // size and number of elements. In the non ext_vector_type case, search from 12255 // the largest type to the smallest type to avoid cases where long long == long, 12256 // where long gets picked over long long. 12257 QualType Sema::GetSignedVectorType(QualType V) { 12258 const VectorType *VTy = V->castAs<VectorType>(); 12259 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12260 12261 if (isa<ExtVectorType>(VTy)) { 12262 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12263 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12264 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12265 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12266 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12267 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12268 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12269 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12270 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12271 "Unhandled vector element size in vector compare"); 12272 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12273 } 12274 12275 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12276 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12277 VectorType::GenericVector); 12278 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12279 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12280 VectorType::GenericVector); 12281 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12282 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12283 VectorType::GenericVector); 12284 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12285 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12286 VectorType::GenericVector); 12287 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12288 "Unhandled vector element size in vector compare"); 12289 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12290 VectorType::GenericVector); 12291 } 12292 12293 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12294 /// operates on extended vector types. Instead of producing an IntTy result, 12295 /// like a scalar comparison, a vector comparison produces a vector of integer 12296 /// types. 12297 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12298 SourceLocation Loc, 12299 BinaryOperatorKind Opc) { 12300 if (Opc == BO_Cmp) { 12301 Diag(Loc, diag::err_three_way_vector_comparison); 12302 return QualType(); 12303 } 12304 12305 // Check to make sure we're operating on vectors of the same type and width, 12306 // Allowing one side to be a scalar of element type. 12307 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12308 /*AllowBothBool*/true, 12309 /*AllowBoolConversions*/getLangOpts().ZVector); 12310 if (vType.isNull()) 12311 return vType; 12312 12313 QualType LHSType = LHS.get()->getType(); 12314 12315 // Determine the return type of a vector compare. By default clang will return 12316 // a scalar for all vector compares except vector bool and vector pixel. 12317 // With the gcc compiler we will always return a vector type and with the xl 12318 // compiler we will always return a scalar type. This switch allows choosing 12319 // which behavior is prefered. 12320 if (getLangOpts().AltiVec) { 12321 switch (getLangOpts().getAltivecSrcCompat()) { 12322 case LangOptions::AltivecSrcCompatKind::Mixed: 12323 // If AltiVec, the comparison results in a numeric type, i.e. 12324 // bool for C++, int for C 12325 if (vType->castAs<VectorType>()->getVectorKind() == 12326 VectorType::AltiVecVector) 12327 return Context.getLogicalOperationType(); 12328 else 12329 Diag(Loc, diag::warn_deprecated_altivec_src_compat); 12330 break; 12331 case LangOptions::AltivecSrcCompatKind::GCC: 12332 // For GCC we always return the vector type. 12333 break; 12334 case LangOptions::AltivecSrcCompatKind::XL: 12335 return Context.getLogicalOperationType(); 12336 break; 12337 } 12338 } 12339 12340 // For non-floating point types, check for self-comparisons of the form 12341 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12342 // often indicate logic errors in the program. 12343 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12344 12345 // Check for comparisons of floating point operands using != and ==. 12346 if (BinaryOperator::isEqualityOp(Opc) && 12347 LHSType->hasFloatingRepresentation()) { 12348 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12349 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12350 } 12351 12352 // Return a signed type for the vector. 12353 return GetSignedVectorType(vType); 12354 } 12355 12356 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12357 const ExprResult &XorRHS, 12358 const SourceLocation Loc) { 12359 // Do not diagnose macros. 12360 if (Loc.isMacroID()) 12361 return; 12362 12363 // Do not diagnose if both LHS and RHS are macros. 12364 if (XorLHS.get()->getExprLoc().isMacroID() && 12365 XorRHS.get()->getExprLoc().isMacroID()) 12366 return; 12367 12368 bool Negative = false; 12369 bool ExplicitPlus = false; 12370 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12371 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12372 12373 if (!LHSInt) 12374 return; 12375 if (!RHSInt) { 12376 // Check negative literals. 12377 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12378 UnaryOperatorKind Opc = UO->getOpcode(); 12379 if (Opc != UO_Minus && Opc != UO_Plus) 12380 return; 12381 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12382 if (!RHSInt) 12383 return; 12384 Negative = (Opc == UO_Minus); 12385 ExplicitPlus = !Negative; 12386 } else { 12387 return; 12388 } 12389 } 12390 12391 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12392 llvm::APInt RightSideValue = RHSInt->getValue(); 12393 if (LeftSideValue != 2 && LeftSideValue != 10) 12394 return; 12395 12396 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12397 return; 12398 12399 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12400 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12401 llvm::StringRef ExprStr = 12402 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12403 12404 CharSourceRange XorRange = 12405 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12406 llvm::StringRef XorStr = 12407 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12408 // Do not diagnose if xor keyword/macro is used. 12409 if (XorStr == "xor") 12410 return; 12411 12412 std::string LHSStr = std::string(Lexer::getSourceText( 12413 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12414 S.getSourceManager(), S.getLangOpts())); 12415 std::string RHSStr = std::string(Lexer::getSourceText( 12416 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12417 S.getSourceManager(), S.getLangOpts())); 12418 12419 if (Negative) { 12420 RightSideValue = -RightSideValue; 12421 RHSStr = "-" + RHSStr; 12422 } else if (ExplicitPlus) { 12423 RHSStr = "+" + RHSStr; 12424 } 12425 12426 StringRef LHSStrRef = LHSStr; 12427 StringRef RHSStrRef = RHSStr; 12428 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12429 // literals. 12430 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12431 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12432 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12433 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12434 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12435 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12436 LHSStrRef.contains('\'') || RHSStrRef.contains('\'')) 12437 return; 12438 12439 bool SuggestXor = 12440 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12441 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12442 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12443 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12444 std::string SuggestedExpr = "1 << " + RHSStr; 12445 bool Overflow = false; 12446 llvm::APInt One = (LeftSideValue - 1); 12447 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12448 if (Overflow) { 12449 if (RightSideIntValue < 64) 12450 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12451 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 12452 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12453 else if (RightSideIntValue == 64) 12454 S.Diag(Loc, diag::warn_xor_used_as_pow) 12455 << ExprStr << toString(XorValue, 10, true); 12456 else 12457 return; 12458 } else { 12459 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12460 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 12461 << toString(PowValue, 10, true) 12462 << FixItHint::CreateReplacement( 12463 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12464 } 12465 12466 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12467 << ("0x2 ^ " + RHSStr) << SuggestXor; 12468 } else if (LeftSideValue == 10) { 12469 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12470 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12471 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 12472 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12473 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12474 << ("0xA ^ " + RHSStr) << SuggestXor; 12475 } 12476 } 12477 12478 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12479 SourceLocation Loc) { 12480 // Ensure that either both operands are of the same vector type, or 12481 // one operand is of a vector type and the other is of its element type. 12482 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12483 /*AllowBothBool*/true, 12484 /*AllowBoolConversions*/false); 12485 if (vType.isNull()) 12486 return InvalidOperands(Loc, LHS, RHS); 12487 if (getLangOpts().OpenCL && 12488 getLangOpts().getOpenCLCompatibleVersion() < 120 && 12489 vType->hasFloatingRepresentation()) 12490 return InvalidOperands(Loc, LHS, RHS); 12491 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12492 // usage of the logical operators && and || with vectors in C. This 12493 // check could be notionally dropped. 12494 if (!getLangOpts().CPlusPlus && 12495 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12496 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12497 12498 return GetSignedVectorType(LHS.get()->getType()); 12499 } 12500 12501 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12502 SourceLocation Loc, 12503 bool IsCompAssign) { 12504 if (!IsCompAssign) { 12505 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12506 if (LHS.isInvalid()) 12507 return QualType(); 12508 } 12509 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12510 if (RHS.isInvalid()) 12511 return QualType(); 12512 12513 // For conversion purposes, we ignore any qualifiers. 12514 // For example, "const float" and "float" are equivalent. 12515 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12516 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12517 12518 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12519 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12520 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12521 12522 if (Context.hasSameType(LHSType, RHSType)) 12523 return LHSType; 12524 12525 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12526 // case we have to return InvalidOperands. 12527 ExprResult OriginalLHS = LHS; 12528 ExprResult OriginalRHS = RHS; 12529 if (LHSMatType && !RHSMatType) { 12530 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12531 if (!RHS.isInvalid()) 12532 return LHSType; 12533 12534 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12535 } 12536 12537 if (!LHSMatType && RHSMatType) { 12538 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12539 if (!LHS.isInvalid()) 12540 return RHSType; 12541 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12542 } 12543 12544 return InvalidOperands(Loc, LHS, RHS); 12545 } 12546 12547 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12548 SourceLocation Loc, 12549 bool IsCompAssign) { 12550 if (!IsCompAssign) { 12551 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12552 if (LHS.isInvalid()) 12553 return QualType(); 12554 } 12555 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12556 if (RHS.isInvalid()) 12557 return QualType(); 12558 12559 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12560 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12561 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12562 12563 if (LHSMatType && RHSMatType) { 12564 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12565 return InvalidOperands(Loc, LHS, RHS); 12566 12567 if (!Context.hasSameType(LHSMatType->getElementType(), 12568 RHSMatType->getElementType())) 12569 return InvalidOperands(Loc, LHS, RHS); 12570 12571 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12572 LHSMatType->getNumRows(), 12573 RHSMatType->getNumColumns()); 12574 } 12575 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12576 } 12577 12578 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12579 SourceLocation Loc, 12580 BinaryOperatorKind Opc) { 12581 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12582 12583 bool IsCompAssign = 12584 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12585 12586 if (LHS.get()->getType()->isVectorType() || 12587 RHS.get()->getType()->isVectorType()) { 12588 if (LHS.get()->getType()->hasIntegerRepresentation() && 12589 RHS.get()->getType()->hasIntegerRepresentation()) 12590 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12591 /*AllowBothBool*/true, 12592 /*AllowBoolConversions*/getLangOpts().ZVector); 12593 return InvalidOperands(Loc, LHS, RHS); 12594 } 12595 12596 if (Opc == BO_And) 12597 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12598 12599 if (LHS.get()->getType()->hasFloatingRepresentation() || 12600 RHS.get()->getType()->hasFloatingRepresentation()) 12601 return InvalidOperands(Loc, LHS, RHS); 12602 12603 ExprResult LHSResult = LHS, RHSResult = RHS; 12604 QualType compType = UsualArithmeticConversions( 12605 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12606 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12607 return QualType(); 12608 LHS = LHSResult.get(); 12609 RHS = RHSResult.get(); 12610 12611 if (Opc == BO_Xor) 12612 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12613 12614 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12615 return compType; 12616 return InvalidOperands(Loc, LHS, RHS); 12617 } 12618 12619 // C99 6.5.[13,14] 12620 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12621 SourceLocation Loc, 12622 BinaryOperatorKind Opc) { 12623 // Check vector operands differently. 12624 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12625 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12626 12627 bool EnumConstantInBoolContext = false; 12628 for (const ExprResult &HS : {LHS, RHS}) { 12629 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12630 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12631 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12632 EnumConstantInBoolContext = true; 12633 } 12634 } 12635 12636 if (EnumConstantInBoolContext) 12637 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12638 12639 // Diagnose cases where the user write a logical and/or but probably meant a 12640 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12641 // is a constant. 12642 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12643 !LHS.get()->getType()->isBooleanType() && 12644 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12645 // Don't warn in macros or template instantiations. 12646 !Loc.isMacroID() && !inTemplateInstantiation()) { 12647 // If the RHS can be constant folded, and if it constant folds to something 12648 // that isn't 0 or 1 (which indicate a potential logical operation that 12649 // happened to fold to true/false) then warn. 12650 // Parens on the RHS are ignored. 12651 Expr::EvalResult EVResult; 12652 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12653 llvm::APSInt Result = EVResult.Val.getInt(); 12654 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12655 !RHS.get()->getExprLoc().isMacroID()) || 12656 (Result != 0 && Result != 1)) { 12657 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12658 << RHS.get()->getSourceRange() 12659 << (Opc == BO_LAnd ? "&&" : "||"); 12660 // Suggest replacing the logical operator with the bitwise version 12661 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12662 << (Opc == BO_LAnd ? "&" : "|") 12663 << FixItHint::CreateReplacement(SourceRange( 12664 Loc, getLocForEndOfToken(Loc)), 12665 Opc == BO_LAnd ? "&" : "|"); 12666 if (Opc == BO_LAnd) 12667 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12668 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12669 << FixItHint::CreateRemoval( 12670 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12671 RHS.get()->getEndLoc())); 12672 } 12673 } 12674 } 12675 12676 if (!Context.getLangOpts().CPlusPlus) { 12677 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12678 // not operate on the built-in scalar and vector float types. 12679 if (Context.getLangOpts().OpenCL && 12680 Context.getLangOpts().OpenCLVersion < 120) { 12681 if (LHS.get()->getType()->isFloatingType() || 12682 RHS.get()->getType()->isFloatingType()) 12683 return InvalidOperands(Loc, LHS, RHS); 12684 } 12685 12686 LHS = UsualUnaryConversions(LHS.get()); 12687 if (LHS.isInvalid()) 12688 return QualType(); 12689 12690 RHS = UsualUnaryConversions(RHS.get()); 12691 if (RHS.isInvalid()) 12692 return QualType(); 12693 12694 if (!LHS.get()->getType()->isScalarType() || 12695 !RHS.get()->getType()->isScalarType()) 12696 return InvalidOperands(Loc, LHS, RHS); 12697 12698 return Context.IntTy; 12699 } 12700 12701 // The following is safe because we only use this method for 12702 // non-overloadable operands. 12703 12704 // C++ [expr.log.and]p1 12705 // C++ [expr.log.or]p1 12706 // The operands are both contextually converted to type bool. 12707 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12708 if (LHSRes.isInvalid()) 12709 return InvalidOperands(Loc, LHS, RHS); 12710 LHS = LHSRes; 12711 12712 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12713 if (RHSRes.isInvalid()) 12714 return InvalidOperands(Loc, LHS, RHS); 12715 RHS = RHSRes; 12716 12717 // C++ [expr.log.and]p2 12718 // C++ [expr.log.or]p2 12719 // The result is a bool. 12720 return Context.BoolTy; 12721 } 12722 12723 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12724 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12725 if (!ME) return false; 12726 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12727 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12728 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12729 if (!Base) return false; 12730 return Base->getMethodDecl() != nullptr; 12731 } 12732 12733 /// Is the given expression (which must be 'const') a reference to a 12734 /// variable which was originally non-const, but which has become 12735 /// 'const' due to being captured within a block? 12736 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12737 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12738 assert(E->isLValue() && E->getType().isConstQualified()); 12739 E = E->IgnoreParens(); 12740 12741 // Must be a reference to a declaration from an enclosing scope. 12742 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12743 if (!DRE) return NCCK_None; 12744 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12745 12746 // The declaration must be a variable which is not declared 'const'. 12747 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12748 if (!var) return NCCK_None; 12749 if (var->getType().isConstQualified()) return NCCK_None; 12750 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12751 12752 // Decide whether the first capture was for a block or a lambda. 12753 DeclContext *DC = S.CurContext, *Prev = nullptr; 12754 // Decide whether the first capture was for a block or a lambda. 12755 while (DC) { 12756 // For init-capture, it is possible that the variable belongs to the 12757 // template pattern of the current context. 12758 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12759 if (var->isInitCapture() && 12760 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12761 break; 12762 if (DC == var->getDeclContext()) 12763 break; 12764 Prev = DC; 12765 DC = DC->getParent(); 12766 } 12767 // Unless we have an init-capture, we've gone one step too far. 12768 if (!var->isInitCapture()) 12769 DC = Prev; 12770 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12771 } 12772 12773 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12774 Ty = Ty.getNonReferenceType(); 12775 if (IsDereference && Ty->isPointerType()) 12776 Ty = Ty->getPointeeType(); 12777 return !Ty.isConstQualified(); 12778 } 12779 12780 // Update err_typecheck_assign_const and note_typecheck_assign_const 12781 // when this enum is changed. 12782 enum { 12783 ConstFunction, 12784 ConstVariable, 12785 ConstMember, 12786 ConstMethod, 12787 NestedConstMember, 12788 ConstUnknown, // Keep as last element 12789 }; 12790 12791 /// Emit the "read-only variable not assignable" error and print notes to give 12792 /// more information about why the variable is not assignable, such as pointing 12793 /// to the declaration of a const variable, showing that a method is const, or 12794 /// that the function is returning a const reference. 12795 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12796 SourceLocation Loc) { 12797 SourceRange ExprRange = E->getSourceRange(); 12798 12799 // Only emit one error on the first const found. All other consts will emit 12800 // a note to the error. 12801 bool DiagnosticEmitted = false; 12802 12803 // Track if the current expression is the result of a dereference, and if the 12804 // next checked expression is the result of a dereference. 12805 bool IsDereference = false; 12806 bool NextIsDereference = false; 12807 12808 // Loop to process MemberExpr chains. 12809 while (true) { 12810 IsDereference = NextIsDereference; 12811 12812 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12813 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12814 NextIsDereference = ME->isArrow(); 12815 const ValueDecl *VD = ME->getMemberDecl(); 12816 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12817 // Mutable fields can be modified even if the class is const. 12818 if (Field->isMutable()) { 12819 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12820 break; 12821 } 12822 12823 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12824 if (!DiagnosticEmitted) { 12825 S.Diag(Loc, diag::err_typecheck_assign_const) 12826 << ExprRange << ConstMember << false /*static*/ << Field 12827 << Field->getType(); 12828 DiagnosticEmitted = true; 12829 } 12830 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12831 << ConstMember << false /*static*/ << Field << Field->getType() 12832 << Field->getSourceRange(); 12833 } 12834 E = ME->getBase(); 12835 continue; 12836 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12837 if (VDecl->getType().isConstQualified()) { 12838 if (!DiagnosticEmitted) { 12839 S.Diag(Loc, diag::err_typecheck_assign_const) 12840 << ExprRange << ConstMember << true /*static*/ << VDecl 12841 << VDecl->getType(); 12842 DiagnosticEmitted = true; 12843 } 12844 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12845 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12846 << VDecl->getSourceRange(); 12847 } 12848 // Static fields do not inherit constness from parents. 12849 break; 12850 } 12851 break; // End MemberExpr 12852 } else if (const ArraySubscriptExpr *ASE = 12853 dyn_cast<ArraySubscriptExpr>(E)) { 12854 E = ASE->getBase()->IgnoreParenImpCasts(); 12855 continue; 12856 } else if (const ExtVectorElementExpr *EVE = 12857 dyn_cast<ExtVectorElementExpr>(E)) { 12858 E = EVE->getBase()->IgnoreParenImpCasts(); 12859 continue; 12860 } 12861 break; 12862 } 12863 12864 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12865 // Function calls 12866 const FunctionDecl *FD = CE->getDirectCallee(); 12867 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12868 if (!DiagnosticEmitted) { 12869 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12870 << ConstFunction << FD; 12871 DiagnosticEmitted = true; 12872 } 12873 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12874 diag::note_typecheck_assign_const) 12875 << ConstFunction << FD << FD->getReturnType() 12876 << FD->getReturnTypeSourceRange(); 12877 } 12878 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12879 // Point to variable declaration. 12880 if (const ValueDecl *VD = DRE->getDecl()) { 12881 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12882 if (!DiagnosticEmitted) { 12883 S.Diag(Loc, diag::err_typecheck_assign_const) 12884 << ExprRange << ConstVariable << VD << VD->getType(); 12885 DiagnosticEmitted = true; 12886 } 12887 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12888 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12889 } 12890 } 12891 } else if (isa<CXXThisExpr>(E)) { 12892 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12893 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12894 if (MD->isConst()) { 12895 if (!DiagnosticEmitted) { 12896 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12897 << ConstMethod << MD; 12898 DiagnosticEmitted = true; 12899 } 12900 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12901 << ConstMethod << MD << MD->getSourceRange(); 12902 } 12903 } 12904 } 12905 } 12906 12907 if (DiagnosticEmitted) 12908 return; 12909 12910 // Can't determine a more specific message, so display the generic error. 12911 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12912 } 12913 12914 enum OriginalExprKind { 12915 OEK_Variable, 12916 OEK_Member, 12917 OEK_LValue 12918 }; 12919 12920 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12921 const RecordType *Ty, 12922 SourceLocation Loc, SourceRange Range, 12923 OriginalExprKind OEK, 12924 bool &DiagnosticEmitted) { 12925 std::vector<const RecordType *> RecordTypeList; 12926 RecordTypeList.push_back(Ty); 12927 unsigned NextToCheckIndex = 0; 12928 // We walk the record hierarchy breadth-first to ensure that we print 12929 // diagnostics in field nesting order. 12930 while (RecordTypeList.size() > NextToCheckIndex) { 12931 bool IsNested = NextToCheckIndex > 0; 12932 for (const FieldDecl *Field : 12933 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12934 // First, check every field for constness. 12935 QualType FieldTy = Field->getType(); 12936 if (FieldTy.isConstQualified()) { 12937 if (!DiagnosticEmitted) { 12938 S.Diag(Loc, diag::err_typecheck_assign_const) 12939 << Range << NestedConstMember << OEK << VD 12940 << IsNested << Field; 12941 DiagnosticEmitted = true; 12942 } 12943 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12944 << NestedConstMember << IsNested << Field 12945 << FieldTy << Field->getSourceRange(); 12946 } 12947 12948 // Then we append it to the list to check next in order. 12949 FieldTy = FieldTy.getCanonicalType(); 12950 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12951 if (!llvm::is_contained(RecordTypeList, FieldRecTy)) 12952 RecordTypeList.push_back(FieldRecTy); 12953 } 12954 } 12955 ++NextToCheckIndex; 12956 } 12957 } 12958 12959 /// Emit an error for the case where a record we are trying to assign to has a 12960 /// const-qualified field somewhere in its hierarchy. 12961 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12962 SourceLocation Loc) { 12963 QualType Ty = E->getType(); 12964 assert(Ty->isRecordType() && "lvalue was not record?"); 12965 SourceRange Range = E->getSourceRange(); 12966 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12967 bool DiagEmitted = false; 12968 12969 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12970 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12971 Range, OEK_Member, DiagEmitted); 12972 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12973 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12974 Range, OEK_Variable, DiagEmitted); 12975 else 12976 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12977 Range, OEK_LValue, DiagEmitted); 12978 if (!DiagEmitted) 12979 DiagnoseConstAssignment(S, E, Loc); 12980 } 12981 12982 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12983 /// emit an error and return true. If so, return false. 12984 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12985 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12986 12987 S.CheckShadowingDeclModification(E, Loc); 12988 12989 SourceLocation OrigLoc = Loc; 12990 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12991 &Loc); 12992 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12993 IsLV = Expr::MLV_InvalidMessageExpression; 12994 if (IsLV == Expr::MLV_Valid) 12995 return false; 12996 12997 unsigned DiagID = 0; 12998 bool NeedType = false; 12999 switch (IsLV) { // C99 6.5.16p2 13000 case Expr::MLV_ConstQualified: 13001 // Use a specialized diagnostic when we're assigning to an object 13002 // from an enclosing function or block. 13003 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 13004 if (NCCK == NCCK_Block) 13005 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 13006 else 13007 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 13008 break; 13009 } 13010 13011 // In ARC, use some specialized diagnostics for occasions where we 13012 // infer 'const'. These are always pseudo-strong variables. 13013 if (S.getLangOpts().ObjCAutoRefCount) { 13014 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 13015 if (declRef && isa<VarDecl>(declRef->getDecl())) { 13016 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 13017 13018 // Use the normal diagnostic if it's pseudo-__strong but the 13019 // user actually wrote 'const'. 13020 if (var->isARCPseudoStrong() && 13021 (!var->getTypeSourceInfo() || 13022 !var->getTypeSourceInfo()->getType().isConstQualified())) { 13023 // There are three pseudo-strong cases: 13024 // - self 13025 ObjCMethodDecl *method = S.getCurMethodDecl(); 13026 if (method && var == method->getSelfDecl()) { 13027 DiagID = method->isClassMethod() 13028 ? diag::err_typecheck_arc_assign_self_class_method 13029 : diag::err_typecheck_arc_assign_self; 13030 13031 // - Objective-C externally_retained attribute. 13032 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 13033 isa<ParmVarDecl>(var)) { 13034 DiagID = diag::err_typecheck_arc_assign_externally_retained; 13035 13036 // - fast enumeration variables 13037 } else { 13038 DiagID = diag::err_typecheck_arr_assign_enumeration; 13039 } 13040 13041 SourceRange Assign; 13042 if (Loc != OrigLoc) 13043 Assign = SourceRange(OrigLoc, OrigLoc); 13044 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13045 // We need to preserve the AST regardless, so migration tool 13046 // can do its job. 13047 return false; 13048 } 13049 } 13050 } 13051 13052 // If none of the special cases above are triggered, then this is a 13053 // simple const assignment. 13054 if (DiagID == 0) { 13055 DiagnoseConstAssignment(S, E, Loc); 13056 return true; 13057 } 13058 13059 break; 13060 case Expr::MLV_ConstAddrSpace: 13061 DiagnoseConstAssignment(S, E, Loc); 13062 return true; 13063 case Expr::MLV_ConstQualifiedField: 13064 DiagnoseRecursiveConstFields(S, E, Loc); 13065 return true; 13066 case Expr::MLV_ArrayType: 13067 case Expr::MLV_ArrayTemporary: 13068 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 13069 NeedType = true; 13070 break; 13071 case Expr::MLV_NotObjectType: 13072 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 13073 NeedType = true; 13074 break; 13075 case Expr::MLV_LValueCast: 13076 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 13077 break; 13078 case Expr::MLV_Valid: 13079 llvm_unreachable("did not take early return for MLV_Valid"); 13080 case Expr::MLV_InvalidExpression: 13081 case Expr::MLV_MemberFunction: 13082 case Expr::MLV_ClassTemporary: 13083 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 13084 break; 13085 case Expr::MLV_IncompleteType: 13086 case Expr::MLV_IncompleteVoidType: 13087 return S.RequireCompleteType(Loc, E->getType(), 13088 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 13089 case Expr::MLV_DuplicateVectorComponents: 13090 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 13091 break; 13092 case Expr::MLV_NoSetterProperty: 13093 llvm_unreachable("readonly properties should be processed differently"); 13094 case Expr::MLV_InvalidMessageExpression: 13095 DiagID = diag::err_readonly_message_assignment; 13096 break; 13097 case Expr::MLV_SubObjCPropertySetting: 13098 DiagID = diag::err_no_subobject_property_setting; 13099 break; 13100 } 13101 13102 SourceRange Assign; 13103 if (Loc != OrigLoc) 13104 Assign = SourceRange(OrigLoc, OrigLoc); 13105 if (NeedType) 13106 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 13107 else 13108 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13109 return true; 13110 } 13111 13112 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 13113 SourceLocation Loc, 13114 Sema &Sema) { 13115 if (Sema.inTemplateInstantiation()) 13116 return; 13117 if (Sema.isUnevaluatedContext()) 13118 return; 13119 if (Loc.isInvalid() || Loc.isMacroID()) 13120 return; 13121 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 13122 return; 13123 13124 // C / C++ fields 13125 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 13126 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 13127 if (ML && MR) { 13128 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 13129 return; 13130 const ValueDecl *LHSDecl = 13131 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 13132 const ValueDecl *RHSDecl = 13133 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13134 if (LHSDecl != RHSDecl) 13135 return; 13136 if (LHSDecl->getType().isVolatileQualified()) 13137 return; 13138 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13139 if (RefTy->getPointeeType().isVolatileQualified()) 13140 return; 13141 13142 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13143 } 13144 13145 // Objective-C instance variables 13146 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13147 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13148 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13149 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13150 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13151 if (RL && RR && RL->getDecl() == RR->getDecl()) 13152 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13153 } 13154 } 13155 13156 // C99 6.5.16.1 13157 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13158 SourceLocation Loc, 13159 QualType CompoundType) { 13160 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13161 13162 // Verify that LHS is a modifiable lvalue, and emit error if not. 13163 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13164 return QualType(); 13165 13166 QualType LHSType = LHSExpr->getType(); 13167 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13168 CompoundType; 13169 // OpenCL v1.2 s6.1.1.1 p2: 13170 // The half data type can only be used to declare a pointer to a buffer that 13171 // contains half values 13172 if (getLangOpts().OpenCL && 13173 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13174 LHSType->isHalfType()) { 13175 Diag(Loc, diag::err_opencl_half_load_store) << 1 13176 << LHSType.getUnqualifiedType(); 13177 return QualType(); 13178 } 13179 13180 AssignConvertType ConvTy; 13181 if (CompoundType.isNull()) { 13182 Expr *RHSCheck = RHS.get(); 13183 13184 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13185 13186 QualType LHSTy(LHSType); 13187 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13188 if (RHS.isInvalid()) 13189 return QualType(); 13190 // Special case of NSObject attributes on c-style pointer types. 13191 if (ConvTy == IncompatiblePointer && 13192 ((Context.isObjCNSObjectType(LHSType) && 13193 RHSType->isObjCObjectPointerType()) || 13194 (Context.isObjCNSObjectType(RHSType) && 13195 LHSType->isObjCObjectPointerType()))) 13196 ConvTy = Compatible; 13197 13198 if (ConvTy == Compatible && 13199 LHSType->isObjCObjectType()) 13200 Diag(Loc, diag::err_objc_object_assignment) 13201 << LHSType; 13202 13203 // If the RHS is a unary plus or minus, check to see if they = and + are 13204 // right next to each other. If so, the user may have typo'd "x =+ 4" 13205 // instead of "x += 4". 13206 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13207 RHSCheck = ICE->getSubExpr(); 13208 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13209 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13210 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13211 // Only if the two operators are exactly adjacent. 13212 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13213 // And there is a space or other character before the subexpr of the 13214 // unary +/-. We don't want to warn on "x=-1". 13215 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13216 UO->getSubExpr()->getBeginLoc().isFileID()) { 13217 Diag(Loc, diag::warn_not_compound_assign) 13218 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13219 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13220 } 13221 } 13222 13223 if (ConvTy == Compatible) { 13224 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13225 // Warn about retain cycles where a block captures the LHS, but 13226 // not if the LHS is a simple variable into which the block is 13227 // being stored...unless that variable can be captured by reference! 13228 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13229 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13230 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13231 checkRetainCycles(LHSExpr, RHS.get()); 13232 } 13233 13234 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13235 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13236 // It is safe to assign a weak reference into a strong variable. 13237 // Although this code can still have problems: 13238 // id x = self.weakProp; 13239 // id y = self.weakProp; 13240 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13241 // paths through the function. This should be revisited if 13242 // -Wrepeated-use-of-weak is made flow-sensitive. 13243 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13244 // variable, which will be valid for the current autorelease scope. 13245 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13246 RHS.get()->getBeginLoc())) 13247 getCurFunction()->markSafeWeakUse(RHS.get()); 13248 13249 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13250 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13251 } 13252 } 13253 } else { 13254 // Compound assignment "x += y" 13255 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13256 } 13257 13258 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13259 RHS.get(), AA_Assigning)) 13260 return QualType(); 13261 13262 CheckForNullPointerDereference(*this, LHSExpr); 13263 13264 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13265 if (CompoundType.isNull()) { 13266 // C++2a [expr.ass]p5: 13267 // A simple-assignment whose left operand is of a volatile-qualified 13268 // type is deprecated unless the assignment is either a discarded-value 13269 // expression or an unevaluated operand 13270 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13271 } else { 13272 // C++2a [expr.ass]p6: 13273 // [Compound-assignment] expressions are deprecated if E1 has 13274 // volatile-qualified type 13275 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13276 } 13277 } 13278 13279 // C99 6.5.16p3: The type of an assignment expression is the type of the 13280 // left operand unless the left operand has qualified type, in which case 13281 // it is the unqualified version of the type of the left operand. 13282 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13283 // is converted to the type of the assignment expression (above). 13284 // C++ 5.17p1: the type of the assignment expression is that of its left 13285 // operand. 13286 return (getLangOpts().CPlusPlus 13287 ? LHSType : LHSType.getUnqualifiedType()); 13288 } 13289 13290 // Only ignore explicit casts to void. 13291 static bool IgnoreCommaOperand(const Expr *E) { 13292 E = E->IgnoreParens(); 13293 13294 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13295 if (CE->getCastKind() == CK_ToVoid) { 13296 return true; 13297 } 13298 13299 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13300 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13301 CE->getSubExpr()->getType()->isDependentType()) { 13302 return true; 13303 } 13304 } 13305 13306 return false; 13307 } 13308 13309 // Look for instances where it is likely the comma operator is confused with 13310 // another operator. There is an explicit list of acceptable expressions for 13311 // the left hand side of the comma operator, otherwise emit a warning. 13312 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13313 // No warnings in macros 13314 if (Loc.isMacroID()) 13315 return; 13316 13317 // Don't warn in template instantiations. 13318 if (inTemplateInstantiation()) 13319 return; 13320 13321 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13322 // instead, skip more than needed, then call back into here with the 13323 // CommaVisitor in SemaStmt.cpp. 13324 // The listed locations are the initialization and increment portions 13325 // of a for loop. The additional checks are on the condition of 13326 // if statements, do/while loops, and for loops. 13327 // Differences in scope flags for C89 mode requires the extra logic. 13328 const unsigned ForIncrementFlags = 13329 getLangOpts().C99 || getLangOpts().CPlusPlus 13330 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13331 : Scope::ContinueScope | Scope::BreakScope; 13332 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13333 const unsigned ScopeFlags = getCurScope()->getFlags(); 13334 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13335 (ScopeFlags & ForInitFlags) == ForInitFlags) 13336 return; 13337 13338 // If there are multiple comma operators used together, get the RHS of the 13339 // of the comma operator as the LHS. 13340 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13341 if (BO->getOpcode() != BO_Comma) 13342 break; 13343 LHS = BO->getRHS(); 13344 } 13345 13346 // Only allow some expressions on LHS to not warn. 13347 if (IgnoreCommaOperand(LHS)) 13348 return; 13349 13350 Diag(Loc, diag::warn_comma_operator); 13351 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13352 << LHS->getSourceRange() 13353 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13354 LangOpts.CPlusPlus ? "static_cast<void>(" 13355 : "(void)(") 13356 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13357 ")"); 13358 } 13359 13360 // C99 6.5.17 13361 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13362 SourceLocation Loc) { 13363 LHS = S.CheckPlaceholderExpr(LHS.get()); 13364 RHS = S.CheckPlaceholderExpr(RHS.get()); 13365 if (LHS.isInvalid() || RHS.isInvalid()) 13366 return QualType(); 13367 13368 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13369 // operands, but not unary promotions. 13370 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13371 13372 // So we treat the LHS as a ignored value, and in C++ we allow the 13373 // containing site to determine what should be done with the RHS. 13374 LHS = S.IgnoredValueConversions(LHS.get()); 13375 if (LHS.isInvalid()) 13376 return QualType(); 13377 13378 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand); 13379 13380 if (!S.getLangOpts().CPlusPlus) { 13381 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13382 if (RHS.isInvalid()) 13383 return QualType(); 13384 if (!RHS.get()->getType()->isVoidType()) 13385 S.RequireCompleteType(Loc, RHS.get()->getType(), 13386 diag::err_incomplete_type); 13387 } 13388 13389 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13390 S.DiagnoseCommaOperator(LHS.get(), Loc); 13391 13392 return RHS.get()->getType(); 13393 } 13394 13395 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13396 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13397 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13398 ExprValueKind &VK, 13399 ExprObjectKind &OK, 13400 SourceLocation OpLoc, 13401 bool IsInc, bool IsPrefix) { 13402 if (Op->isTypeDependent()) 13403 return S.Context.DependentTy; 13404 13405 QualType ResType = Op->getType(); 13406 // Atomic types can be used for increment / decrement where the non-atomic 13407 // versions can, so ignore the _Atomic() specifier for the purpose of 13408 // checking. 13409 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13410 ResType = ResAtomicType->getValueType(); 13411 13412 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13413 13414 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13415 // Decrement of bool is not allowed. 13416 if (!IsInc) { 13417 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13418 return QualType(); 13419 } 13420 // Increment of bool sets it to true, but is deprecated. 13421 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13422 : diag::warn_increment_bool) 13423 << Op->getSourceRange(); 13424 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13425 // Error on enum increments and decrements in C++ mode 13426 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13427 return QualType(); 13428 } else if (ResType->isRealType()) { 13429 // OK! 13430 } else if (ResType->isPointerType()) { 13431 // C99 6.5.2.4p2, 6.5.6p2 13432 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13433 return QualType(); 13434 } else if (ResType->isObjCObjectPointerType()) { 13435 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13436 // Otherwise, we just need a complete type. 13437 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13438 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13439 return QualType(); 13440 } else if (ResType->isAnyComplexType()) { 13441 // C99 does not support ++/-- on complex types, we allow as an extension. 13442 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13443 << ResType << Op->getSourceRange(); 13444 } else if (ResType->isPlaceholderType()) { 13445 ExprResult PR = S.CheckPlaceholderExpr(Op); 13446 if (PR.isInvalid()) return QualType(); 13447 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13448 IsInc, IsPrefix); 13449 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13450 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13451 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13452 (ResType->castAs<VectorType>()->getVectorKind() != 13453 VectorType::AltiVecBool)) { 13454 // The z vector extensions allow ++ and -- for non-bool vectors. 13455 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13456 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13457 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13458 } else { 13459 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13460 << ResType << int(IsInc) << Op->getSourceRange(); 13461 return QualType(); 13462 } 13463 // At this point, we know we have a real, complex or pointer type. 13464 // Now make sure the operand is a modifiable lvalue. 13465 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13466 return QualType(); 13467 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13468 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13469 // An operand with volatile-qualified type is deprecated 13470 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13471 << IsInc << ResType; 13472 } 13473 // In C++, a prefix increment is the same type as the operand. Otherwise 13474 // (in C or with postfix), the increment is the unqualified type of the 13475 // operand. 13476 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13477 VK = VK_LValue; 13478 OK = Op->getObjectKind(); 13479 return ResType; 13480 } else { 13481 VK = VK_PRValue; 13482 return ResType.getUnqualifiedType(); 13483 } 13484 } 13485 13486 13487 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13488 /// This routine allows us to typecheck complex/recursive expressions 13489 /// where the declaration is needed for type checking. We only need to 13490 /// handle cases when the expression references a function designator 13491 /// or is an lvalue. Here are some examples: 13492 /// - &(x) => x 13493 /// - &*****f => f for f a function designator. 13494 /// - &s.xx => s 13495 /// - &s.zz[1].yy -> s, if zz is an array 13496 /// - *(x + 1) -> x, if x is an array 13497 /// - &"123"[2] -> 0 13498 /// - & __real__ x -> x 13499 /// 13500 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13501 /// members. 13502 static ValueDecl *getPrimaryDecl(Expr *E) { 13503 switch (E->getStmtClass()) { 13504 case Stmt::DeclRefExprClass: 13505 return cast<DeclRefExpr>(E)->getDecl(); 13506 case Stmt::MemberExprClass: 13507 // If this is an arrow operator, the address is an offset from 13508 // the base's value, so the object the base refers to is 13509 // irrelevant. 13510 if (cast<MemberExpr>(E)->isArrow()) 13511 return nullptr; 13512 // Otherwise, the expression refers to a part of the base 13513 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13514 case Stmt::ArraySubscriptExprClass: { 13515 // FIXME: This code shouldn't be necessary! We should catch the implicit 13516 // promotion of register arrays earlier. 13517 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13518 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13519 if (ICE->getSubExpr()->getType()->isArrayType()) 13520 return getPrimaryDecl(ICE->getSubExpr()); 13521 } 13522 return nullptr; 13523 } 13524 case Stmt::UnaryOperatorClass: { 13525 UnaryOperator *UO = cast<UnaryOperator>(E); 13526 13527 switch(UO->getOpcode()) { 13528 case UO_Real: 13529 case UO_Imag: 13530 case UO_Extension: 13531 return getPrimaryDecl(UO->getSubExpr()); 13532 default: 13533 return nullptr; 13534 } 13535 } 13536 case Stmt::ParenExprClass: 13537 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13538 case Stmt::ImplicitCastExprClass: 13539 // If the result of an implicit cast is an l-value, we care about 13540 // the sub-expression; otherwise, the result here doesn't matter. 13541 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13542 case Stmt::CXXUuidofExprClass: 13543 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13544 default: 13545 return nullptr; 13546 } 13547 } 13548 13549 namespace { 13550 enum { 13551 AO_Bit_Field = 0, 13552 AO_Vector_Element = 1, 13553 AO_Property_Expansion = 2, 13554 AO_Register_Variable = 3, 13555 AO_Matrix_Element = 4, 13556 AO_No_Error = 5 13557 }; 13558 } 13559 /// Diagnose invalid operand for address of operations. 13560 /// 13561 /// \param Type The type of operand which cannot have its address taken. 13562 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13563 Expr *E, unsigned Type) { 13564 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13565 } 13566 13567 /// CheckAddressOfOperand - The operand of & must be either a function 13568 /// designator or an lvalue designating an object. If it is an lvalue, the 13569 /// object cannot be declared with storage class register or be a bit field. 13570 /// Note: The usual conversions are *not* applied to the operand of the & 13571 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13572 /// In C++, the operand might be an overloaded function name, in which case 13573 /// we allow the '&' but retain the overloaded-function type. 13574 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13575 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13576 if (PTy->getKind() == BuiltinType::Overload) { 13577 Expr *E = OrigOp.get()->IgnoreParens(); 13578 if (!isa<OverloadExpr>(E)) { 13579 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13580 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13581 << OrigOp.get()->getSourceRange(); 13582 return QualType(); 13583 } 13584 13585 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13586 if (isa<UnresolvedMemberExpr>(Ovl)) 13587 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13588 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13589 << OrigOp.get()->getSourceRange(); 13590 return QualType(); 13591 } 13592 13593 return Context.OverloadTy; 13594 } 13595 13596 if (PTy->getKind() == BuiltinType::UnknownAny) 13597 return Context.UnknownAnyTy; 13598 13599 if (PTy->getKind() == BuiltinType::BoundMember) { 13600 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13601 << OrigOp.get()->getSourceRange(); 13602 return QualType(); 13603 } 13604 13605 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13606 if (OrigOp.isInvalid()) return QualType(); 13607 } 13608 13609 if (OrigOp.get()->isTypeDependent()) 13610 return Context.DependentTy; 13611 13612 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13613 13614 // Make sure to ignore parentheses in subsequent checks 13615 Expr *op = OrigOp.get()->IgnoreParens(); 13616 13617 // In OpenCL captures for blocks called as lambda functions 13618 // are located in the private address space. Blocks used in 13619 // enqueue_kernel can be located in a different address space 13620 // depending on a vendor implementation. Thus preventing 13621 // taking an address of the capture to avoid invalid AS casts. 13622 if (LangOpts.OpenCL) { 13623 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13624 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13625 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13626 return QualType(); 13627 } 13628 } 13629 13630 if (getLangOpts().C99) { 13631 // Implement C99-only parts of addressof rules. 13632 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13633 if (uOp->getOpcode() == UO_Deref) 13634 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13635 // (assuming the deref expression is valid). 13636 return uOp->getSubExpr()->getType(); 13637 } 13638 // Technically, there should be a check for array subscript 13639 // expressions here, but the result of one is always an lvalue anyway. 13640 } 13641 ValueDecl *dcl = getPrimaryDecl(op); 13642 13643 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13644 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13645 op->getBeginLoc())) 13646 return QualType(); 13647 13648 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13649 unsigned AddressOfError = AO_No_Error; 13650 13651 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13652 bool sfinae = (bool)isSFINAEContext(); 13653 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13654 : diag::ext_typecheck_addrof_temporary) 13655 << op->getType() << op->getSourceRange(); 13656 if (sfinae) 13657 return QualType(); 13658 // Materialize the temporary as an lvalue so that we can take its address. 13659 OrigOp = op = 13660 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13661 } else if (isa<ObjCSelectorExpr>(op)) { 13662 return Context.getPointerType(op->getType()); 13663 } else if (lval == Expr::LV_MemberFunction) { 13664 // If it's an instance method, make a member pointer. 13665 // The expression must have exactly the form &A::foo. 13666 13667 // If the underlying expression isn't a decl ref, give up. 13668 if (!isa<DeclRefExpr>(op)) { 13669 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13670 << OrigOp.get()->getSourceRange(); 13671 return QualType(); 13672 } 13673 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13674 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13675 13676 // The id-expression was parenthesized. 13677 if (OrigOp.get() != DRE) { 13678 Diag(OpLoc, diag::err_parens_pointer_member_function) 13679 << OrigOp.get()->getSourceRange(); 13680 13681 // The method was named without a qualifier. 13682 } else if (!DRE->getQualifier()) { 13683 if (MD->getParent()->getName().empty()) 13684 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13685 << op->getSourceRange(); 13686 else { 13687 SmallString<32> Str; 13688 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13689 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13690 << op->getSourceRange() 13691 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13692 } 13693 } 13694 13695 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13696 if (isa<CXXDestructorDecl>(MD)) 13697 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13698 13699 QualType MPTy = Context.getMemberPointerType( 13700 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13701 // Under the MS ABI, lock down the inheritance model now. 13702 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13703 (void)isCompleteType(OpLoc, MPTy); 13704 return MPTy; 13705 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13706 // C99 6.5.3.2p1 13707 // The operand must be either an l-value or a function designator 13708 if (!op->getType()->isFunctionType()) { 13709 // Use a special diagnostic for loads from property references. 13710 if (isa<PseudoObjectExpr>(op)) { 13711 AddressOfError = AO_Property_Expansion; 13712 } else { 13713 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13714 << op->getType() << op->getSourceRange(); 13715 return QualType(); 13716 } 13717 } 13718 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13719 // The operand cannot be a bit-field 13720 AddressOfError = AO_Bit_Field; 13721 } else if (op->getObjectKind() == OK_VectorComponent) { 13722 // The operand cannot be an element of a vector 13723 AddressOfError = AO_Vector_Element; 13724 } else if (op->getObjectKind() == OK_MatrixComponent) { 13725 // The operand cannot be an element of a matrix. 13726 AddressOfError = AO_Matrix_Element; 13727 } else if (dcl) { // C99 6.5.3.2p1 13728 // We have an lvalue with a decl. Make sure the decl is not declared 13729 // with the register storage-class specifier. 13730 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13731 // in C++ it is not error to take address of a register 13732 // variable (c++03 7.1.1P3) 13733 if (vd->getStorageClass() == SC_Register && 13734 !getLangOpts().CPlusPlus) { 13735 AddressOfError = AO_Register_Variable; 13736 } 13737 } else if (isa<MSPropertyDecl>(dcl)) { 13738 AddressOfError = AO_Property_Expansion; 13739 } else if (isa<FunctionTemplateDecl>(dcl)) { 13740 return Context.OverloadTy; 13741 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13742 // Okay: we can take the address of a field. 13743 // Could be a pointer to member, though, if there is an explicit 13744 // scope qualifier for the class. 13745 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13746 DeclContext *Ctx = dcl->getDeclContext(); 13747 if (Ctx && Ctx->isRecord()) { 13748 if (dcl->getType()->isReferenceType()) { 13749 Diag(OpLoc, 13750 diag::err_cannot_form_pointer_to_member_of_reference_type) 13751 << dcl->getDeclName() << dcl->getType(); 13752 return QualType(); 13753 } 13754 13755 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13756 Ctx = Ctx->getParent(); 13757 13758 QualType MPTy = Context.getMemberPointerType( 13759 op->getType(), 13760 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13761 // Under the MS ABI, lock down the inheritance model now. 13762 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13763 (void)isCompleteType(OpLoc, MPTy); 13764 return MPTy; 13765 } 13766 } 13767 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13768 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13769 llvm_unreachable("Unknown/unexpected decl type"); 13770 } 13771 13772 if (AddressOfError != AO_No_Error) { 13773 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13774 return QualType(); 13775 } 13776 13777 if (lval == Expr::LV_IncompleteVoidType) { 13778 // Taking the address of a void variable is technically illegal, but we 13779 // allow it in cases which are otherwise valid. 13780 // Example: "extern void x; void* y = &x;". 13781 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13782 } 13783 13784 // If the operand has type "type", the result has type "pointer to type". 13785 if (op->getType()->isObjCObjectType()) 13786 return Context.getObjCObjectPointerType(op->getType()); 13787 13788 CheckAddressOfPackedMember(op); 13789 13790 return Context.getPointerType(op->getType()); 13791 } 13792 13793 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13794 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13795 if (!DRE) 13796 return; 13797 const Decl *D = DRE->getDecl(); 13798 if (!D) 13799 return; 13800 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13801 if (!Param) 13802 return; 13803 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13804 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13805 return; 13806 if (FunctionScopeInfo *FD = S.getCurFunction()) 13807 if (!FD->ModifiedNonNullParams.count(Param)) 13808 FD->ModifiedNonNullParams.insert(Param); 13809 } 13810 13811 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13812 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13813 SourceLocation OpLoc) { 13814 if (Op->isTypeDependent()) 13815 return S.Context.DependentTy; 13816 13817 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13818 if (ConvResult.isInvalid()) 13819 return QualType(); 13820 Op = ConvResult.get(); 13821 QualType OpTy = Op->getType(); 13822 QualType Result; 13823 13824 if (isa<CXXReinterpretCastExpr>(Op)) { 13825 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13826 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13827 Op->getSourceRange()); 13828 } 13829 13830 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13831 { 13832 Result = PT->getPointeeType(); 13833 } 13834 else if (const ObjCObjectPointerType *OPT = 13835 OpTy->getAs<ObjCObjectPointerType>()) 13836 Result = OPT->getPointeeType(); 13837 else { 13838 ExprResult PR = S.CheckPlaceholderExpr(Op); 13839 if (PR.isInvalid()) return QualType(); 13840 if (PR.get() != Op) 13841 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13842 } 13843 13844 if (Result.isNull()) { 13845 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13846 << OpTy << Op->getSourceRange(); 13847 return QualType(); 13848 } 13849 13850 // Note that per both C89 and C99, indirection is always legal, even if Result 13851 // is an incomplete type or void. It would be possible to warn about 13852 // dereferencing a void pointer, but it's completely well-defined, and such a 13853 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13854 // for pointers to 'void' but is fine for any other pointer type: 13855 // 13856 // C++ [expr.unary.op]p1: 13857 // [...] the expression to which [the unary * operator] is applied shall 13858 // be a pointer to an object type, or a pointer to a function type 13859 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13860 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13861 << OpTy << Op->getSourceRange(); 13862 13863 // Dereferences are usually l-values... 13864 VK = VK_LValue; 13865 13866 // ...except that certain expressions are never l-values in C. 13867 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13868 VK = VK_PRValue; 13869 13870 return Result; 13871 } 13872 13873 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13874 BinaryOperatorKind Opc; 13875 switch (Kind) { 13876 default: llvm_unreachable("Unknown binop!"); 13877 case tok::periodstar: Opc = BO_PtrMemD; break; 13878 case tok::arrowstar: Opc = BO_PtrMemI; break; 13879 case tok::star: Opc = BO_Mul; break; 13880 case tok::slash: Opc = BO_Div; break; 13881 case tok::percent: Opc = BO_Rem; break; 13882 case tok::plus: Opc = BO_Add; break; 13883 case tok::minus: Opc = BO_Sub; break; 13884 case tok::lessless: Opc = BO_Shl; break; 13885 case tok::greatergreater: Opc = BO_Shr; break; 13886 case tok::lessequal: Opc = BO_LE; break; 13887 case tok::less: Opc = BO_LT; break; 13888 case tok::greaterequal: Opc = BO_GE; break; 13889 case tok::greater: Opc = BO_GT; break; 13890 case tok::exclaimequal: Opc = BO_NE; break; 13891 case tok::equalequal: Opc = BO_EQ; break; 13892 case tok::spaceship: Opc = BO_Cmp; break; 13893 case tok::amp: Opc = BO_And; break; 13894 case tok::caret: Opc = BO_Xor; break; 13895 case tok::pipe: Opc = BO_Or; break; 13896 case tok::ampamp: Opc = BO_LAnd; break; 13897 case tok::pipepipe: Opc = BO_LOr; break; 13898 case tok::equal: Opc = BO_Assign; break; 13899 case tok::starequal: Opc = BO_MulAssign; break; 13900 case tok::slashequal: Opc = BO_DivAssign; break; 13901 case tok::percentequal: Opc = BO_RemAssign; break; 13902 case tok::plusequal: Opc = BO_AddAssign; break; 13903 case tok::minusequal: Opc = BO_SubAssign; break; 13904 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13905 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13906 case tok::ampequal: Opc = BO_AndAssign; break; 13907 case tok::caretequal: Opc = BO_XorAssign; break; 13908 case tok::pipeequal: Opc = BO_OrAssign; break; 13909 case tok::comma: Opc = BO_Comma; break; 13910 } 13911 return Opc; 13912 } 13913 13914 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13915 tok::TokenKind Kind) { 13916 UnaryOperatorKind Opc; 13917 switch (Kind) { 13918 default: llvm_unreachable("Unknown unary op!"); 13919 case tok::plusplus: Opc = UO_PreInc; break; 13920 case tok::minusminus: Opc = UO_PreDec; break; 13921 case tok::amp: Opc = UO_AddrOf; break; 13922 case tok::star: Opc = UO_Deref; break; 13923 case tok::plus: Opc = UO_Plus; break; 13924 case tok::minus: Opc = UO_Minus; break; 13925 case tok::tilde: Opc = UO_Not; break; 13926 case tok::exclaim: Opc = UO_LNot; break; 13927 case tok::kw___real: Opc = UO_Real; break; 13928 case tok::kw___imag: Opc = UO_Imag; break; 13929 case tok::kw___extension__: Opc = UO_Extension; break; 13930 } 13931 return Opc; 13932 } 13933 13934 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13935 /// This warning suppressed in the event of macro expansions. 13936 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13937 SourceLocation OpLoc, bool IsBuiltin) { 13938 if (S.inTemplateInstantiation()) 13939 return; 13940 if (S.isUnevaluatedContext()) 13941 return; 13942 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13943 return; 13944 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13945 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13946 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13947 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13948 if (!LHSDeclRef || !RHSDeclRef || 13949 LHSDeclRef->getLocation().isMacroID() || 13950 RHSDeclRef->getLocation().isMacroID()) 13951 return; 13952 const ValueDecl *LHSDecl = 13953 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13954 const ValueDecl *RHSDecl = 13955 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13956 if (LHSDecl != RHSDecl) 13957 return; 13958 if (LHSDecl->getType().isVolatileQualified()) 13959 return; 13960 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13961 if (RefTy->getPointeeType().isVolatileQualified()) 13962 return; 13963 13964 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13965 : diag::warn_self_assignment_overloaded) 13966 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13967 << RHSExpr->getSourceRange(); 13968 } 13969 13970 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13971 /// is usually indicative of introspection within the Objective-C pointer. 13972 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13973 SourceLocation OpLoc) { 13974 if (!S.getLangOpts().ObjC) 13975 return; 13976 13977 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13978 const Expr *LHS = L.get(); 13979 const Expr *RHS = R.get(); 13980 13981 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13982 ObjCPointerExpr = LHS; 13983 OtherExpr = RHS; 13984 } 13985 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13986 ObjCPointerExpr = RHS; 13987 OtherExpr = LHS; 13988 } 13989 13990 // This warning is deliberately made very specific to reduce false 13991 // positives with logic that uses '&' for hashing. This logic mainly 13992 // looks for code trying to introspect into tagged pointers, which 13993 // code should generally never do. 13994 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13995 unsigned Diag = diag::warn_objc_pointer_masking; 13996 // Determine if we are introspecting the result of performSelectorXXX. 13997 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13998 // Special case messages to -performSelector and friends, which 13999 // can return non-pointer values boxed in a pointer value. 14000 // Some clients may wish to silence warnings in this subcase. 14001 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 14002 Selector S = ME->getSelector(); 14003 StringRef SelArg0 = S.getNameForSlot(0); 14004 if (SelArg0.startswith("performSelector")) 14005 Diag = diag::warn_objc_pointer_masking_performSelector; 14006 } 14007 14008 S.Diag(OpLoc, Diag) 14009 << ObjCPointerExpr->getSourceRange(); 14010 } 14011 } 14012 14013 static NamedDecl *getDeclFromExpr(Expr *E) { 14014 if (!E) 14015 return nullptr; 14016 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 14017 return DRE->getDecl(); 14018 if (auto *ME = dyn_cast<MemberExpr>(E)) 14019 return ME->getMemberDecl(); 14020 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 14021 return IRE->getDecl(); 14022 return nullptr; 14023 } 14024 14025 // This helper function promotes a binary operator's operands (which are of a 14026 // half vector type) to a vector of floats and then truncates the result to 14027 // a vector of either half or short. 14028 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 14029 BinaryOperatorKind Opc, QualType ResultTy, 14030 ExprValueKind VK, ExprObjectKind OK, 14031 bool IsCompAssign, SourceLocation OpLoc, 14032 FPOptionsOverride FPFeatures) { 14033 auto &Context = S.getASTContext(); 14034 assert((isVector(ResultTy, Context.HalfTy) || 14035 isVector(ResultTy, Context.ShortTy)) && 14036 "Result must be a vector of half or short"); 14037 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 14038 isVector(RHS.get()->getType(), Context.HalfTy) && 14039 "both operands expected to be a half vector"); 14040 14041 RHS = convertVector(RHS.get(), Context.FloatTy, S); 14042 QualType BinOpResTy = RHS.get()->getType(); 14043 14044 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 14045 // change BinOpResTy to a vector of ints. 14046 if (isVector(ResultTy, Context.ShortTy)) 14047 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 14048 14049 if (IsCompAssign) 14050 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14051 ResultTy, VK, OK, OpLoc, FPFeatures, 14052 BinOpResTy, BinOpResTy); 14053 14054 LHS = convertVector(LHS.get(), Context.FloatTy, S); 14055 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14056 BinOpResTy, VK, OK, OpLoc, FPFeatures); 14057 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 14058 } 14059 14060 static std::pair<ExprResult, ExprResult> 14061 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 14062 Expr *RHSExpr) { 14063 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14064 if (!S.Context.isDependenceAllowed()) { 14065 // C cannot handle TypoExpr nodes on either side of a binop because it 14066 // doesn't handle dependent types properly, so make sure any TypoExprs have 14067 // been dealt with before checking the operands. 14068 LHS = S.CorrectDelayedTyposInExpr(LHS); 14069 RHS = S.CorrectDelayedTyposInExpr( 14070 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 14071 [Opc, LHS](Expr *E) { 14072 if (Opc != BO_Assign) 14073 return ExprResult(E); 14074 // Avoid correcting the RHS to the same Expr as the LHS. 14075 Decl *D = getDeclFromExpr(E); 14076 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 14077 }); 14078 } 14079 return std::make_pair(LHS, RHS); 14080 } 14081 14082 /// Returns true if conversion between vectors of halfs and vectors of floats 14083 /// is needed. 14084 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 14085 Expr *E0, Expr *E1 = nullptr) { 14086 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 14087 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 14088 return false; 14089 14090 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 14091 QualType Ty = E->IgnoreImplicit()->getType(); 14092 14093 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 14094 // to vectors of floats. Although the element type of the vectors is __fp16, 14095 // the vectors shouldn't be treated as storage-only types. See the 14096 // discussion here: https://reviews.llvm.org/rG825235c140e7 14097 if (const VectorType *VT = Ty->getAs<VectorType>()) { 14098 if (VT->getVectorKind() == VectorType::NeonVector) 14099 return false; 14100 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 14101 } 14102 return false; 14103 }; 14104 14105 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 14106 } 14107 14108 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 14109 /// operator @p Opc at location @c TokLoc. This routine only supports 14110 /// built-in operations; ActOnBinOp handles overloaded operators. 14111 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 14112 BinaryOperatorKind Opc, 14113 Expr *LHSExpr, Expr *RHSExpr) { 14114 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 14115 // The syntax only allows initializer lists on the RHS of assignment, 14116 // so we don't need to worry about accepting invalid code for 14117 // non-assignment operators. 14118 // C++11 5.17p9: 14119 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 14120 // of x = {} is x = T(). 14121 InitializationKind Kind = InitializationKind::CreateDirectList( 14122 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14123 InitializedEntity Entity = 14124 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 14125 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 14126 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 14127 if (Init.isInvalid()) 14128 return Init; 14129 RHSExpr = Init.get(); 14130 } 14131 14132 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14133 QualType ResultTy; // Result type of the binary operator. 14134 // The following two variables are used for compound assignment operators 14135 QualType CompLHSTy; // Type of LHS after promotions for computation 14136 QualType CompResultTy; // Type of computation result 14137 ExprValueKind VK = VK_PRValue; 14138 ExprObjectKind OK = OK_Ordinary; 14139 bool ConvertHalfVec = false; 14140 14141 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14142 if (!LHS.isUsable() || !RHS.isUsable()) 14143 return ExprError(); 14144 14145 if (getLangOpts().OpenCL) { 14146 QualType LHSTy = LHSExpr->getType(); 14147 QualType RHSTy = RHSExpr->getType(); 14148 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14149 // the ATOMIC_VAR_INIT macro. 14150 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14151 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14152 if (BO_Assign == Opc) 14153 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14154 else 14155 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14156 return ExprError(); 14157 } 14158 14159 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14160 // only with a builtin functions and therefore should be disallowed here. 14161 if (LHSTy->isImageType() || RHSTy->isImageType() || 14162 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14163 LHSTy->isPipeType() || RHSTy->isPipeType() || 14164 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14165 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14166 return ExprError(); 14167 } 14168 } 14169 14170 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14171 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14172 14173 switch (Opc) { 14174 case BO_Assign: 14175 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14176 if (getLangOpts().CPlusPlus && 14177 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14178 VK = LHS.get()->getValueKind(); 14179 OK = LHS.get()->getObjectKind(); 14180 } 14181 if (!ResultTy.isNull()) { 14182 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14183 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14184 14185 // Avoid copying a block to the heap if the block is assigned to a local 14186 // auto variable that is declared in the same scope as the block. This 14187 // optimization is unsafe if the local variable is declared in an outer 14188 // scope. For example: 14189 // 14190 // BlockTy b; 14191 // { 14192 // b = ^{...}; 14193 // } 14194 // // It is unsafe to invoke the block here if it wasn't copied to the 14195 // // heap. 14196 // b(); 14197 14198 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14199 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14200 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14201 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14202 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14203 14204 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14205 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14206 NTCUC_Assignment, NTCUK_Copy); 14207 } 14208 RecordModifiableNonNullParam(*this, LHS.get()); 14209 break; 14210 case BO_PtrMemD: 14211 case BO_PtrMemI: 14212 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14213 Opc == BO_PtrMemI); 14214 break; 14215 case BO_Mul: 14216 case BO_Div: 14217 ConvertHalfVec = true; 14218 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14219 Opc == BO_Div); 14220 break; 14221 case BO_Rem: 14222 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14223 break; 14224 case BO_Add: 14225 ConvertHalfVec = true; 14226 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14227 break; 14228 case BO_Sub: 14229 ConvertHalfVec = true; 14230 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14231 break; 14232 case BO_Shl: 14233 case BO_Shr: 14234 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14235 break; 14236 case BO_LE: 14237 case BO_LT: 14238 case BO_GE: 14239 case BO_GT: 14240 ConvertHalfVec = true; 14241 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14242 break; 14243 case BO_EQ: 14244 case BO_NE: 14245 ConvertHalfVec = true; 14246 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14247 break; 14248 case BO_Cmp: 14249 ConvertHalfVec = true; 14250 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14251 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14252 break; 14253 case BO_And: 14254 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14255 LLVM_FALLTHROUGH; 14256 case BO_Xor: 14257 case BO_Or: 14258 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14259 break; 14260 case BO_LAnd: 14261 case BO_LOr: 14262 ConvertHalfVec = true; 14263 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14264 break; 14265 case BO_MulAssign: 14266 case BO_DivAssign: 14267 ConvertHalfVec = true; 14268 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14269 Opc == BO_DivAssign); 14270 CompLHSTy = CompResultTy; 14271 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14272 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14273 break; 14274 case BO_RemAssign: 14275 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14276 CompLHSTy = CompResultTy; 14277 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14278 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14279 break; 14280 case BO_AddAssign: 14281 ConvertHalfVec = true; 14282 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14283 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14284 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14285 break; 14286 case BO_SubAssign: 14287 ConvertHalfVec = true; 14288 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14289 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14290 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14291 break; 14292 case BO_ShlAssign: 14293 case BO_ShrAssign: 14294 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14295 CompLHSTy = CompResultTy; 14296 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14297 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14298 break; 14299 case BO_AndAssign: 14300 case BO_OrAssign: // fallthrough 14301 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14302 LLVM_FALLTHROUGH; 14303 case BO_XorAssign: 14304 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14305 CompLHSTy = CompResultTy; 14306 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14307 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14308 break; 14309 case BO_Comma: 14310 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14311 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14312 VK = RHS.get()->getValueKind(); 14313 OK = RHS.get()->getObjectKind(); 14314 } 14315 break; 14316 } 14317 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14318 return ExprError(); 14319 14320 // Some of the binary operations require promoting operands of half vector to 14321 // float vectors and truncating the result back to half vector. For now, we do 14322 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14323 // arm64). 14324 assert( 14325 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14326 isVector(LHS.get()->getType(), Context.HalfTy)) && 14327 "both sides are half vectors or neither sides are"); 14328 ConvertHalfVec = 14329 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14330 14331 // Check for array bounds violations for both sides of the BinaryOperator 14332 CheckArrayAccess(LHS.get()); 14333 CheckArrayAccess(RHS.get()); 14334 14335 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14336 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14337 &Context.Idents.get("object_setClass"), 14338 SourceLocation(), LookupOrdinaryName); 14339 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14340 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14341 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14342 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14343 "object_setClass(") 14344 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14345 ",") 14346 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14347 } 14348 else 14349 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14350 } 14351 else if (const ObjCIvarRefExpr *OIRE = 14352 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14353 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14354 14355 // Opc is not a compound assignment if CompResultTy is null. 14356 if (CompResultTy.isNull()) { 14357 if (ConvertHalfVec) 14358 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14359 OpLoc, CurFPFeatureOverrides()); 14360 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14361 VK, OK, OpLoc, CurFPFeatureOverrides()); 14362 } 14363 14364 // Handle compound assignments. 14365 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14366 OK_ObjCProperty) { 14367 VK = VK_LValue; 14368 OK = LHS.get()->getObjectKind(); 14369 } 14370 14371 // The LHS is not converted to the result type for fixed-point compound 14372 // assignment as the common type is computed on demand. Reset the CompLHSTy 14373 // to the LHS type we would have gotten after unary conversions. 14374 if (CompResultTy->isFixedPointType()) 14375 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14376 14377 if (ConvertHalfVec) 14378 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14379 OpLoc, CurFPFeatureOverrides()); 14380 14381 return CompoundAssignOperator::Create( 14382 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14383 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14384 } 14385 14386 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14387 /// operators are mixed in a way that suggests that the programmer forgot that 14388 /// comparison operators have higher precedence. The most typical example of 14389 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14390 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14391 SourceLocation OpLoc, Expr *LHSExpr, 14392 Expr *RHSExpr) { 14393 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14394 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14395 14396 // Check that one of the sides is a comparison operator and the other isn't. 14397 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14398 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14399 if (isLeftComp == isRightComp) 14400 return; 14401 14402 // Bitwise operations are sometimes used as eager logical ops. 14403 // Don't diagnose this. 14404 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14405 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14406 if (isLeftBitwise || isRightBitwise) 14407 return; 14408 14409 SourceRange DiagRange = isLeftComp 14410 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14411 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14412 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14413 SourceRange ParensRange = 14414 isLeftComp 14415 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14416 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14417 14418 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14419 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14420 SuggestParentheses(Self, OpLoc, 14421 Self.PDiag(diag::note_precedence_silence) << OpStr, 14422 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14423 SuggestParentheses(Self, OpLoc, 14424 Self.PDiag(diag::note_precedence_bitwise_first) 14425 << BinaryOperator::getOpcodeStr(Opc), 14426 ParensRange); 14427 } 14428 14429 /// It accepts a '&&' expr that is inside a '||' one. 14430 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14431 /// in parentheses. 14432 static void 14433 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14434 BinaryOperator *Bop) { 14435 assert(Bop->getOpcode() == BO_LAnd); 14436 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14437 << Bop->getSourceRange() << OpLoc; 14438 SuggestParentheses(Self, Bop->getOperatorLoc(), 14439 Self.PDiag(diag::note_precedence_silence) 14440 << Bop->getOpcodeStr(), 14441 Bop->getSourceRange()); 14442 } 14443 14444 /// Returns true if the given expression can be evaluated as a constant 14445 /// 'true'. 14446 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14447 bool Res; 14448 return !E->isValueDependent() && 14449 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14450 } 14451 14452 /// Returns true if the given expression can be evaluated as a constant 14453 /// 'false'. 14454 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14455 bool Res; 14456 return !E->isValueDependent() && 14457 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14458 } 14459 14460 /// Look for '&&' in the left hand of a '||' expr. 14461 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14462 Expr *LHSExpr, Expr *RHSExpr) { 14463 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14464 if (Bop->getOpcode() == BO_LAnd) { 14465 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14466 if (EvaluatesAsFalse(S, RHSExpr)) 14467 return; 14468 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14469 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14470 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14471 } else if (Bop->getOpcode() == BO_LOr) { 14472 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14473 // If it's "a || b && 1 || c" we didn't warn earlier for 14474 // "a || b && 1", but warn now. 14475 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14476 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14477 } 14478 } 14479 } 14480 } 14481 14482 /// Look for '&&' in the right hand of a '||' expr. 14483 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14484 Expr *LHSExpr, Expr *RHSExpr) { 14485 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14486 if (Bop->getOpcode() == BO_LAnd) { 14487 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14488 if (EvaluatesAsFalse(S, LHSExpr)) 14489 return; 14490 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14491 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14492 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14493 } 14494 } 14495 } 14496 14497 /// Look for bitwise op in the left or right hand of a bitwise op with 14498 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14499 /// the '&' expression in parentheses. 14500 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14501 SourceLocation OpLoc, Expr *SubExpr) { 14502 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14503 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14504 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14505 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14506 << Bop->getSourceRange() << OpLoc; 14507 SuggestParentheses(S, Bop->getOperatorLoc(), 14508 S.PDiag(diag::note_precedence_silence) 14509 << Bop->getOpcodeStr(), 14510 Bop->getSourceRange()); 14511 } 14512 } 14513 } 14514 14515 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14516 Expr *SubExpr, StringRef Shift) { 14517 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14518 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14519 StringRef Op = Bop->getOpcodeStr(); 14520 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14521 << Bop->getSourceRange() << OpLoc << Shift << Op; 14522 SuggestParentheses(S, Bop->getOperatorLoc(), 14523 S.PDiag(diag::note_precedence_silence) << Op, 14524 Bop->getSourceRange()); 14525 } 14526 } 14527 } 14528 14529 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14530 Expr *LHSExpr, Expr *RHSExpr) { 14531 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14532 if (!OCE) 14533 return; 14534 14535 FunctionDecl *FD = OCE->getDirectCallee(); 14536 if (!FD || !FD->isOverloadedOperator()) 14537 return; 14538 14539 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14540 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14541 return; 14542 14543 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14544 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14545 << (Kind == OO_LessLess); 14546 SuggestParentheses(S, OCE->getOperatorLoc(), 14547 S.PDiag(diag::note_precedence_silence) 14548 << (Kind == OO_LessLess ? "<<" : ">>"), 14549 OCE->getSourceRange()); 14550 SuggestParentheses( 14551 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14552 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14553 } 14554 14555 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14556 /// precedence. 14557 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14558 SourceLocation OpLoc, Expr *LHSExpr, 14559 Expr *RHSExpr){ 14560 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14561 if (BinaryOperator::isBitwiseOp(Opc)) 14562 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14563 14564 // Diagnose "arg1 & arg2 | arg3" 14565 if ((Opc == BO_Or || Opc == BO_Xor) && 14566 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14567 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14568 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14569 } 14570 14571 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14572 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14573 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14574 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14575 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14576 } 14577 14578 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14579 || Opc == BO_Shr) { 14580 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14581 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14582 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14583 } 14584 14585 // Warn on overloaded shift operators and comparisons, such as: 14586 // cout << 5 == 4; 14587 if (BinaryOperator::isComparisonOp(Opc)) 14588 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14589 } 14590 14591 // Binary Operators. 'Tok' is the token for the operator. 14592 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14593 tok::TokenKind Kind, 14594 Expr *LHSExpr, Expr *RHSExpr) { 14595 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14596 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14597 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14598 14599 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14600 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14601 14602 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14603 } 14604 14605 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14606 UnresolvedSetImpl &Functions) { 14607 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14608 if (OverOp != OO_None && OverOp != OO_Equal) 14609 LookupOverloadedOperatorName(OverOp, S, Functions); 14610 14611 // In C++20 onwards, we may have a second operator to look up. 14612 if (getLangOpts().CPlusPlus20) { 14613 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14614 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14615 } 14616 } 14617 14618 /// Build an overloaded binary operator expression in the given scope. 14619 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14620 BinaryOperatorKind Opc, 14621 Expr *LHS, Expr *RHS) { 14622 switch (Opc) { 14623 case BO_Assign: 14624 case BO_DivAssign: 14625 case BO_RemAssign: 14626 case BO_SubAssign: 14627 case BO_AndAssign: 14628 case BO_OrAssign: 14629 case BO_XorAssign: 14630 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14631 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14632 break; 14633 default: 14634 break; 14635 } 14636 14637 // Find all of the overloaded operators visible from this point. 14638 UnresolvedSet<16> Functions; 14639 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14640 14641 // Build the (potentially-overloaded, potentially-dependent) 14642 // binary operation. 14643 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14644 } 14645 14646 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14647 BinaryOperatorKind Opc, 14648 Expr *LHSExpr, Expr *RHSExpr) { 14649 ExprResult LHS, RHS; 14650 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14651 if (!LHS.isUsable() || !RHS.isUsable()) 14652 return ExprError(); 14653 LHSExpr = LHS.get(); 14654 RHSExpr = RHS.get(); 14655 14656 // We want to end up calling one of checkPseudoObjectAssignment 14657 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14658 // both expressions are overloadable or either is type-dependent), 14659 // or CreateBuiltinBinOp (in any other case). We also want to get 14660 // any placeholder types out of the way. 14661 14662 // Handle pseudo-objects in the LHS. 14663 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14664 // Assignments with a pseudo-object l-value need special analysis. 14665 if (pty->getKind() == BuiltinType::PseudoObject && 14666 BinaryOperator::isAssignmentOp(Opc)) 14667 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14668 14669 // Don't resolve overloads if the other type is overloadable. 14670 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14671 // We can't actually test that if we still have a placeholder, 14672 // though. Fortunately, none of the exceptions we see in that 14673 // code below are valid when the LHS is an overload set. Note 14674 // that an overload set can be dependently-typed, but it never 14675 // instantiates to having an overloadable type. 14676 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14677 if (resolvedRHS.isInvalid()) return ExprError(); 14678 RHSExpr = resolvedRHS.get(); 14679 14680 if (RHSExpr->isTypeDependent() || 14681 RHSExpr->getType()->isOverloadableType()) 14682 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14683 } 14684 14685 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14686 // template, diagnose the missing 'template' keyword instead of diagnosing 14687 // an invalid use of a bound member function. 14688 // 14689 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14690 // to C++1z [over.over]/1.4, but we already checked for that case above. 14691 if (Opc == BO_LT && inTemplateInstantiation() && 14692 (pty->getKind() == BuiltinType::BoundMember || 14693 pty->getKind() == BuiltinType::Overload)) { 14694 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14695 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14696 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14697 return isa<FunctionTemplateDecl>(ND); 14698 })) { 14699 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14700 : OE->getNameLoc(), 14701 diag::err_template_kw_missing) 14702 << OE->getName().getAsString() << ""; 14703 return ExprError(); 14704 } 14705 } 14706 14707 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14708 if (LHS.isInvalid()) return ExprError(); 14709 LHSExpr = LHS.get(); 14710 } 14711 14712 // Handle pseudo-objects in the RHS. 14713 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14714 // An overload in the RHS can potentially be resolved by the type 14715 // being assigned to. 14716 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14717 if (getLangOpts().CPlusPlus && 14718 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14719 LHSExpr->getType()->isOverloadableType())) 14720 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14721 14722 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14723 } 14724 14725 // Don't resolve overloads if the other type is overloadable. 14726 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14727 LHSExpr->getType()->isOverloadableType()) 14728 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14729 14730 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14731 if (!resolvedRHS.isUsable()) return ExprError(); 14732 RHSExpr = resolvedRHS.get(); 14733 } 14734 14735 if (getLangOpts().CPlusPlus) { 14736 // If either expression is type-dependent, always build an 14737 // overloaded op. 14738 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14739 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14740 14741 // Otherwise, build an overloaded op if either expression has an 14742 // overloadable type. 14743 if (LHSExpr->getType()->isOverloadableType() || 14744 RHSExpr->getType()->isOverloadableType()) 14745 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14746 } 14747 14748 if (getLangOpts().RecoveryAST && 14749 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14750 assert(!getLangOpts().CPlusPlus); 14751 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14752 "Should only occur in error-recovery path."); 14753 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14754 // C [6.15.16] p3: 14755 // An assignment expression has the value of the left operand after the 14756 // assignment, but is not an lvalue. 14757 return CompoundAssignOperator::Create( 14758 Context, LHSExpr, RHSExpr, Opc, 14759 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 14760 OpLoc, CurFPFeatureOverrides()); 14761 QualType ResultType; 14762 switch (Opc) { 14763 case BO_Assign: 14764 ResultType = LHSExpr->getType().getUnqualifiedType(); 14765 break; 14766 case BO_LT: 14767 case BO_GT: 14768 case BO_LE: 14769 case BO_GE: 14770 case BO_EQ: 14771 case BO_NE: 14772 case BO_LAnd: 14773 case BO_LOr: 14774 // These operators have a fixed result type regardless of operands. 14775 ResultType = Context.IntTy; 14776 break; 14777 case BO_Comma: 14778 ResultType = RHSExpr->getType(); 14779 break; 14780 default: 14781 ResultType = Context.DependentTy; 14782 break; 14783 } 14784 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14785 VK_PRValue, OK_Ordinary, OpLoc, 14786 CurFPFeatureOverrides()); 14787 } 14788 14789 // Build a built-in binary operation. 14790 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14791 } 14792 14793 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14794 if (T.isNull() || T->isDependentType()) 14795 return false; 14796 14797 if (!T->isPromotableIntegerType()) 14798 return true; 14799 14800 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14801 } 14802 14803 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14804 UnaryOperatorKind Opc, 14805 Expr *InputExpr) { 14806 ExprResult Input = InputExpr; 14807 ExprValueKind VK = VK_PRValue; 14808 ExprObjectKind OK = OK_Ordinary; 14809 QualType resultType; 14810 bool CanOverflow = false; 14811 14812 bool ConvertHalfVec = false; 14813 if (getLangOpts().OpenCL) { 14814 QualType Ty = InputExpr->getType(); 14815 // The only legal unary operation for atomics is '&'. 14816 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14817 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14818 // only with a builtin functions and therefore should be disallowed here. 14819 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14820 || Ty->isBlockPointerType())) { 14821 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14822 << InputExpr->getType() 14823 << Input.get()->getSourceRange()); 14824 } 14825 } 14826 14827 switch (Opc) { 14828 case UO_PreInc: 14829 case UO_PreDec: 14830 case UO_PostInc: 14831 case UO_PostDec: 14832 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14833 OpLoc, 14834 Opc == UO_PreInc || 14835 Opc == UO_PostInc, 14836 Opc == UO_PreInc || 14837 Opc == UO_PreDec); 14838 CanOverflow = isOverflowingIntegerType(Context, resultType); 14839 break; 14840 case UO_AddrOf: 14841 resultType = CheckAddressOfOperand(Input, OpLoc); 14842 CheckAddressOfNoDeref(InputExpr); 14843 RecordModifiableNonNullParam(*this, InputExpr); 14844 break; 14845 case UO_Deref: { 14846 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14847 if (Input.isInvalid()) return ExprError(); 14848 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14849 break; 14850 } 14851 case UO_Plus: 14852 case UO_Minus: 14853 CanOverflow = Opc == UO_Minus && 14854 isOverflowingIntegerType(Context, Input.get()->getType()); 14855 Input = UsualUnaryConversions(Input.get()); 14856 if (Input.isInvalid()) return ExprError(); 14857 // Unary plus and minus require promoting an operand of half vector to a 14858 // float vector and truncating the result back to a half vector. For now, we 14859 // do this only when HalfArgsAndReturns is set (that is, when the target is 14860 // arm or arm64). 14861 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14862 14863 // If the operand is a half vector, promote it to a float vector. 14864 if (ConvertHalfVec) 14865 Input = convertVector(Input.get(), Context.FloatTy, *this); 14866 resultType = Input.get()->getType(); 14867 if (resultType->isDependentType()) 14868 break; 14869 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14870 break; 14871 else if (resultType->isVectorType() && 14872 // The z vector extensions don't allow + or - with bool vectors. 14873 (!Context.getLangOpts().ZVector || 14874 resultType->castAs<VectorType>()->getVectorKind() != 14875 VectorType::AltiVecBool)) 14876 break; 14877 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14878 Opc == UO_Plus && 14879 resultType->isPointerType()) 14880 break; 14881 14882 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14883 << resultType << Input.get()->getSourceRange()); 14884 14885 case UO_Not: // bitwise complement 14886 Input = UsualUnaryConversions(Input.get()); 14887 if (Input.isInvalid()) 14888 return ExprError(); 14889 resultType = Input.get()->getType(); 14890 if (resultType->isDependentType()) 14891 break; 14892 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14893 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14894 // C99 does not support '~' for complex conjugation. 14895 Diag(OpLoc, diag::ext_integer_complement_complex) 14896 << resultType << Input.get()->getSourceRange(); 14897 else if (resultType->hasIntegerRepresentation()) 14898 break; 14899 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14900 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14901 // on vector float types. 14902 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14903 if (!T->isIntegerType()) 14904 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14905 << resultType << Input.get()->getSourceRange()); 14906 } else { 14907 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14908 << resultType << Input.get()->getSourceRange()); 14909 } 14910 break; 14911 14912 case UO_LNot: // logical negation 14913 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14914 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14915 if (Input.isInvalid()) return ExprError(); 14916 resultType = Input.get()->getType(); 14917 14918 // Though we still have to promote half FP to float... 14919 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14920 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14921 resultType = Context.FloatTy; 14922 } 14923 14924 if (resultType->isDependentType()) 14925 break; 14926 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14927 // C99 6.5.3.3p1: ok, fallthrough; 14928 if (Context.getLangOpts().CPlusPlus) { 14929 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14930 // operand contextually converted to bool. 14931 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14932 ScalarTypeToBooleanCastKind(resultType)); 14933 } else if (Context.getLangOpts().OpenCL && 14934 Context.getLangOpts().OpenCLVersion < 120) { 14935 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14936 // operate on scalar float types. 14937 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14938 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14939 << resultType << Input.get()->getSourceRange()); 14940 } 14941 } else if (resultType->isExtVectorType()) { 14942 if (Context.getLangOpts().OpenCL && 14943 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { 14944 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14945 // operate on vector float types. 14946 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14947 if (!T->isIntegerType()) 14948 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14949 << resultType << Input.get()->getSourceRange()); 14950 } 14951 // Vector logical not returns the signed variant of the operand type. 14952 resultType = GetSignedVectorType(resultType); 14953 break; 14954 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14955 const VectorType *VTy = resultType->castAs<VectorType>(); 14956 if (VTy->getVectorKind() != VectorType::GenericVector) 14957 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14958 << resultType << Input.get()->getSourceRange()); 14959 14960 // Vector logical not returns the signed variant of the operand type. 14961 resultType = GetSignedVectorType(resultType); 14962 break; 14963 } else { 14964 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14965 << resultType << Input.get()->getSourceRange()); 14966 } 14967 14968 // LNot always has type int. C99 6.5.3.3p5. 14969 // In C++, it's bool. C++ 5.3.1p8 14970 resultType = Context.getLogicalOperationType(); 14971 break; 14972 case UO_Real: 14973 case UO_Imag: 14974 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14975 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14976 // complex l-values to ordinary l-values and all other values to r-values. 14977 if (Input.isInvalid()) return ExprError(); 14978 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14979 if (Input.get()->isGLValue() && 14980 Input.get()->getObjectKind() == OK_Ordinary) 14981 VK = Input.get()->getValueKind(); 14982 } else if (!getLangOpts().CPlusPlus) { 14983 // In C, a volatile scalar is read by __imag. In C++, it is not. 14984 Input = DefaultLvalueConversion(Input.get()); 14985 } 14986 break; 14987 case UO_Extension: 14988 resultType = Input.get()->getType(); 14989 VK = Input.get()->getValueKind(); 14990 OK = Input.get()->getObjectKind(); 14991 break; 14992 case UO_Coawait: 14993 // It's unnecessary to represent the pass-through operator co_await in the 14994 // AST; just return the input expression instead. 14995 assert(!Input.get()->getType()->isDependentType() && 14996 "the co_await expression must be non-dependant before " 14997 "building operator co_await"); 14998 return Input; 14999 } 15000 if (resultType.isNull() || Input.isInvalid()) 15001 return ExprError(); 15002 15003 // Check for array bounds violations in the operand of the UnaryOperator, 15004 // except for the '*' and '&' operators that have to be handled specially 15005 // by CheckArrayAccess (as there are special cases like &array[arraysize] 15006 // that are explicitly defined as valid by the standard). 15007 if (Opc != UO_AddrOf && Opc != UO_Deref) 15008 CheckArrayAccess(Input.get()); 15009 15010 auto *UO = 15011 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 15012 OpLoc, CanOverflow, CurFPFeatureOverrides()); 15013 15014 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 15015 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 15016 !isUnevaluatedContext()) 15017 ExprEvalContexts.back().PossibleDerefs.insert(UO); 15018 15019 // Convert the result back to a half vector. 15020 if (ConvertHalfVec) 15021 return convertVector(UO, Context.HalfTy, *this); 15022 return UO; 15023 } 15024 15025 /// Determine whether the given expression is a qualified member 15026 /// access expression, of a form that could be turned into a pointer to member 15027 /// with the address-of operator. 15028 bool Sema::isQualifiedMemberAccess(Expr *E) { 15029 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15030 if (!DRE->getQualifier()) 15031 return false; 15032 15033 ValueDecl *VD = DRE->getDecl(); 15034 if (!VD->isCXXClassMember()) 15035 return false; 15036 15037 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 15038 return true; 15039 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 15040 return Method->isInstance(); 15041 15042 return false; 15043 } 15044 15045 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15046 if (!ULE->getQualifier()) 15047 return false; 15048 15049 for (NamedDecl *D : ULE->decls()) { 15050 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 15051 if (Method->isInstance()) 15052 return true; 15053 } else { 15054 // Overload set does not contain methods. 15055 break; 15056 } 15057 } 15058 15059 return false; 15060 } 15061 15062 return false; 15063 } 15064 15065 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 15066 UnaryOperatorKind Opc, Expr *Input) { 15067 // First things first: handle placeholders so that the 15068 // overloaded-operator check considers the right type. 15069 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 15070 // Increment and decrement of pseudo-object references. 15071 if (pty->getKind() == BuiltinType::PseudoObject && 15072 UnaryOperator::isIncrementDecrementOp(Opc)) 15073 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 15074 15075 // extension is always a builtin operator. 15076 if (Opc == UO_Extension) 15077 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15078 15079 // & gets special logic for several kinds of placeholder. 15080 // The builtin code knows what to do. 15081 if (Opc == UO_AddrOf && 15082 (pty->getKind() == BuiltinType::Overload || 15083 pty->getKind() == BuiltinType::UnknownAny || 15084 pty->getKind() == BuiltinType::BoundMember)) 15085 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15086 15087 // Anything else needs to be handled now. 15088 ExprResult Result = CheckPlaceholderExpr(Input); 15089 if (Result.isInvalid()) return ExprError(); 15090 Input = Result.get(); 15091 } 15092 15093 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 15094 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 15095 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 15096 // Find all of the overloaded operators visible from this point. 15097 UnresolvedSet<16> Functions; 15098 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 15099 if (S && OverOp != OO_None) 15100 LookupOverloadedOperatorName(OverOp, S, Functions); 15101 15102 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 15103 } 15104 15105 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15106 } 15107 15108 // Unary Operators. 'Tok' is the token for the operator. 15109 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 15110 tok::TokenKind Op, Expr *Input) { 15111 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 15112 } 15113 15114 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 15115 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 15116 LabelDecl *TheDecl) { 15117 TheDecl->markUsed(Context); 15118 // Create the AST node. The address of a label always has type 'void*'. 15119 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 15120 Context.getPointerType(Context.VoidTy)); 15121 } 15122 15123 void Sema::ActOnStartStmtExpr() { 15124 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15125 } 15126 15127 void Sema::ActOnStmtExprError() { 15128 // Note that function is also called by TreeTransform when leaving a 15129 // StmtExpr scope without rebuilding anything. 15130 15131 DiscardCleanupsInEvaluationContext(); 15132 PopExpressionEvaluationContext(); 15133 } 15134 15135 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15136 SourceLocation RPLoc) { 15137 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15138 } 15139 15140 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15141 SourceLocation RPLoc, unsigned TemplateDepth) { 15142 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15143 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15144 15145 if (hasAnyUnrecoverableErrorsInThisFunction()) 15146 DiscardCleanupsInEvaluationContext(); 15147 assert(!Cleanup.exprNeedsCleanups() && 15148 "cleanups within StmtExpr not correctly bound!"); 15149 PopExpressionEvaluationContext(); 15150 15151 // FIXME: there are a variety of strange constraints to enforce here, for 15152 // example, it is not possible to goto into a stmt expression apparently. 15153 // More semantic analysis is needed. 15154 15155 // If there are sub-stmts in the compound stmt, take the type of the last one 15156 // as the type of the stmtexpr. 15157 QualType Ty = Context.VoidTy; 15158 bool StmtExprMayBindToTemp = false; 15159 if (!Compound->body_empty()) { 15160 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15161 if (const auto *LastStmt = 15162 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15163 if (const Expr *Value = LastStmt->getExprStmt()) { 15164 StmtExprMayBindToTemp = true; 15165 Ty = Value->getType(); 15166 } 15167 } 15168 } 15169 15170 // FIXME: Check that expression type is complete/non-abstract; statement 15171 // expressions are not lvalues. 15172 Expr *ResStmtExpr = 15173 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15174 if (StmtExprMayBindToTemp) 15175 return MaybeBindToTemporary(ResStmtExpr); 15176 return ResStmtExpr; 15177 } 15178 15179 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15180 if (ER.isInvalid()) 15181 return ExprError(); 15182 15183 // Do function/array conversion on the last expression, but not 15184 // lvalue-to-rvalue. However, initialize an unqualified type. 15185 ER = DefaultFunctionArrayConversion(ER.get()); 15186 if (ER.isInvalid()) 15187 return ExprError(); 15188 Expr *E = ER.get(); 15189 15190 if (E->isTypeDependent()) 15191 return E; 15192 15193 // In ARC, if the final expression ends in a consume, splice 15194 // the consume out and bind it later. In the alternate case 15195 // (when dealing with a retainable type), the result 15196 // initialization will create a produce. In both cases the 15197 // result will be +1, and we'll need to balance that out with 15198 // a bind. 15199 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15200 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15201 return Cast->getSubExpr(); 15202 15203 // FIXME: Provide a better location for the initialization. 15204 return PerformCopyInitialization( 15205 InitializedEntity::InitializeStmtExprResult( 15206 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15207 SourceLocation(), E); 15208 } 15209 15210 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15211 TypeSourceInfo *TInfo, 15212 ArrayRef<OffsetOfComponent> Components, 15213 SourceLocation RParenLoc) { 15214 QualType ArgTy = TInfo->getType(); 15215 bool Dependent = ArgTy->isDependentType(); 15216 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15217 15218 // We must have at least one component that refers to the type, and the first 15219 // one is known to be a field designator. Verify that the ArgTy represents 15220 // a struct/union/class. 15221 if (!Dependent && !ArgTy->isRecordType()) 15222 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15223 << ArgTy << TypeRange); 15224 15225 // Type must be complete per C99 7.17p3 because a declaring a variable 15226 // with an incomplete type would be ill-formed. 15227 if (!Dependent 15228 && RequireCompleteType(BuiltinLoc, ArgTy, 15229 diag::err_offsetof_incomplete_type, TypeRange)) 15230 return ExprError(); 15231 15232 bool DidWarnAboutNonPOD = false; 15233 QualType CurrentType = ArgTy; 15234 SmallVector<OffsetOfNode, 4> Comps; 15235 SmallVector<Expr*, 4> Exprs; 15236 for (const OffsetOfComponent &OC : Components) { 15237 if (OC.isBrackets) { 15238 // Offset of an array sub-field. TODO: Should we allow vector elements? 15239 if (!CurrentType->isDependentType()) { 15240 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15241 if(!AT) 15242 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15243 << CurrentType); 15244 CurrentType = AT->getElementType(); 15245 } else 15246 CurrentType = Context.DependentTy; 15247 15248 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15249 if (IdxRval.isInvalid()) 15250 return ExprError(); 15251 Expr *Idx = IdxRval.get(); 15252 15253 // The expression must be an integral expression. 15254 // FIXME: An integral constant expression? 15255 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15256 !Idx->getType()->isIntegerType()) 15257 return ExprError( 15258 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15259 << Idx->getSourceRange()); 15260 15261 // Record this array index. 15262 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15263 Exprs.push_back(Idx); 15264 continue; 15265 } 15266 15267 // Offset of a field. 15268 if (CurrentType->isDependentType()) { 15269 // We have the offset of a field, but we can't look into the dependent 15270 // type. Just record the identifier of the field. 15271 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15272 CurrentType = Context.DependentTy; 15273 continue; 15274 } 15275 15276 // We need to have a complete type to look into. 15277 if (RequireCompleteType(OC.LocStart, CurrentType, 15278 diag::err_offsetof_incomplete_type)) 15279 return ExprError(); 15280 15281 // Look for the designated field. 15282 const RecordType *RC = CurrentType->getAs<RecordType>(); 15283 if (!RC) 15284 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15285 << CurrentType); 15286 RecordDecl *RD = RC->getDecl(); 15287 15288 // C++ [lib.support.types]p5: 15289 // The macro offsetof accepts a restricted set of type arguments in this 15290 // International Standard. type shall be a POD structure or a POD union 15291 // (clause 9). 15292 // C++11 [support.types]p4: 15293 // If type is not a standard-layout class (Clause 9), the results are 15294 // undefined. 15295 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15296 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15297 unsigned DiagID = 15298 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15299 : diag::ext_offsetof_non_pod_type; 15300 15301 if (!IsSafe && !DidWarnAboutNonPOD && 15302 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15303 PDiag(DiagID) 15304 << SourceRange(Components[0].LocStart, OC.LocEnd) 15305 << CurrentType)) 15306 DidWarnAboutNonPOD = true; 15307 } 15308 15309 // Look for the field. 15310 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15311 LookupQualifiedName(R, RD); 15312 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15313 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15314 if (!MemberDecl) { 15315 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15316 MemberDecl = IndirectMemberDecl->getAnonField(); 15317 } 15318 15319 if (!MemberDecl) 15320 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15321 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15322 OC.LocEnd)); 15323 15324 // C99 7.17p3: 15325 // (If the specified member is a bit-field, the behavior is undefined.) 15326 // 15327 // We diagnose this as an error. 15328 if (MemberDecl->isBitField()) { 15329 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15330 << MemberDecl->getDeclName() 15331 << SourceRange(BuiltinLoc, RParenLoc); 15332 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15333 return ExprError(); 15334 } 15335 15336 RecordDecl *Parent = MemberDecl->getParent(); 15337 if (IndirectMemberDecl) 15338 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15339 15340 // If the member was found in a base class, introduce OffsetOfNodes for 15341 // the base class indirections. 15342 CXXBasePaths Paths; 15343 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15344 Paths)) { 15345 if (Paths.getDetectedVirtual()) { 15346 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15347 << MemberDecl->getDeclName() 15348 << SourceRange(BuiltinLoc, RParenLoc); 15349 return ExprError(); 15350 } 15351 15352 CXXBasePath &Path = Paths.front(); 15353 for (const CXXBasePathElement &B : Path) 15354 Comps.push_back(OffsetOfNode(B.Base)); 15355 } 15356 15357 if (IndirectMemberDecl) { 15358 for (auto *FI : IndirectMemberDecl->chain()) { 15359 assert(isa<FieldDecl>(FI)); 15360 Comps.push_back(OffsetOfNode(OC.LocStart, 15361 cast<FieldDecl>(FI), OC.LocEnd)); 15362 } 15363 } else 15364 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15365 15366 CurrentType = MemberDecl->getType().getNonReferenceType(); 15367 } 15368 15369 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15370 Comps, Exprs, RParenLoc); 15371 } 15372 15373 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15374 SourceLocation BuiltinLoc, 15375 SourceLocation TypeLoc, 15376 ParsedType ParsedArgTy, 15377 ArrayRef<OffsetOfComponent> Components, 15378 SourceLocation RParenLoc) { 15379 15380 TypeSourceInfo *ArgTInfo; 15381 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15382 if (ArgTy.isNull()) 15383 return ExprError(); 15384 15385 if (!ArgTInfo) 15386 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15387 15388 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15389 } 15390 15391 15392 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15393 Expr *CondExpr, 15394 Expr *LHSExpr, Expr *RHSExpr, 15395 SourceLocation RPLoc) { 15396 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15397 15398 ExprValueKind VK = VK_PRValue; 15399 ExprObjectKind OK = OK_Ordinary; 15400 QualType resType; 15401 bool CondIsTrue = false; 15402 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15403 resType = Context.DependentTy; 15404 } else { 15405 // The conditional expression is required to be a constant expression. 15406 llvm::APSInt condEval(32); 15407 ExprResult CondICE = VerifyIntegerConstantExpression( 15408 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15409 if (CondICE.isInvalid()) 15410 return ExprError(); 15411 CondExpr = CondICE.get(); 15412 CondIsTrue = condEval.getZExtValue(); 15413 15414 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15415 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15416 15417 resType = ActiveExpr->getType(); 15418 VK = ActiveExpr->getValueKind(); 15419 OK = ActiveExpr->getObjectKind(); 15420 } 15421 15422 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15423 resType, VK, OK, RPLoc, CondIsTrue); 15424 } 15425 15426 //===----------------------------------------------------------------------===// 15427 // Clang Extensions. 15428 //===----------------------------------------------------------------------===// 15429 15430 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15431 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15432 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15433 15434 if (LangOpts.CPlusPlus) { 15435 MangleNumberingContext *MCtx; 15436 Decl *ManglingContextDecl; 15437 std::tie(MCtx, ManglingContextDecl) = 15438 getCurrentMangleNumberContext(Block->getDeclContext()); 15439 if (MCtx) { 15440 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15441 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15442 } 15443 } 15444 15445 PushBlockScope(CurScope, Block); 15446 CurContext->addDecl(Block); 15447 if (CurScope) 15448 PushDeclContext(CurScope, Block); 15449 else 15450 CurContext = Block; 15451 15452 getCurBlock()->HasImplicitReturnType = true; 15453 15454 // Enter a new evaluation context to insulate the block from any 15455 // cleanups from the enclosing full-expression. 15456 PushExpressionEvaluationContext( 15457 ExpressionEvaluationContext::PotentiallyEvaluated); 15458 } 15459 15460 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15461 Scope *CurScope) { 15462 assert(ParamInfo.getIdentifier() == nullptr && 15463 "block-id should have no identifier!"); 15464 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15465 BlockScopeInfo *CurBlock = getCurBlock(); 15466 15467 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15468 QualType T = Sig->getType(); 15469 15470 // FIXME: We should allow unexpanded parameter packs here, but that would, 15471 // in turn, make the block expression contain unexpanded parameter packs. 15472 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15473 // Drop the parameters. 15474 FunctionProtoType::ExtProtoInfo EPI; 15475 EPI.HasTrailingReturn = false; 15476 EPI.TypeQuals.addConst(); 15477 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15478 Sig = Context.getTrivialTypeSourceInfo(T); 15479 } 15480 15481 // GetTypeForDeclarator always produces a function type for a block 15482 // literal signature. Furthermore, it is always a FunctionProtoType 15483 // unless the function was written with a typedef. 15484 assert(T->isFunctionType() && 15485 "GetTypeForDeclarator made a non-function block signature"); 15486 15487 // Look for an explicit signature in that function type. 15488 FunctionProtoTypeLoc ExplicitSignature; 15489 15490 if ((ExplicitSignature = Sig->getTypeLoc() 15491 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15492 15493 // Check whether that explicit signature was synthesized by 15494 // GetTypeForDeclarator. If so, don't save that as part of the 15495 // written signature. 15496 if (ExplicitSignature.getLocalRangeBegin() == 15497 ExplicitSignature.getLocalRangeEnd()) { 15498 // This would be much cheaper if we stored TypeLocs instead of 15499 // TypeSourceInfos. 15500 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15501 unsigned Size = Result.getFullDataSize(); 15502 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15503 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15504 15505 ExplicitSignature = FunctionProtoTypeLoc(); 15506 } 15507 } 15508 15509 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15510 CurBlock->FunctionType = T; 15511 15512 const auto *Fn = T->castAs<FunctionType>(); 15513 QualType RetTy = Fn->getReturnType(); 15514 bool isVariadic = 15515 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15516 15517 CurBlock->TheDecl->setIsVariadic(isVariadic); 15518 15519 // Context.DependentTy is used as a placeholder for a missing block 15520 // return type. TODO: what should we do with declarators like: 15521 // ^ * { ... } 15522 // If the answer is "apply template argument deduction".... 15523 if (RetTy != Context.DependentTy) { 15524 CurBlock->ReturnType = RetTy; 15525 CurBlock->TheDecl->setBlockMissingReturnType(false); 15526 CurBlock->HasImplicitReturnType = false; 15527 } 15528 15529 // Push block parameters from the declarator if we had them. 15530 SmallVector<ParmVarDecl*, 8> Params; 15531 if (ExplicitSignature) { 15532 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15533 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15534 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15535 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15536 // Diagnose this as an extension in C17 and earlier. 15537 if (!getLangOpts().C2x) 15538 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15539 } 15540 Params.push_back(Param); 15541 } 15542 15543 // Fake up parameter variables if we have a typedef, like 15544 // ^ fntype { ... } 15545 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15546 for (const auto &I : Fn->param_types()) { 15547 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15548 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15549 Params.push_back(Param); 15550 } 15551 } 15552 15553 // Set the parameters on the block decl. 15554 if (!Params.empty()) { 15555 CurBlock->TheDecl->setParams(Params); 15556 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15557 /*CheckParameterNames=*/false); 15558 } 15559 15560 // Finally we can process decl attributes. 15561 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15562 15563 // Put the parameter variables in scope. 15564 for (auto AI : CurBlock->TheDecl->parameters()) { 15565 AI->setOwningFunction(CurBlock->TheDecl); 15566 15567 // If this has an identifier, add it to the scope stack. 15568 if (AI->getIdentifier()) { 15569 CheckShadow(CurBlock->TheScope, AI); 15570 15571 PushOnScopeChains(AI, CurBlock->TheScope); 15572 } 15573 } 15574 } 15575 15576 /// ActOnBlockError - If there is an error parsing a block, this callback 15577 /// is invoked to pop the information about the block from the action impl. 15578 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15579 // Leave the expression-evaluation context. 15580 DiscardCleanupsInEvaluationContext(); 15581 PopExpressionEvaluationContext(); 15582 15583 // Pop off CurBlock, handle nested blocks. 15584 PopDeclContext(); 15585 PopFunctionScopeInfo(); 15586 } 15587 15588 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15589 /// literal was successfully completed. ^(int x){...} 15590 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15591 Stmt *Body, Scope *CurScope) { 15592 // If blocks are disabled, emit an error. 15593 if (!LangOpts.Blocks) 15594 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15595 15596 // Leave the expression-evaluation context. 15597 if (hasAnyUnrecoverableErrorsInThisFunction()) 15598 DiscardCleanupsInEvaluationContext(); 15599 assert(!Cleanup.exprNeedsCleanups() && 15600 "cleanups within block not correctly bound!"); 15601 PopExpressionEvaluationContext(); 15602 15603 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15604 BlockDecl *BD = BSI->TheDecl; 15605 15606 if (BSI->HasImplicitReturnType) 15607 deduceClosureReturnType(*BSI); 15608 15609 QualType RetTy = Context.VoidTy; 15610 if (!BSI->ReturnType.isNull()) 15611 RetTy = BSI->ReturnType; 15612 15613 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15614 QualType BlockTy; 15615 15616 // If the user wrote a function type in some form, try to use that. 15617 if (!BSI->FunctionType.isNull()) { 15618 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15619 15620 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15621 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15622 15623 // Turn protoless block types into nullary block types. 15624 if (isa<FunctionNoProtoType>(FTy)) { 15625 FunctionProtoType::ExtProtoInfo EPI; 15626 EPI.ExtInfo = Ext; 15627 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15628 15629 // Otherwise, if we don't need to change anything about the function type, 15630 // preserve its sugar structure. 15631 } else if (FTy->getReturnType() == RetTy && 15632 (!NoReturn || FTy->getNoReturnAttr())) { 15633 BlockTy = BSI->FunctionType; 15634 15635 // Otherwise, make the minimal modifications to the function type. 15636 } else { 15637 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15638 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15639 EPI.TypeQuals = Qualifiers(); 15640 EPI.ExtInfo = Ext; 15641 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15642 } 15643 15644 // If we don't have a function type, just build one from nothing. 15645 } else { 15646 FunctionProtoType::ExtProtoInfo EPI; 15647 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15648 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15649 } 15650 15651 DiagnoseUnusedParameters(BD->parameters()); 15652 BlockTy = Context.getBlockPointerType(BlockTy); 15653 15654 // If needed, diagnose invalid gotos and switches in the block. 15655 if (getCurFunction()->NeedsScopeChecking() && 15656 !PP.isCodeCompletionEnabled()) 15657 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15658 15659 BD->setBody(cast<CompoundStmt>(Body)); 15660 15661 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15662 DiagnoseUnguardedAvailabilityViolations(BD); 15663 15664 // Try to apply the named return value optimization. We have to check again 15665 // if we can do this, though, because blocks keep return statements around 15666 // to deduce an implicit return type. 15667 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15668 !BD->isDependentContext()) 15669 computeNRVO(Body, BSI); 15670 15671 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15672 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15673 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15674 NTCUK_Destruct|NTCUK_Copy); 15675 15676 PopDeclContext(); 15677 15678 // Set the captured variables on the block. 15679 SmallVector<BlockDecl::Capture, 4> Captures; 15680 for (Capture &Cap : BSI->Captures) { 15681 if (Cap.isInvalid() || Cap.isThisCapture()) 15682 continue; 15683 15684 VarDecl *Var = Cap.getVariable(); 15685 Expr *CopyExpr = nullptr; 15686 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15687 if (const RecordType *Record = 15688 Cap.getCaptureType()->getAs<RecordType>()) { 15689 // The capture logic needs the destructor, so make sure we mark it. 15690 // Usually this is unnecessary because most local variables have 15691 // their destructors marked at declaration time, but parameters are 15692 // an exception because it's technically only the call site that 15693 // actually requires the destructor. 15694 if (isa<ParmVarDecl>(Var)) 15695 FinalizeVarWithDestructor(Var, Record); 15696 15697 // Enter a separate potentially-evaluated context while building block 15698 // initializers to isolate their cleanups from those of the block 15699 // itself. 15700 // FIXME: Is this appropriate even when the block itself occurs in an 15701 // unevaluated operand? 15702 EnterExpressionEvaluationContext EvalContext( 15703 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15704 15705 SourceLocation Loc = Cap.getLocation(); 15706 15707 ExprResult Result = BuildDeclarationNameExpr( 15708 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15709 15710 // According to the blocks spec, the capture of a variable from 15711 // the stack requires a const copy constructor. This is not true 15712 // of the copy/move done to move a __block variable to the heap. 15713 if (!Result.isInvalid() && 15714 !Result.get()->getType().isConstQualified()) { 15715 Result = ImpCastExprToType(Result.get(), 15716 Result.get()->getType().withConst(), 15717 CK_NoOp, VK_LValue); 15718 } 15719 15720 if (!Result.isInvalid()) { 15721 Result = PerformCopyInitialization( 15722 InitializedEntity::InitializeBlock(Var->getLocation(), 15723 Cap.getCaptureType()), 15724 Loc, Result.get()); 15725 } 15726 15727 // Build a full-expression copy expression if initialization 15728 // succeeded and used a non-trivial constructor. Recover from 15729 // errors by pretending that the copy isn't necessary. 15730 if (!Result.isInvalid() && 15731 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15732 ->isTrivial()) { 15733 Result = MaybeCreateExprWithCleanups(Result); 15734 CopyExpr = Result.get(); 15735 } 15736 } 15737 } 15738 15739 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15740 CopyExpr); 15741 Captures.push_back(NewCap); 15742 } 15743 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15744 15745 // Pop the block scope now but keep it alive to the end of this function. 15746 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15747 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15748 15749 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15750 15751 // If the block isn't obviously global, i.e. it captures anything at 15752 // all, then we need to do a few things in the surrounding context: 15753 if (Result->getBlockDecl()->hasCaptures()) { 15754 // First, this expression has a new cleanup object. 15755 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15756 Cleanup.setExprNeedsCleanups(true); 15757 15758 // It also gets a branch-protected scope if any of the captured 15759 // variables needs destruction. 15760 for (const auto &CI : Result->getBlockDecl()->captures()) { 15761 const VarDecl *var = CI.getVariable(); 15762 if (var->getType().isDestructedType() != QualType::DK_none) { 15763 setFunctionHasBranchProtectedScope(); 15764 break; 15765 } 15766 } 15767 } 15768 15769 if (getCurFunction()) 15770 getCurFunction()->addBlock(BD); 15771 15772 return Result; 15773 } 15774 15775 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15776 SourceLocation RPLoc) { 15777 TypeSourceInfo *TInfo; 15778 GetTypeFromParser(Ty, &TInfo); 15779 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15780 } 15781 15782 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15783 Expr *E, TypeSourceInfo *TInfo, 15784 SourceLocation RPLoc) { 15785 Expr *OrigExpr = E; 15786 bool IsMS = false; 15787 15788 // CUDA device code does not support varargs. 15789 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15790 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15791 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15792 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15793 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15794 } 15795 } 15796 15797 // NVPTX does not support va_arg expression. 15798 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15799 Context.getTargetInfo().getTriple().isNVPTX()) 15800 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15801 15802 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15803 // as Microsoft ABI on an actual Microsoft platform, where 15804 // __builtin_ms_va_list and __builtin_va_list are the same.) 15805 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15806 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15807 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15808 if (Context.hasSameType(MSVaListType, E->getType())) { 15809 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15810 return ExprError(); 15811 IsMS = true; 15812 } 15813 } 15814 15815 // Get the va_list type 15816 QualType VaListType = Context.getBuiltinVaListType(); 15817 if (!IsMS) { 15818 if (VaListType->isArrayType()) { 15819 // Deal with implicit array decay; for example, on x86-64, 15820 // va_list is an array, but it's supposed to decay to 15821 // a pointer for va_arg. 15822 VaListType = Context.getArrayDecayedType(VaListType); 15823 // Make sure the input expression also decays appropriately. 15824 ExprResult Result = UsualUnaryConversions(E); 15825 if (Result.isInvalid()) 15826 return ExprError(); 15827 E = Result.get(); 15828 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15829 // If va_list is a record type and we are compiling in C++ mode, 15830 // check the argument using reference binding. 15831 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15832 Context, Context.getLValueReferenceType(VaListType), false); 15833 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15834 if (Init.isInvalid()) 15835 return ExprError(); 15836 E = Init.getAs<Expr>(); 15837 } else { 15838 // Otherwise, the va_list argument must be an l-value because 15839 // it is modified by va_arg. 15840 if (!E->isTypeDependent() && 15841 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15842 return ExprError(); 15843 } 15844 } 15845 15846 if (!IsMS && !E->isTypeDependent() && 15847 !Context.hasSameType(VaListType, E->getType())) 15848 return ExprError( 15849 Diag(E->getBeginLoc(), 15850 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15851 << OrigExpr->getType() << E->getSourceRange()); 15852 15853 if (!TInfo->getType()->isDependentType()) { 15854 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15855 diag::err_second_parameter_to_va_arg_incomplete, 15856 TInfo->getTypeLoc())) 15857 return ExprError(); 15858 15859 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15860 TInfo->getType(), 15861 diag::err_second_parameter_to_va_arg_abstract, 15862 TInfo->getTypeLoc())) 15863 return ExprError(); 15864 15865 if (!TInfo->getType().isPODType(Context)) { 15866 Diag(TInfo->getTypeLoc().getBeginLoc(), 15867 TInfo->getType()->isObjCLifetimeType() 15868 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15869 : diag::warn_second_parameter_to_va_arg_not_pod) 15870 << TInfo->getType() 15871 << TInfo->getTypeLoc().getSourceRange(); 15872 } 15873 15874 // Check for va_arg where arguments of the given type will be promoted 15875 // (i.e. this va_arg is guaranteed to have undefined behavior). 15876 QualType PromoteType; 15877 if (TInfo->getType()->isPromotableIntegerType()) { 15878 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15879 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 15880 // and C2x 7.16.1.1p2 says, in part: 15881 // If type is not compatible with the type of the actual next argument 15882 // (as promoted according to the default argument promotions), the 15883 // behavior is undefined, except for the following cases: 15884 // - both types are pointers to qualified or unqualified versions of 15885 // compatible types; 15886 // - one type is a signed integer type, the other type is the 15887 // corresponding unsigned integer type, and the value is 15888 // representable in both types; 15889 // - one type is pointer to qualified or unqualified void and the 15890 // other is a pointer to a qualified or unqualified character type. 15891 // Given that type compatibility is the primary requirement (ignoring 15892 // qualifications), you would think we could call typesAreCompatible() 15893 // directly to test this. However, in C++, that checks for *same type*, 15894 // which causes false positives when passing an enumeration type to 15895 // va_arg. Instead, get the underlying type of the enumeration and pass 15896 // that. 15897 QualType UnderlyingType = TInfo->getType(); 15898 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 15899 UnderlyingType = ET->getDecl()->getIntegerType(); 15900 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15901 /*CompareUnqualified*/ true)) 15902 PromoteType = QualType(); 15903 15904 // If the types are still not compatible, we need to test whether the 15905 // promoted type and the underlying type are the same except for 15906 // signedness. Ask the AST for the correctly corresponding type and see 15907 // if that's compatible. 15908 if (!PromoteType.isNull() && 15909 PromoteType->isUnsignedIntegerType() != 15910 UnderlyingType->isUnsignedIntegerType()) { 15911 UnderlyingType = 15912 UnderlyingType->isUnsignedIntegerType() 15913 ? Context.getCorrespondingSignedType(UnderlyingType) 15914 : Context.getCorrespondingUnsignedType(UnderlyingType); 15915 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15916 /*CompareUnqualified*/ true)) 15917 PromoteType = QualType(); 15918 } 15919 } 15920 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15921 PromoteType = Context.DoubleTy; 15922 if (!PromoteType.isNull()) 15923 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15924 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15925 << TInfo->getType() 15926 << PromoteType 15927 << TInfo->getTypeLoc().getSourceRange()); 15928 } 15929 15930 QualType T = TInfo->getType().getNonLValueExprType(Context); 15931 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15932 } 15933 15934 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15935 // The type of __null will be int or long, depending on the size of 15936 // pointers on the target. 15937 QualType Ty; 15938 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15939 if (pw == Context.getTargetInfo().getIntWidth()) 15940 Ty = Context.IntTy; 15941 else if (pw == Context.getTargetInfo().getLongWidth()) 15942 Ty = Context.LongTy; 15943 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15944 Ty = Context.LongLongTy; 15945 else { 15946 llvm_unreachable("I don't know size of pointer!"); 15947 } 15948 15949 return new (Context) GNUNullExpr(Ty, TokenLoc); 15950 } 15951 15952 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15953 SourceLocation BuiltinLoc, 15954 SourceLocation RPLoc) { 15955 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15956 } 15957 15958 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15959 SourceLocation BuiltinLoc, 15960 SourceLocation RPLoc, 15961 DeclContext *ParentContext) { 15962 return new (Context) 15963 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15964 } 15965 15966 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15967 bool Diagnose) { 15968 if (!getLangOpts().ObjC) 15969 return false; 15970 15971 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15972 if (!PT) 15973 return false; 15974 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15975 15976 // Ignore any parens, implicit casts (should only be 15977 // array-to-pointer decays), and not-so-opaque values. The last is 15978 // important for making this trigger for property assignments. 15979 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15980 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15981 if (OV->getSourceExpr()) 15982 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15983 15984 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15985 if (!PT->isObjCIdType() && 15986 !(ID && ID->getIdentifier()->isStr("NSString"))) 15987 return false; 15988 if (!SL->isAscii()) 15989 return false; 15990 15991 if (Diagnose) { 15992 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15993 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15994 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15995 } 15996 return true; 15997 } 15998 15999 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 16000 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 16001 isa<CXXBoolLiteralExpr>(SrcExpr)) && 16002 !SrcExpr->isNullPointerConstant( 16003 getASTContext(), Expr::NPC_NeverValueDependent)) { 16004 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 16005 return false; 16006 if (Diagnose) { 16007 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 16008 << /*number*/1 16009 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 16010 Expr *NumLit = 16011 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 16012 if (NumLit) 16013 Exp = NumLit; 16014 } 16015 return true; 16016 } 16017 16018 return false; 16019 } 16020 16021 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 16022 const Expr *SrcExpr) { 16023 if (!DstType->isFunctionPointerType() || 16024 !SrcExpr->getType()->isFunctionType()) 16025 return false; 16026 16027 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 16028 if (!DRE) 16029 return false; 16030 16031 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 16032 if (!FD) 16033 return false; 16034 16035 return !S.checkAddressOfFunctionIsAvailable(FD, 16036 /*Complain=*/true, 16037 SrcExpr->getBeginLoc()); 16038 } 16039 16040 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 16041 SourceLocation Loc, 16042 QualType DstType, QualType SrcType, 16043 Expr *SrcExpr, AssignmentAction Action, 16044 bool *Complained) { 16045 if (Complained) 16046 *Complained = false; 16047 16048 // Decode the result (notice that AST's are still created for extensions). 16049 bool CheckInferredResultType = false; 16050 bool isInvalid = false; 16051 unsigned DiagKind = 0; 16052 ConversionFixItGenerator ConvHints; 16053 bool MayHaveConvFixit = false; 16054 bool MayHaveFunctionDiff = false; 16055 const ObjCInterfaceDecl *IFace = nullptr; 16056 const ObjCProtocolDecl *PDecl = nullptr; 16057 16058 switch (ConvTy) { 16059 case Compatible: 16060 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 16061 return false; 16062 16063 case PointerToInt: 16064 if (getLangOpts().CPlusPlus) { 16065 DiagKind = diag::err_typecheck_convert_pointer_int; 16066 isInvalid = true; 16067 } else { 16068 DiagKind = diag::ext_typecheck_convert_pointer_int; 16069 } 16070 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16071 MayHaveConvFixit = true; 16072 break; 16073 case IntToPointer: 16074 if (getLangOpts().CPlusPlus) { 16075 DiagKind = diag::err_typecheck_convert_int_pointer; 16076 isInvalid = true; 16077 } else { 16078 DiagKind = diag::ext_typecheck_convert_int_pointer; 16079 } 16080 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16081 MayHaveConvFixit = true; 16082 break; 16083 case IncompatibleFunctionPointer: 16084 if (getLangOpts().CPlusPlus) { 16085 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 16086 isInvalid = true; 16087 } else { 16088 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 16089 } 16090 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16091 MayHaveConvFixit = true; 16092 break; 16093 case IncompatiblePointer: 16094 if (Action == AA_Passing_CFAudited) { 16095 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 16096 } else if (getLangOpts().CPlusPlus) { 16097 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 16098 isInvalid = true; 16099 } else { 16100 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 16101 } 16102 CheckInferredResultType = DstType->isObjCObjectPointerType() && 16103 SrcType->isObjCObjectPointerType(); 16104 if (!CheckInferredResultType) { 16105 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16106 } else if (CheckInferredResultType) { 16107 SrcType = SrcType.getUnqualifiedType(); 16108 DstType = DstType.getUnqualifiedType(); 16109 } 16110 MayHaveConvFixit = true; 16111 break; 16112 case IncompatiblePointerSign: 16113 if (getLangOpts().CPlusPlus) { 16114 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 16115 isInvalid = true; 16116 } else { 16117 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 16118 } 16119 break; 16120 case FunctionVoidPointer: 16121 if (getLangOpts().CPlusPlus) { 16122 DiagKind = diag::err_typecheck_convert_pointer_void_func; 16123 isInvalid = true; 16124 } else { 16125 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 16126 } 16127 break; 16128 case IncompatiblePointerDiscardsQualifiers: { 16129 // Perform array-to-pointer decay if necessary. 16130 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 16131 16132 isInvalid = true; 16133 16134 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 16135 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 16136 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 16137 DiagKind = diag::err_typecheck_incompatible_address_space; 16138 break; 16139 16140 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 16141 DiagKind = diag::err_typecheck_incompatible_ownership; 16142 break; 16143 } 16144 16145 llvm_unreachable("unknown error case for discarding qualifiers!"); 16146 // fallthrough 16147 } 16148 case CompatiblePointerDiscardsQualifiers: 16149 // If the qualifiers lost were because we were applying the 16150 // (deprecated) C++ conversion from a string literal to a char* 16151 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 16152 // Ideally, this check would be performed in 16153 // checkPointerTypesForAssignment. However, that would require a 16154 // bit of refactoring (so that the second argument is an 16155 // expression, rather than a type), which should be done as part 16156 // of a larger effort to fix checkPointerTypesForAssignment for 16157 // C++ semantics. 16158 if (getLangOpts().CPlusPlus && 16159 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 16160 return false; 16161 if (getLangOpts().CPlusPlus) { 16162 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 16163 isInvalid = true; 16164 } else { 16165 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 16166 } 16167 16168 break; 16169 case IncompatibleNestedPointerQualifiers: 16170 if (getLangOpts().CPlusPlus) { 16171 isInvalid = true; 16172 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 16173 } else { 16174 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16175 } 16176 break; 16177 case IncompatibleNestedPointerAddressSpaceMismatch: 16178 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16179 isInvalid = true; 16180 break; 16181 case IntToBlockPointer: 16182 DiagKind = diag::err_int_to_block_pointer; 16183 isInvalid = true; 16184 break; 16185 case IncompatibleBlockPointer: 16186 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16187 isInvalid = true; 16188 break; 16189 case IncompatibleObjCQualifiedId: { 16190 if (SrcType->isObjCQualifiedIdType()) { 16191 const ObjCObjectPointerType *srcOPT = 16192 SrcType->castAs<ObjCObjectPointerType>(); 16193 for (auto *srcProto : srcOPT->quals()) { 16194 PDecl = srcProto; 16195 break; 16196 } 16197 if (const ObjCInterfaceType *IFaceT = 16198 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16199 IFace = IFaceT->getDecl(); 16200 } 16201 else if (DstType->isObjCQualifiedIdType()) { 16202 const ObjCObjectPointerType *dstOPT = 16203 DstType->castAs<ObjCObjectPointerType>(); 16204 for (auto *dstProto : dstOPT->quals()) { 16205 PDecl = dstProto; 16206 break; 16207 } 16208 if (const ObjCInterfaceType *IFaceT = 16209 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16210 IFace = IFaceT->getDecl(); 16211 } 16212 if (getLangOpts().CPlusPlus) { 16213 DiagKind = diag::err_incompatible_qualified_id; 16214 isInvalid = true; 16215 } else { 16216 DiagKind = diag::warn_incompatible_qualified_id; 16217 } 16218 break; 16219 } 16220 case IncompatibleVectors: 16221 if (getLangOpts().CPlusPlus) { 16222 DiagKind = diag::err_incompatible_vectors; 16223 isInvalid = true; 16224 } else { 16225 DiagKind = diag::warn_incompatible_vectors; 16226 } 16227 break; 16228 case IncompatibleObjCWeakRef: 16229 DiagKind = diag::err_arc_weak_unavailable_assign; 16230 isInvalid = true; 16231 break; 16232 case Incompatible: 16233 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16234 if (Complained) 16235 *Complained = true; 16236 return true; 16237 } 16238 16239 DiagKind = diag::err_typecheck_convert_incompatible; 16240 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16241 MayHaveConvFixit = true; 16242 isInvalid = true; 16243 MayHaveFunctionDiff = true; 16244 break; 16245 } 16246 16247 QualType FirstType, SecondType; 16248 switch (Action) { 16249 case AA_Assigning: 16250 case AA_Initializing: 16251 // The destination type comes first. 16252 FirstType = DstType; 16253 SecondType = SrcType; 16254 break; 16255 16256 case AA_Returning: 16257 case AA_Passing: 16258 case AA_Passing_CFAudited: 16259 case AA_Converting: 16260 case AA_Sending: 16261 case AA_Casting: 16262 // The source type comes first. 16263 FirstType = SrcType; 16264 SecondType = DstType; 16265 break; 16266 } 16267 16268 PartialDiagnostic FDiag = PDiag(DiagKind); 16269 if (Action == AA_Passing_CFAudited) 16270 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16271 else 16272 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16273 16274 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16275 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16276 auto isPlainChar = [](const clang::Type *Type) { 16277 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16278 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16279 }; 16280 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16281 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16282 } 16283 16284 // If we can fix the conversion, suggest the FixIts. 16285 if (!ConvHints.isNull()) { 16286 for (FixItHint &H : ConvHints.Hints) 16287 FDiag << H; 16288 } 16289 16290 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16291 16292 if (MayHaveFunctionDiff) 16293 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16294 16295 Diag(Loc, FDiag); 16296 if ((DiagKind == diag::warn_incompatible_qualified_id || 16297 DiagKind == diag::err_incompatible_qualified_id) && 16298 PDecl && IFace && !IFace->hasDefinition()) 16299 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16300 << IFace << PDecl; 16301 16302 if (SecondType == Context.OverloadTy) 16303 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16304 FirstType, /*TakingAddress=*/true); 16305 16306 if (CheckInferredResultType) 16307 EmitRelatedResultTypeNote(SrcExpr); 16308 16309 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16310 EmitRelatedResultTypeNoteForReturn(DstType); 16311 16312 if (Complained) 16313 *Complained = true; 16314 return isInvalid; 16315 } 16316 16317 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16318 llvm::APSInt *Result, 16319 AllowFoldKind CanFold) { 16320 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16321 public: 16322 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16323 QualType T) override { 16324 return S.Diag(Loc, diag::err_ice_not_integral) 16325 << T << S.LangOpts.CPlusPlus; 16326 } 16327 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16328 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16329 } 16330 } Diagnoser; 16331 16332 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16333 } 16334 16335 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16336 llvm::APSInt *Result, 16337 unsigned DiagID, 16338 AllowFoldKind CanFold) { 16339 class IDDiagnoser : public VerifyICEDiagnoser { 16340 unsigned DiagID; 16341 16342 public: 16343 IDDiagnoser(unsigned DiagID) 16344 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16345 16346 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16347 return S.Diag(Loc, DiagID); 16348 } 16349 } Diagnoser(DiagID); 16350 16351 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16352 } 16353 16354 Sema::SemaDiagnosticBuilder 16355 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16356 QualType T) { 16357 return diagnoseNotICE(S, Loc); 16358 } 16359 16360 Sema::SemaDiagnosticBuilder 16361 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16362 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16363 } 16364 16365 ExprResult 16366 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16367 VerifyICEDiagnoser &Diagnoser, 16368 AllowFoldKind CanFold) { 16369 SourceLocation DiagLoc = E->getBeginLoc(); 16370 16371 if (getLangOpts().CPlusPlus11) { 16372 // C++11 [expr.const]p5: 16373 // If an expression of literal class type is used in a context where an 16374 // integral constant expression is required, then that class type shall 16375 // have a single non-explicit conversion function to an integral or 16376 // unscoped enumeration type 16377 ExprResult Converted; 16378 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16379 VerifyICEDiagnoser &BaseDiagnoser; 16380 public: 16381 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16382 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16383 BaseDiagnoser.Suppress, true), 16384 BaseDiagnoser(BaseDiagnoser) {} 16385 16386 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16387 QualType T) override { 16388 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16389 } 16390 16391 SemaDiagnosticBuilder diagnoseIncomplete( 16392 Sema &S, SourceLocation Loc, QualType T) override { 16393 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16394 } 16395 16396 SemaDiagnosticBuilder diagnoseExplicitConv( 16397 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16398 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16399 } 16400 16401 SemaDiagnosticBuilder noteExplicitConv( 16402 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16403 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16404 << ConvTy->isEnumeralType() << ConvTy; 16405 } 16406 16407 SemaDiagnosticBuilder diagnoseAmbiguous( 16408 Sema &S, SourceLocation Loc, QualType T) override { 16409 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16410 } 16411 16412 SemaDiagnosticBuilder noteAmbiguous( 16413 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16414 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16415 << ConvTy->isEnumeralType() << ConvTy; 16416 } 16417 16418 SemaDiagnosticBuilder diagnoseConversion( 16419 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16420 llvm_unreachable("conversion functions are permitted"); 16421 } 16422 } ConvertDiagnoser(Diagnoser); 16423 16424 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16425 ConvertDiagnoser); 16426 if (Converted.isInvalid()) 16427 return Converted; 16428 E = Converted.get(); 16429 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16430 return ExprError(); 16431 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16432 // An ICE must be of integral or unscoped enumeration type. 16433 if (!Diagnoser.Suppress) 16434 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16435 << E->getSourceRange(); 16436 return ExprError(); 16437 } 16438 16439 ExprResult RValueExpr = DefaultLvalueConversion(E); 16440 if (RValueExpr.isInvalid()) 16441 return ExprError(); 16442 16443 E = RValueExpr.get(); 16444 16445 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16446 // in the non-ICE case. 16447 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16448 if (Result) 16449 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16450 if (!isa<ConstantExpr>(E)) 16451 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16452 : ConstantExpr::Create(Context, E); 16453 return E; 16454 } 16455 16456 Expr::EvalResult EvalResult; 16457 SmallVector<PartialDiagnosticAt, 8> Notes; 16458 EvalResult.Diag = &Notes; 16459 16460 // Try to evaluate the expression, and produce diagnostics explaining why it's 16461 // not a constant expression as a side-effect. 16462 bool Folded = 16463 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16464 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16465 16466 if (!isa<ConstantExpr>(E)) 16467 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16468 16469 // In C++11, we can rely on diagnostics being produced for any expression 16470 // which is not a constant expression. If no diagnostics were produced, then 16471 // this is a constant expression. 16472 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16473 if (Result) 16474 *Result = EvalResult.Val.getInt(); 16475 return E; 16476 } 16477 16478 // If our only note is the usual "invalid subexpression" note, just point 16479 // the caret at its location rather than producing an essentially 16480 // redundant note. 16481 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16482 diag::note_invalid_subexpr_in_const_expr) { 16483 DiagLoc = Notes[0].first; 16484 Notes.clear(); 16485 } 16486 16487 if (!Folded || !CanFold) { 16488 if (!Diagnoser.Suppress) { 16489 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16490 for (const PartialDiagnosticAt &Note : Notes) 16491 Diag(Note.first, Note.second); 16492 } 16493 16494 return ExprError(); 16495 } 16496 16497 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16498 for (const PartialDiagnosticAt &Note : Notes) 16499 Diag(Note.first, Note.second); 16500 16501 if (Result) 16502 *Result = EvalResult.Val.getInt(); 16503 return E; 16504 } 16505 16506 namespace { 16507 // Handle the case where we conclude a expression which we speculatively 16508 // considered to be unevaluated is actually evaluated. 16509 class TransformToPE : public TreeTransform<TransformToPE> { 16510 typedef TreeTransform<TransformToPE> BaseTransform; 16511 16512 public: 16513 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16514 16515 // Make sure we redo semantic analysis 16516 bool AlwaysRebuild() { return true; } 16517 bool ReplacingOriginal() { return true; } 16518 16519 // We need to special-case DeclRefExprs referring to FieldDecls which 16520 // are not part of a member pointer formation; normal TreeTransforming 16521 // doesn't catch this case because of the way we represent them in the AST. 16522 // FIXME: This is a bit ugly; is it really the best way to handle this 16523 // case? 16524 // 16525 // Error on DeclRefExprs referring to FieldDecls. 16526 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16527 if (isa<FieldDecl>(E->getDecl()) && 16528 !SemaRef.isUnevaluatedContext()) 16529 return SemaRef.Diag(E->getLocation(), 16530 diag::err_invalid_non_static_member_use) 16531 << E->getDecl() << E->getSourceRange(); 16532 16533 return BaseTransform::TransformDeclRefExpr(E); 16534 } 16535 16536 // Exception: filter out member pointer formation 16537 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16538 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16539 return E; 16540 16541 return BaseTransform::TransformUnaryOperator(E); 16542 } 16543 16544 // The body of a lambda-expression is in a separate expression evaluation 16545 // context so never needs to be transformed. 16546 // FIXME: Ideally we wouldn't transform the closure type either, and would 16547 // just recreate the capture expressions and lambda expression. 16548 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16549 return SkipLambdaBody(E, Body); 16550 } 16551 }; 16552 } 16553 16554 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16555 assert(isUnevaluatedContext() && 16556 "Should only transform unevaluated expressions"); 16557 ExprEvalContexts.back().Context = 16558 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16559 if (isUnevaluatedContext()) 16560 return E; 16561 return TransformToPE(*this).TransformExpr(E); 16562 } 16563 16564 void 16565 Sema::PushExpressionEvaluationContext( 16566 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16567 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16568 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16569 LambdaContextDecl, ExprContext); 16570 Cleanup.reset(); 16571 if (!MaybeODRUseExprs.empty()) 16572 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16573 } 16574 16575 void 16576 Sema::PushExpressionEvaluationContext( 16577 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16578 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16579 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16580 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16581 } 16582 16583 namespace { 16584 16585 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16586 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16587 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16588 if (E->getOpcode() == UO_Deref) 16589 return CheckPossibleDeref(S, E->getSubExpr()); 16590 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16591 return CheckPossibleDeref(S, E->getBase()); 16592 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16593 return CheckPossibleDeref(S, E->getBase()); 16594 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16595 QualType Inner; 16596 QualType Ty = E->getType(); 16597 if (const auto *Ptr = Ty->getAs<PointerType>()) 16598 Inner = Ptr->getPointeeType(); 16599 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16600 Inner = Arr->getElementType(); 16601 else 16602 return nullptr; 16603 16604 if (Inner->hasAttr(attr::NoDeref)) 16605 return E; 16606 } 16607 return nullptr; 16608 } 16609 16610 } // namespace 16611 16612 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16613 for (const Expr *E : Rec.PossibleDerefs) { 16614 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16615 if (DeclRef) { 16616 const ValueDecl *Decl = DeclRef->getDecl(); 16617 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16618 << Decl->getName() << E->getSourceRange(); 16619 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16620 } else { 16621 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16622 << E->getSourceRange(); 16623 } 16624 } 16625 Rec.PossibleDerefs.clear(); 16626 } 16627 16628 /// Check whether E, which is either a discarded-value expression or an 16629 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16630 /// and if so, remove it from the list of volatile-qualified assignments that 16631 /// we are going to warn are deprecated. 16632 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16633 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16634 return; 16635 16636 // Note: ignoring parens here is not justified by the standard rules, but 16637 // ignoring parentheses seems like a more reasonable approach, and this only 16638 // drives a deprecation warning so doesn't affect conformance. 16639 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16640 if (BO->getOpcode() == BO_Assign) { 16641 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16642 llvm::erase_value(LHSs, BO->getLHS()); 16643 } 16644 } 16645 } 16646 16647 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16648 if (isUnevaluatedContext() || !E.isUsable() || !Decl || 16649 !Decl->isConsteval() || isConstantEvaluated() || 16650 RebuildingImmediateInvocation || isImmediateFunctionContext()) 16651 return E; 16652 16653 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16654 /// It's OK if this fails; we'll also remove this in 16655 /// HandleImmediateInvocations, but catching it here allows us to avoid 16656 /// walking the AST looking for it in simple cases. 16657 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16658 if (auto *DeclRef = 16659 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16660 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16661 16662 E = MaybeCreateExprWithCleanups(E); 16663 16664 ConstantExpr *Res = ConstantExpr::Create( 16665 getASTContext(), E.get(), 16666 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16667 getASTContext()), 16668 /*IsImmediateInvocation*/ true); 16669 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16670 return Res; 16671 } 16672 16673 static void EvaluateAndDiagnoseImmediateInvocation( 16674 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16675 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16676 Expr::EvalResult Eval; 16677 Eval.Diag = &Notes; 16678 ConstantExpr *CE = Candidate.getPointer(); 16679 bool Result = CE->EvaluateAsConstantExpr( 16680 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16681 if (!Result || !Notes.empty()) { 16682 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16683 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16684 InnerExpr = FunctionalCast->getSubExpr(); 16685 FunctionDecl *FD = nullptr; 16686 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16687 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16688 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16689 FD = Call->getConstructor(); 16690 else 16691 llvm_unreachable("unhandled decl kind"); 16692 assert(FD->isConsteval()); 16693 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16694 for (auto &Note : Notes) 16695 SemaRef.Diag(Note.first, Note.second); 16696 return; 16697 } 16698 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16699 } 16700 16701 static void RemoveNestedImmediateInvocation( 16702 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16703 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16704 struct ComplexRemove : TreeTransform<ComplexRemove> { 16705 using Base = TreeTransform<ComplexRemove>; 16706 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16707 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16708 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16709 CurrentII; 16710 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16711 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16712 SmallVector<Sema::ImmediateInvocationCandidate, 16713 4>::reverse_iterator Current) 16714 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16715 void RemoveImmediateInvocation(ConstantExpr* E) { 16716 auto It = std::find_if(CurrentII, IISet.rend(), 16717 [E](Sema::ImmediateInvocationCandidate Elem) { 16718 return Elem.getPointer() == E; 16719 }); 16720 assert(It != IISet.rend() && 16721 "ConstantExpr marked IsImmediateInvocation should " 16722 "be present"); 16723 It->setInt(1); // Mark as deleted 16724 } 16725 ExprResult TransformConstantExpr(ConstantExpr *E) { 16726 if (!E->isImmediateInvocation()) 16727 return Base::TransformConstantExpr(E); 16728 RemoveImmediateInvocation(E); 16729 return Base::TransformExpr(E->getSubExpr()); 16730 } 16731 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16732 /// we need to remove its DeclRefExpr from the DRSet. 16733 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16734 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16735 return Base::TransformCXXOperatorCallExpr(E); 16736 } 16737 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16738 /// here. 16739 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16740 if (!Init) 16741 return Init; 16742 /// ConstantExpr are the first layer of implicit node to be removed so if 16743 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16744 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16745 if (CE->isImmediateInvocation()) 16746 RemoveImmediateInvocation(CE); 16747 return Base::TransformInitializer(Init, NotCopyInit); 16748 } 16749 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16750 DRSet.erase(E); 16751 return E; 16752 } 16753 bool AlwaysRebuild() { return false; } 16754 bool ReplacingOriginal() { return true; } 16755 bool AllowSkippingCXXConstructExpr() { 16756 bool Res = AllowSkippingFirstCXXConstructExpr; 16757 AllowSkippingFirstCXXConstructExpr = true; 16758 return Res; 16759 } 16760 bool AllowSkippingFirstCXXConstructExpr = true; 16761 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16762 Rec.ImmediateInvocationCandidates, It); 16763 16764 /// CXXConstructExpr with a single argument are getting skipped by 16765 /// TreeTransform in some situtation because they could be implicit. This 16766 /// can only occur for the top-level CXXConstructExpr because it is used 16767 /// nowhere in the expression being transformed therefore will not be rebuilt. 16768 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16769 /// skipping the first CXXConstructExpr. 16770 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16771 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16772 16773 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16774 assert(Res.isUsable()); 16775 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16776 It->getPointer()->setSubExpr(Res.get()); 16777 } 16778 16779 static void 16780 HandleImmediateInvocations(Sema &SemaRef, 16781 Sema::ExpressionEvaluationContextRecord &Rec) { 16782 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16783 Rec.ReferenceToConsteval.size() == 0) || 16784 SemaRef.RebuildingImmediateInvocation) 16785 return; 16786 16787 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16788 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16789 /// need to remove ReferenceToConsteval in the immediate invocation. 16790 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16791 16792 /// Prevent sema calls during the tree transform from adding pointers that 16793 /// are already in the sets. 16794 llvm::SaveAndRestore<bool> DisableIITracking( 16795 SemaRef.RebuildingImmediateInvocation, true); 16796 16797 /// Prevent diagnostic during tree transfrom as they are duplicates 16798 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16799 16800 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16801 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16802 if (!It->getInt()) 16803 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16804 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16805 Rec.ReferenceToConsteval.size()) { 16806 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16807 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16808 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16809 bool VisitDeclRefExpr(DeclRefExpr *E) { 16810 DRSet.erase(E); 16811 return DRSet.size(); 16812 } 16813 } Visitor(Rec.ReferenceToConsteval); 16814 Visitor.TraverseStmt( 16815 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16816 } 16817 for (auto CE : Rec.ImmediateInvocationCandidates) 16818 if (!CE.getInt()) 16819 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16820 for (auto DR : Rec.ReferenceToConsteval) { 16821 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16822 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16823 << FD; 16824 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16825 } 16826 } 16827 16828 void Sema::PopExpressionEvaluationContext() { 16829 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16830 unsigned NumTypos = Rec.NumTypos; 16831 16832 if (!Rec.Lambdas.empty()) { 16833 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16834 if (!getLangOpts().CPlusPlus20 && 16835 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 16836 Rec.isUnevaluated() || 16837 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 16838 unsigned D; 16839 if (Rec.isUnevaluated()) { 16840 // C++11 [expr.prim.lambda]p2: 16841 // A lambda-expression shall not appear in an unevaluated operand 16842 // (Clause 5). 16843 D = diag::err_lambda_unevaluated_operand; 16844 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16845 // C++1y [expr.const]p2: 16846 // A conditional-expression e is a core constant expression unless the 16847 // evaluation of e, following the rules of the abstract machine, would 16848 // evaluate [...] a lambda-expression. 16849 D = diag::err_lambda_in_constant_expression; 16850 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16851 // C++17 [expr.prim.lamda]p2: 16852 // A lambda-expression shall not appear [...] in a template-argument. 16853 D = diag::err_lambda_in_invalid_context; 16854 } else 16855 llvm_unreachable("Couldn't infer lambda error message."); 16856 16857 for (const auto *L : Rec.Lambdas) 16858 Diag(L->getBeginLoc(), D); 16859 } 16860 } 16861 16862 WarnOnPendingNoDerefs(Rec); 16863 HandleImmediateInvocations(*this, Rec); 16864 16865 // Warn on any volatile-qualified simple-assignments that are not discarded- 16866 // value expressions nor unevaluated operands (those cases get removed from 16867 // this list by CheckUnusedVolatileAssignment). 16868 for (auto *BO : Rec.VolatileAssignmentLHSs) 16869 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16870 << BO->getType(); 16871 16872 // When are coming out of an unevaluated context, clear out any 16873 // temporaries that we may have created as part of the evaluation of 16874 // the expression in that context: they aren't relevant because they 16875 // will never be constructed. 16876 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16877 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16878 ExprCleanupObjects.end()); 16879 Cleanup = Rec.ParentCleanup; 16880 CleanupVarDeclMarking(); 16881 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16882 // Otherwise, merge the contexts together. 16883 } else { 16884 Cleanup.mergeFrom(Rec.ParentCleanup); 16885 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16886 Rec.SavedMaybeODRUseExprs.end()); 16887 } 16888 16889 // Pop the current expression evaluation context off the stack. 16890 ExprEvalContexts.pop_back(); 16891 16892 // The global expression evaluation context record is never popped. 16893 ExprEvalContexts.back().NumTypos += NumTypos; 16894 } 16895 16896 void Sema::DiscardCleanupsInEvaluationContext() { 16897 ExprCleanupObjects.erase( 16898 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16899 ExprCleanupObjects.end()); 16900 Cleanup.reset(); 16901 MaybeODRUseExprs.clear(); 16902 } 16903 16904 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16905 ExprResult Result = CheckPlaceholderExpr(E); 16906 if (Result.isInvalid()) 16907 return ExprError(); 16908 E = Result.get(); 16909 if (!E->getType()->isVariablyModifiedType()) 16910 return E; 16911 return TransformToPotentiallyEvaluated(E); 16912 } 16913 16914 /// Are we in a context that is potentially constant evaluated per C++20 16915 /// [expr.const]p12? 16916 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16917 /// C++2a [expr.const]p12: 16918 // An expression or conversion is potentially constant evaluated if it is 16919 switch (SemaRef.ExprEvalContexts.back().Context) { 16920 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16921 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 16922 16923 // -- a manifestly constant-evaluated expression, 16924 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16925 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16926 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16927 // -- a potentially-evaluated expression, 16928 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16929 // -- an immediate subexpression of a braced-init-list, 16930 16931 // -- [FIXME] an expression of the form & cast-expression that occurs 16932 // within a templated entity 16933 // -- a subexpression of one of the above that is not a subexpression of 16934 // a nested unevaluated operand. 16935 return true; 16936 16937 case Sema::ExpressionEvaluationContext::Unevaluated: 16938 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16939 // Expressions in this context are never evaluated. 16940 return false; 16941 } 16942 llvm_unreachable("Invalid context"); 16943 } 16944 16945 /// Return true if this function has a calling convention that requires mangling 16946 /// in the size of the parameter pack. 16947 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16948 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16949 // we don't need parameter type sizes. 16950 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16951 if (!TT.isOSWindows() || !TT.isX86()) 16952 return false; 16953 16954 // If this is C++ and this isn't an extern "C" function, parameters do not 16955 // need to be complete. In this case, C++ mangling will apply, which doesn't 16956 // use the size of the parameters. 16957 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16958 return false; 16959 16960 // Stdcall, fastcall, and vectorcall need this special treatment. 16961 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16962 switch (CC) { 16963 case CC_X86StdCall: 16964 case CC_X86FastCall: 16965 case CC_X86VectorCall: 16966 return true; 16967 default: 16968 break; 16969 } 16970 return false; 16971 } 16972 16973 /// Require that all of the parameter types of function be complete. Normally, 16974 /// parameter types are only required to be complete when a function is called 16975 /// or defined, but to mangle functions with certain calling conventions, the 16976 /// mangler needs to know the size of the parameter list. In this situation, 16977 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16978 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16979 /// result in a linker error. Clang doesn't implement this behavior, and instead 16980 /// attempts to error at compile time. 16981 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16982 SourceLocation Loc) { 16983 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16984 FunctionDecl *FD; 16985 ParmVarDecl *Param; 16986 16987 public: 16988 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16989 : FD(FD), Param(Param) {} 16990 16991 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16992 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16993 StringRef CCName; 16994 switch (CC) { 16995 case CC_X86StdCall: 16996 CCName = "stdcall"; 16997 break; 16998 case CC_X86FastCall: 16999 CCName = "fastcall"; 17000 break; 17001 case CC_X86VectorCall: 17002 CCName = "vectorcall"; 17003 break; 17004 default: 17005 llvm_unreachable("CC does not need mangling"); 17006 } 17007 17008 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 17009 << Param->getDeclName() << FD->getDeclName() << CCName; 17010 } 17011 }; 17012 17013 for (ParmVarDecl *Param : FD->parameters()) { 17014 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 17015 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 17016 } 17017 } 17018 17019 namespace { 17020 enum class OdrUseContext { 17021 /// Declarations in this context are not odr-used. 17022 None, 17023 /// Declarations in this context are formally odr-used, but this is a 17024 /// dependent context. 17025 Dependent, 17026 /// Declarations in this context are odr-used but not actually used (yet). 17027 FormallyOdrUsed, 17028 /// Declarations in this context are used. 17029 Used 17030 }; 17031 } 17032 17033 /// Are we within a context in which references to resolved functions or to 17034 /// variables result in odr-use? 17035 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 17036 OdrUseContext Result; 17037 17038 switch (SemaRef.ExprEvalContexts.back().Context) { 17039 case Sema::ExpressionEvaluationContext::Unevaluated: 17040 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17041 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17042 return OdrUseContext::None; 17043 17044 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17045 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 17046 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17047 Result = OdrUseContext::Used; 17048 break; 17049 17050 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17051 Result = OdrUseContext::FormallyOdrUsed; 17052 break; 17053 17054 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17055 // A default argument formally results in odr-use, but doesn't actually 17056 // result in a use in any real sense until it itself is used. 17057 Result = OdrUseContext::FormallyOdrUsed; 17058 break; 17059 } 17060 17061 if (SemaRef.CurContext->isDependentContext()) 17062 return OdrUseContext::Dependent; 17063 17064 return Result; 17065 } 17066 17067 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 17068 if (!Func->isConstexpr()) 17069 return false; 17070 17071 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 17072 return true; 17073 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 17074 return CCD && CCD->getInheritedConstructor(); 17075 } 17076 17077 /// Mark a function referenced, and check whether it is odr-used 17078 /// (C++ [basic.def.odr]p2, C99 6.9p3) 17079 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 17080 bool MightBeOdrUse) { 17081 assert(Func && "No function?"); 17082 17083 Func->setReferenced(); 17084 17085 // Recursive functions aren't really used until they're used from some other 17086 // context. 17087 bool IsRecursiveCall = CurContext == Func; 17088 17089 // C++11 [basic.def.odr]p3: 17090 // A function whose name appears as a potentially-evaluated expression is 17091 // odr-used if it is the unique lookup result or the selected member of a 17092 // set of overloaded functions [...]. 17093 // 17094 // We (incorrectly) mark overload resolution as an unevaluated context, so we 17095 // can just check that here. 17096 OdrUseContext OdrUse = 17097 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 17098 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 17099 OdrUse = OdrUseContext::FormallyOdrUsed; 17100 17101 // Trivial default constructors and destructors are never actually used. 17102 // FIXME: What about other special members? 17103 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 17104 OdrUse == OdrUseContext::Used) { 17105 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 17106 if (Constructor->isDefaultConstructor()) 17107 OdrUse = OdrUseContext::FormallyOdrUsed; 17108 if (isa<CXXDestructorDecl>(Func)) 17109 OdrUse = OdrUseContext::FormallyOdrUsed; 17110 } 17111 17112 // C++20 [expr.const]p12: 17113 // A function [...] is needed for constant evaluation if it is [...] a 17114 // constexpr function that is named by an expression that is potentially 17115 // constant evaluated 17116 bool NeededForConstantEvaluation = 17117 isPotentiallyConstantEvaluatedContext(*this) && 17118 isImplicitlyDefinableConstexprFunction(Func); 17119 17120 // Determine whether we require a function definition to exist, per 17121 // C++11 [temp.inst]p3: 17122 // Unless a function template specialization has been explicitly 17123 // instantiated or explicitly specialized, the function template 17124 // specialization is implicitly instantiated when the specialization is 17125 // referenced in a context that requires a function definition to exist. 17126 // C++20 [temp.inst]p7: 17127 // The existence of a definition of a [...] function is considered to 17128 // affect the semantics of the program if the [...] function is needed for 17129 // constant evaluation by an expression 17130 // C++20 [basic.def.odr]p10: 17131 // Every program shall contain exactly one definition of every non-inline 17132 // function or variable that is odr-used in that program outside of a 17133 // discarded statement 17134 // C++20 [special]p1: 17135 // The implementation will implicitly define [defaulted special members] 17136 // if they are odr-used or needed for constant evaluation. 17137 // 17138 // Note that we skip the implicit instantiation of templates that are only 17139 // used in unused default arguments or by recursive calls to themselves. 17140 // This is formally non-conforming, but seems reasonable in practice. 17141 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 17142 NeededForConstantEvaluation); 17143 17144 // C++14 [temp.expl.spec]p6: 17145 // If a template [...] is explicitly specialized then that specialization 17146 // shall be declared before the first use of that specialization that would 17147 // cause an implicit instantiation to take place, in every translation unit 17148 // in which such a use occurs 17149 if (NeedDefinition && 17150 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 17151 Func->getMemberSpecializationInfo())) 17152 checkSpecializationVisibility(Loc, Func); 17153 17154 if (getLangOpts().CUDA) 17155 CheckCUDACall(Loc, Func); 17156 17157 if (getLangOpts().SYCLIsDevice) 17158 checkSYCLDeviceFunction(Loc, Func); 17159 17160 // If we need a definition, try to create one. 17161 if (NeedDefinition && !Func->getBody()) { 17162 runWithSufficientStackSpace(Loc, [&] { 17163 if (CXXConstructorDecl *Constructor = 17164 dyn_cast<CXXConstructorDecl>(Func)) { 17165 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 17166 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 17167 if (Constructor->isDefaultConstructor()) { 17168 if (Constructor->isTrivial() && 17169 !Constructor->hasAttr<DLLExportAttr>()) 17170 return; 17171 DefineImplicitDefaultConstructor(Loc, Constructor); 17172 } else if (Constructor->isCopyConstructor()) { 17173 DefineImplicitCopyConstructor(Loc, Constructor); 17174 } else if (Constructor->isMoveConstructor()) { 17175 DefineImplicitMoveConstructor(Loc, Constructor); 17176 } 17177 } else if (Constructor->getInheritedConstructor()) { 17178 DefineInheritingConstructor(Loc, Constructor); 17179 } 17180 } else if (CXXDestructorDecl *Destructor = 17181 dyn_cast<CXXDestructorDecl>(Func)) { 17182 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17183 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17184 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17185 return; 17186 DefineImplicitDestructor(Loc, Destructor); 17187 } 17188 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17189 MarkVTableUsed(Loc, Destructor->getParent()); 17190 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17191 if (MethodDecl->isOverloadedOperator() && 17192 MethodDecl->getOverloadedOperator() == OO_Equal) { 17193 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17194 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17195 if (MethodDecl->isCopyAssignmentOperator()) 17196 DefineImplicitCopyAssignment(Loc, MethodDecl); 17197 else if (MethodDecl->isMoveAssignmentOperator()) 17198 DefineImplicitMoveAssignment(Loc, MethodDecl); 17199 } 17200 } else if (isa<CXXConversionDecl>(MethodDecl) && 17201 MethodDecl->getParent()->isLambda()) { 17202 CXXConversionDecl *Conversion = 17203 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17204 if (Conversion->isLambdaToBlockPointerConversion()) 17205 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17206 else 17207 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17208 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17209 MarkVTableUsed(Loc, MethodDecl->getParent()); 17210 } 17211 17212 if (Func->isDefaulted() && !Func->isDeleted()) { 17213 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17214 if (DCK != DefaultedComparisonKind::None) 17215 DefineDefaultedComparison(Loc, Func, DCK); 17216 } 17217 17218 // Implicit instantiation of function templates and member functions of 17219 // class templates. 17220 if (Func->isImplicitlyInstantiable()) { 17221 TemplateSpecializationKind TSK = 17222 Func->getTemplateSpecializationKindForInstantiation(); 17223 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17224 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17225 if (FirstInstantiation) { 17226 PointOfInstantiation = Loc; 17227 if (auto *MSI = Func->getMemberSpecializationInfo()) 17228 MSI->setPointOfInstantiation(Loc); 17229 // FIXME: Notify listener. 17230 else 17231 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17232 } else if (TSK != TSK_ImplicitInstantiation) { 17233 // Use the point of use as the point of instantiation, instead of the 17234 // point of explicit instantiation (which we track as the actual point 17235 // of instantiation). This gives better backtraces in diagnostics. 17236 PointOfInstantiation = Loc; 17237 } 17238 17239 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17240 Func->isConstexpr()) { 17241 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17242 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17243 CodeSynthesisContexts.size()) 17244 PendingLocalImplicitInstantiations.push_back( 17245 std::make_pair(Func, PointOfInstantiation)); 17246 else if (Func->isConstexpr()) 17247 // Do not defer instantiations of constexpr functions, to avoid the 17248 // expression evaluator needing to call back into Sema if it sees a 17249 // call to such a function. 17250 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17251 else { 17252 Func->setInstantiationIsPending(true); 17253 PendingInstantiations.push_back( 17254 std::make_pair(Func, PointOfInstantiation)); 17255 // Notify the consumer that a function was implicitly instantiated. 17256 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17257 } 17258 } 17259 } else { 17260 // Walk redefinitions, as some of them may be instantiable. 17261 for (auto i : Func->redecls()) { 17262 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17263 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17264 } 17265 } 17266 }); 17267 } 17268 17269 // C++14 [except.spec]p17: 17270 // An exception-specification is considered to be needed when: 17271 // - the function is odr-used or, if it appears in an unevaluated operand, 17272 // would be odr-used if the expression were potentially-evaluated; 17273 // 17274 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17275 // function is a pure virtual function we're calling, and in that case the 17276 // function was selected by overload resolution and we need to resolve its 17277 // exception specification for a different reason. 17278 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17279 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17280 ResolveExceptionSpec(Loc, FPT); 17281 17282 // If this is the first "real" use, act on that. 17283 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17284 // Keep track of used but undefined functions. 17285 if (!Func->isDefined()) { 17286 if (mightHaveNonExternalLinkage(Func)) 17287 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17288 else if (Func->getMostRecentDecl()->isInlined() && 17289 !LangOpts.GNUInline && 17290 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17291 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17292 else if (isExternalWithNoLinkageType(Func)) 17293 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17294 } 17295 17296 // Some x86 Windows calling conventions mangle the size of the parameter 17297 // pack into the name. Computing the size of the parameters requires the 17298 // parameter types to be complete. Check that now. 17299 if (funcHasParameterSizeMangling(*this, Func)) 17300 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17301 17302 // In the MS C++ ABI, the compiler emits destructor variants where they are 17303 // used. If the destructor is used here but defined elsewhere, mark the 17304 // virtual base destructors referenced. If those virtual base destructors 17305 // are inline, this will ensure they are defined when emitting the complete 17306 // destructor variant. This checking may be redundant if the destructor is 17307 // provided later in this TU. 17308 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17309 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17310 CXXRecordDecl *Parent = Dtor->getParent(); 17311 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17312 CheckCompleteDestructorVariant(Loc, Dtor); 17313 } 17314 } 17315 17316 Func->markUsed(Context); 17317 } 17318 } 17319 17320 /// Directly mark a variable odr-used. Given a choice, prefer to use 17321 /// MarkVariableReferenced since it does additional checks and then 17322 /// calls MarkVarDeclODRUsed. 17323 /// If the variable must be captured: 17324 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17325 /// - else capture it in the DeclContext that maps to the 17326 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17327 static void 17328 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17329 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17330 // Keep track of used but undefined variables. 17331 // FIXME: We shouldn't suppress this warning for static data members. 17332 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17333 (!Var->isExternallyVisible() || Var->isInline() || 17334 SemaRef.isExternalWithNoLinkageType(Var)) && 17335 !(Var->isStaticDataMember() && Var->hasInit())) { 17336 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17337 if (old.isInvalid()) 17338 old = Loc; 17339 } 17340 QualType CaptureType, DeclRefType; 17341 if (SemaRef.LangOpts.OpenMP) 17342 SemaRef.tryCaptureOpenMPLambdas(Var); 17343 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17344 /*EllipsisLoc*/ SourceLocation(), 17345 /*BuildAndDiagnose*/ true, 17346 CaptureType, DeclRefType, 17347 FunctionScopeIndexToStopAt); 17348 17349 if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) { 17350 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 17351 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 17352 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 17353 if (VarTarget == Sema::CVT_Host && 17354 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 17355 UserTarget == Sema::CFT_Global)) { 17356 // Diagnose ODR-use of host global variables in device functions. 17357 // Reference of device global variables in host functions is allowed 17358 // through shadow variables therefore it is not diagnosed. 17359 if (SemaRef.LangOpts.CUDAIsDevice) { 17360 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 17361 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 17362 SemaRef.targetDiag(Var->getLocation(), 17363 Var->getType().isConstQualified() 17364 ? diag::note_cuda_const_var_unpromoted 17365 : diag::note_cuda_host_var); 17366 } 17367 } else if (VarTarget == Sema::CVT_Device && 17368 (UserTarget == Sema::CFT_Host || 17369 UserTarget == Sema::CFT_HostDevice) && 17370 !Var->hasExternalStorage()) { 17371 // Record a CUDA/HIP device side variable if it is ODR-used 17372 // by host code. This is done conservatively, when the variable is 17373 // referenced in any of the following contexts: 17374 // - a non-function context 17375 // - a host function 17376 // - a host device function 17377 // This makes the ODR-use of the device side variable by host code to 17378 // be visible in the device compilation for the compiler to be able to 17379 // emit template variables instantiated by host code only and to 17380 // externalize the static device side variable ODR-used by host code. 17381 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 17382 } 17383 } 17384 17385 Var->markUsed(SemaRef.Context); 17386 } 17387 17388 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17389 SourceLocation Loc, 17390 unsigned CapturingScopeIndex) { 17391 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17392 } 17393 17394 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17395 ValueDecl *var) { 17396 DeclContext *VarDC = var->getDeclContext(); 17397 17398 // If the parameter still belongs to the translation unit, then 17399 // we're actually just using one parameter in the declaration of 17400 // the next. 17401 if (isa<ParmVarDecl>(var) && 17402 isa<TranslationUnitDecl>(VarDC)) 17403 return; 17404 17405 // For C code, don't diagnose about capture if we're not actually in code 17406 // right now; it's impossible to write a non-constant expression outside of 17407 // function context, so we'll get other (more useful) diagnostics later. 17408 // 17409 // For C++, things get a bit more nasty... it would be nice to suppress this 17410 // diagnostic for certain cases like using a local variable in an array bound 17411 // for a member of a local class, but the correct predicate is not obvious. 17412 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17413 return; 17414 17415 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17416 unsigned ContextKind = 3; // unknown 17417 if (isa<CXXMethodDecl>(VarDC) && 17418 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17419 ContextKind = 2; 17420 } else if (isa<FunctionDecl>(VarDC)) { 17421 ContextKind = 0; 17422 } else if (isa<BlockDecl>(VarDC)) { 17423 ContextKind = 1; 17424 } 17425 17426 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17427 << var << ValueKind << ContextKind << VarDC; 17428 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17429 << var; 17430 17431 // FIXME: Add additional diagnostic info about class etc. which prevents 17432 // capture. 17433 } 17434 17435 17436 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17437 bool &SubCapturesAreNested, 17438 QualType &CaptureType, 17439 QualType &DeclRefType) { 17440 // Check whether we've already captured it. 17441 if (CSI->CaptureMap.count(Var)) { 17442 // If we found a capture, any subcaptures are nested. 17443 SubCapturesAreNested = true; 17444 17445 // Retrieve the capture type for this variable. 17446 CaptureType = CSI->getCapture(Var).getCaptureType(); 17447 17448 // Compute the type of an expression that refers to this variable. 17449 DeclRefType = CaptureType.getNonReferenceType(); 17450 17451 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17452 // are mutable in the sense that user can change their value - they are 17453 // private instances of the captured declarations. 17454 const Capture &Cap = CSI->getCapture(Var); 17455 if (Cap.isCopyCapture() && 17456 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17457 !(isa<CapturedRegionScopeInfo>(CSI) && 17458 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17459 DeclRefType.addConst(); 17460 return true; 17461 } 17462 return false; 17463 } 17464 17465 // Only block literals, captured statements, and lambda expressions can 17466 // capture; other scopes don't work. 17467 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17468 SourceLocation Loc, 17469 const bool Diagnose, Sema &S) { 17470 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17471 return getLambdaAwareParentOfDeclContext(DC); 17472 else if (Var->hasLocalStorage()) { 17473 if (Diagnose) 17474 diagnoseUncapturableValueReference(S, Loc, Var); 17475 } 17476 return nullptr; 17477 } 17478 17479 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17480 // certain types of variables (unnamed, variably modified types etc.) 17481 // so check for eligibility. 17482 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17483 SourceLocation Loc, 17484 const bool Diagnose, Sema &S) { 17485 17486 bool IsBlock = isa<BlockScopeInfo>(CSI); 17487 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17488 17489 // Lambdas are not allowed to capture unnamed variables 17490 // (e.g. anonymous unions). 17491 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17492 // assuming that's the intent. 17493 if (IsLambda && !Var->getDeclName()) { 17494 if (Diagnose) { 17495 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17496 S.Diag(Var->getLocation(), diag::note_declared_at); 17497 } 17498 return false; 17499 } 17500 17501 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17502 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17503 if (Diagnose) { 17504 S.Diag(Loc, diag::err_ref_vm_type); 17505 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17506 } 17507 return false; 17508 } 17509 // Prohibit structs with flexible array members too. 17510 // We cannot capture what is in the tail end of the struct. 17511 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17512 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17513 if (Diagnose) { 17514 if (IsBlock) 17515 S.Diag(Loc, diag::err_ref_flexarray_type); 17516 else 17517 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17518 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17519 } 17520 return false; 17521 } 17522 } 17523 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17524 // Lambdas and captured statements are not allowed to capture __block 17525 // variables; they don't support the expected semantics. 17526 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17527 if (Diagnose) { 17528 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17529 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17530 } 17531 return false; 17532 } 17533 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17534 if (S.getLangOpts().OpenCL && IsBlock && 17535 Var->getType()->isBlockPointerType()) { 17536 if (Diagnose) 17537 S.Diag(Loc, diag::err_opencl_block_ref_block); 17538 return false; 17539 } 17540 17541 return true; 17542 } 17543 17544 // Returns true if the capture by block was successful. 17545 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17546 SourceLocation Loc, 17547 const bool BuildAndDiagnose, 17548 QualType &CaptureType, 17549 QualType &DeclRefType, 17550 const bool Nested, 17551 Sema &S, bool Invalid) { 17552 bool ByRef = false; 17553 17554 // Blocks are not allowed to capture arrays, excepting OpenCL. 17555 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17556 // (decayed to pointers). 17557 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17558 if (BuildAndDiagnose) { 17559 S.Diag(Loc, diag::err_ref_array_type); 17560 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17561 Invalid = true; 17562 } else { 17563 return false; 17564 } 17565 } 17566 17567 // Forbid the block-capture of autoreleasing variables. 17568 if (!Invalid && 17569 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17570 if (BuildAndDiagnose) { 17571 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17572 << /*block*/ 0; 17573 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17574 Invalid = true; 17575 } else { 17576 return false; 17577 } 17578 } 17579 17580 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17581 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17582 QualType PointeeTy = PT->getPointeeType(); 17583 17584 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17585 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17586 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17587 if (BuildAndDiagnose) { 17588 SourceLocation VarLoc = Var->getLocation(); 17589 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17590 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17591 } 17592 } 17593 } 17594 17595 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17596 if (HasBlocksAttr || CaptureType->isReferenceType() || 17597 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17598 // Block capture by reference does not change the capture or 17599 // declaration reference types. 17600 ByRef = true; 17601 } else { 17602 // Block capture by copy introduces 'const'. 17603 CaptureType = CaptureType.getNonReferenceType().withConst(); 17604 DeclRefType = CaptureType; 17605 } 17606 17607 // Actually capture the variable. 17608 if (BuildAndDiagnose) 17609 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17610 CaptureType, Invalid); 17611 17612 return !Invalid; 17613 } 17614 17615 17616 /// Capture the given variable in the captured region. 17617 static bool captureInCapturedRegion( 17618 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 17619 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 17620 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 17621 bool IsTopScope, Sema &S, bool Invalid) { 17622 // By default, capture variables by reference. 17623 bool ByRef = true; 17624 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17625 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17626 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17627 // Using an LValue reference type is consistent with Lambdas (see below). 17628 if (S.isOpenMPCapturedDecl(Var)) { 17629 bool HasConst = DeclRefType.isConstQualified(); 17630 DeclRefType = DeclRefType.getUnqualifiedType(); 17631 // Don't lose diagnostics about assignments to const. 17632 if (HasConst) 17633 DeclRefType.addConst(); 17634 } 17635 // Do not capture firstprivates in tasks. 17636 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17637 OMPC_unknown) 17638 return true; 17639 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17640 RSI->OpenMPCaptureLevel); 17641 } 17642 17643 if (ByRef) 17644 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17645 else 17646 CaptureType = DeclRefType; 17647 17648 // Actually capture the variable. 17649 if (BuildAndDiagnose) 17650 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17651 Loc, SourceLocation(), CaptureType, Invalid); 17652 17653 return !Invalid; 17654 } 17655 17656 /// Capture the given variable in the lambda. 17657 static bool captureInLambda(LambdaScopeInfo *LSI, 17658 VarDecl *Var, 17659 SourceLocation Loc, 17660 const bool BuildAndDiagnose, 17661 QualType &CaptureType, 17662 QualType &DeclRefType, 17663 const bool RefersToCapturedVariable, 17664 const Sema::TryCaptureKind Kind, 17665 SourceLocation EllipsisLoc, 17666 const bool IsTopScope, 17667 Sema &S, bool Invalid) { 17668 // Determine whether we are capturing by reference or by value. 17669 bool ByRef = false; 17670 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17671 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17672 } else { 17673 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17674 } 17675 17676 // Compute the type of the field that will capture this variable. 17677 if (ByRef) { 17678 // C++11 [expr.prim.lambda]p15: 17679 // An entity is captured by reference if it is implicitly or 17680 // explicitly captured but not captured by copy. It is 17681 // unspecified whether additional unnamed non-static data 17682 // members are declared in the closure type for entities 17683 // captured by reference. 17684 // 17685 // FIXME: It is not clear whether we want to build an lvalue reference 17686 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17687 // to do the former, while EDG does the latter. Core issue 1249 will 17688 // clarify, but for now we follow GCC because it's a more permissive and 17689 // easily defensible position. 17690 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17691 } else { 17692 // C++11 [expr.prim.lambda]p14: 17693 // For each entity captured by copy, an unnamed non-static 17694 // data member is declared in the closure type. The 17695 // declaration order of these members is unspecified. The type 17696 // of such a data member is the type of the corresponding 17697 // captured entity if the entity is not a reference to an 17698 // object, or the referenced type otherwise. [Note: If the 17699 // captured entity is a reference to a function, the 17700 // corresponding data member is also a reference to a 17701 // function. - end note ] 17702 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17703 if (!RefType->getPointeeType()->isFunctionType()) 17704 CaptureType = RefType->getPointeeType(); 17705 } 17706 17707 // Forbid the lambda copy-capture of autoreleasing variables. 17708 if (!Invalid && 17709 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17710 if (BuildAndDiagnose) { 17711 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17712 S.Diag(Var->getLocation(), diag::note_previous_decl) 17713 << Var->getDeclName(); 17714 Invalid = true; 17715 } else { 17716 return false; 17717 } 17718 } 17719 17720 // Make sure that by-copy captures are of a complete and non-abstract type. 17721 if (!Invalid && BuildAndDiagnose) { 17722 if (!CaptureType->isDependentType() && 17723 S.RequireCompleteSizedType( 17724 Loc, CaptureType, 17725 diag::err_capture_of_incomplete_or_sizeless_type, 17726 Var->getDeclName())) 17727 Invalid = true; 17728 else if (S.RequireNonAbstractType(Loc, CaptureType, 17729 diag::err_capture_of_abstract_type)) 17730 Invalid = true; 17731 } 17732 } 17733 17734 // Compute the type of a reference to this captured variable. 17735 if (ByRef) 17736 DeclRefType = CaptureType.getNonReferenceType(); 17737 else { 17738 // C++ [expr.prim.lambda]p5: 17739 // The closure type for a lambda-expression has a public inline 17740 // function call operator [...]. This function call operator is 17741 // declared const (9.3.1) if and only if the lambda-expression's 17742 // parameter-declaration-clause is not followed by mutable. 17743 DeclRefType = CaptureType.getNonReferenceType(); 17744 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17745 DeclRefType.addConst(); 17746 } 17747 17748 // Add the capture. 17749 if (BuildAndDiagnose) 17750 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17751 Loc, EllipsisLoc, CaptureType, Invalid); 17752 17753 return !Invalid; 17754 } 17755 17756 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 17757 // Offer a Copy fix even if the type is dependent. 17758 if (Var->getType()->isDependentType()) 17759 return true; 17760 QualType T = Var->getType().getNonReferenceType(); 17761 if (T.isTriviallyCopyableType(Context)) 17762 return true; 17763 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 17764 17765 if (!(RD = RD->getDefinition())) 17766 return false; 17767 if (RD->hasSimpleCopyConstructor()) 17768 return true; 17769 if (RD->hasUserDeclaredCopyConstructor()) 17770 for (CXXConstructorDecl *Ctor : RD->ctors()) 17771 if (Ctor->isCopyConstructor()) 17772 return !Ctor->isDeleted(); 17773 } 17774 return false; 17775 } 17776 17777 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 17778 /// default capture. Fixes may be omitted if they aren't allowed by the 17779 /// standard, for example we can't emit a default copy capture fix-it if we 17780 /// already explicitly copy capture capture another variable. 17781 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 17782 VarDecl *Var) { 17783 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 17784 // Don't offer Capture by copy of default capture by copy fixes if Var is 17785 // known not to be copy constructible. 17786 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 17787 17788 SmallString<32> FixBuffer; 17789 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 17790 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 17791 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 17792 if (ShouldOfferCopyFix) { 17793 // Offer fixes to insert an explicit capture for the variable. 17794 // [] -> [VarName] 17795 // [OtherCapture] -> [OtherCapture, VarName] 17796 FixBuffer.assign({Separator, Var->getName()}); 17797 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17798 << Var << /*value*/ 0 17799 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17800 } 17801 // As above but capture by reference. 17802 FixBuffer.assign({Separator, "&", Var->getName()}); 17803 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17804 << Var << /*reference*/ 1 17805 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17806 } 17807 17808 // Only try to offer default capture if there are no captures excluding this 17809 // and init captures. 17810 // [this]: OK. 17811 // [X = Y]: OK. 17812 // [&A, &B]: Don't offer. 17813 // [A, B]: Don't offer. 17814 if (llvm::any_of(LSI->Captures, [](Capture &C) { 17815 return !C.isThisCapture() && !C.isInitCapture(); 17816 })) 17817 return; 17818 17819 // The default capture specifiers, '=' or '&', must appear first in the 17820 // capture body. 17821 SourceLocation DefaultInsertLoc = 17822 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 17823 17824 if (ShouldOfferCopyFix) { 17825 bool CanDefaultCopyCapture = true; 17826 // [=, *this] OK since c++17 17827 // [=, this] OK since c++20 17828 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 17829 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 17830 ? LSI->getCXXThisCapture().isCopyCapture() 17831 : false; 17832 // We can't use default capture by copy if any captures already specified 17833 // capture by copy. 17834 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 17835 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 17836 })) { 17837 FixBuffer.assign({"=", Separator}); 17838 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17839 << /*value*/ 0 17840 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17841 } 17842 } 17843 17844 // We can't use default capture by reference if any captures already specified 17845 // capture by reference. 17846 if (llvm::none_of(LSI->Captures, [](Capture &C) { 17847 return !C.isInitCapture() && C.isReferenceCapture() && 17848 !C.isThisCapture(); 17849 })) { 17850 FixBuffer.assign({"&", Separator}); 17851 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17852 << /*reference*/ 1 17853 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17854 } 17855 } 17856 17857 bool Sema::tryCaptureVariable( 17858 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17859 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17860 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17861 // An init-capture is notionally from the context surrounding its 17862 // declaration, but its parent DC is the lambda class. 17863 DeclContext *VarDC = Var->getDeclContext(); 17864 if (Var->isInitCapture()) 17865 VarDC = VarDC->getParent(); 17866 17867 DeclContext *DC = CurContext; 17868 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17869 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17870 // We need to sync up the Declaration Context with the 17871 // FunctionScopeIndexToStopAt 17872 if (FunctionScopeIndexToStopAt) { 17873 unsigned FSIndex = FunctionScopes.size() - 1; 17874 while (FSIndex != MaxFunctionScopesIndex) { 17875 DC = getLambdaAwareParentOfDeclContext(DC); 17876 --FSIndex; 17877 } 17878 } 17879 17880 17881 // If the variable is declared in the current context, there is no need to 17882 // capture it. 17883 if (VarDC == DC) return true; 17884 17885 // Capture global variables if it is required to use private copy of this 17886 // variable. 17887 bool IsGlobal = !Var->hasLocalStorage(); 17888 if (IsGlobal && 17889 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17890 MaxFunctionScopesIndex))) 17891 return true; 17892 Var = Var->getCanonicalDecl(); 17893 17894 // Walk up the stack to determine whether we can capture the variable, 17895 // performing the "simple" checks that don't depend on type. We stop when 17896 // we've either hit the declared scope of the variable or find an existing 17897 // capture of that variable. We start from the innermost capturing-entity 17898 // (the DC) and ensure that all intervening capturing-entities 17899 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17900 // declcontext can either capture the variable or have already captured 17901 // the variable. 17902 CaptureType = Var->getType(); 17903 DeclRefType = CaptureType.getNonReferenceType(); 17904 bool Nested = false; 17905 bool Explicit = (Kind != TryCapture_Implicit); 17906 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17907 do { 17908 // Only block literals, captured statements, and lambda expressions can 17909 // capture; other scopes don't work. 17910 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17911 ExprLoc, 17912 BuildAndDiagnose, 17913 *this); 17914 // We need to check for the parent *first* because, if we *have* 17915 // private-captured a global variable, we need to recursively capture it in 17916 // intermediate blocks, lambdas, etc. 17917 if (!ParentDC) { 17918 if (IsGlobal) { 17919 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17920 break; 17921 } 17922 return true; 17923 } 17924 17925 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17926 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17927 17928 17929 // Check whether we've already captured it. 17930 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17931 DeclRefType)) { 17932 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17933 break; 17934 } 17935 // If we are instantiating a generic lambda call operator body, 17936 // we do not want to capture new variables. What was captured 17937 // during either a lambdas transformation or initial parsing 17938 // should be used. 17939 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17940 if (BuildAndDiagnose) { 17941 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17942 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17943 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17944 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17945 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17946 buildLambdaCaptureFixit(*this, LSI, Var); 17947 } else 17948 diagnoseUncapturableValueReference(*this, ExprLoc, Var); 17949 } 17950 return true; 17951 } 17952 17953 // Try to capture variable-length arrays types. 17954 if (Var->getType()->isVariablyModifiedType()) { 17955 // We're going to walk down into the type and look for VLA 17956 // expressions. 17957 QualType QTy = Var->getType(); 17958 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17959 QTy = PVD->getOriginalType(); 17960 captureVariablyModifiedType(Context, QTy, CSI); 17961 } 17962 17963 if (getLangOpts().OpenMP) { 17964 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17965 // OpenMP private variables should not be captured in outer scope, so 17966 // just break here. Similarly, global variables that are captured in a 17967 // target region should not be captured outside the scope of the region. 17968 if (RSI->CapRegionKind == CR_OpenMP) { 17969 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17970 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17971 // If the variable is private (i.e. not captured) and has variably 17972 // modified type, we still need to capture the type for correct 17973 // codegen in all regions, associated with the construct. Currently, 17974 // it is captured in the innermost captured region only. 17975 if (IsOpenMPPrivateDecl != OMPC_unknown && 17976 Var->getType()->isVariablyModifiedType()) { 17977 QualType QTy = Var->getType(); 17978 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17979 QTy = PVD->getOriginalType(); 17980 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17981 I < E; ++I) { 17982 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17983 FunctionScopes[FunctionScopesIndex - I]); 17984 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17985 "Wrong number of captured regions associated with the " 17986 "OpenMP construct."); 17987 captureVariablyModifiedType(Context, QTy, OuterRSI); 17988 } 17989 } 17990 bool IsTargetCap = 17991 IsOpenMPPrivateDecl != OMPC_private && 17992 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17993 RSI->OpenMPCaptureLevel); 17994 // Do not capture global if it is not privatized in outer regions. 17995 bool IsGlobalCap = 17996 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17997 RSI->OpenMPCaptureLevel); 17998 17999 // When we detect target captures we are looking from inside the 18000 // target region, therefore we need to propagate the capture from the 18001 // enclosing region. Therefore, the capture is not initially nested. 18002 if (IsTargetCap) 18003 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 18004 18005 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 18006 (IsGlobal && !IsGlobalCap)) { 18007 Nested = !IsTargetCap; 18008 bool HasConst = DeclRefType.isConstQualified(); 18009 DeclRefType = DeclRefType.getUnqualifiedType(); 18010 // Don't lose diagnostics about assignments to const. 18011 if (HasConst) 18012 DeclRefType.addConst(); 18013 CaptureType = Context.getLValueReferenceType(DeclRefType); 18014 break; 18015 } 18016 } 18017 } 18018 } 18019 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 18020 // No capture-default, and this is not an explicit capture 18021 // so cannot capture this variable. 18022 if (BuildAndDiagnose) { 18023 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18024 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18025 auto *LSI = cast<LambdaScopeInfo>(CSI); 18026 if (LSI->Lambda) { 18027 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18028 buildLambdaCaptureFixit(*this, LSI, Var); 18029 } 18030 // FIXME: If we error out because an outer lambda can not implicitly 18031 // capture a variable that an inner lambda explicitly captures, we 18032 // should have the inner lambda do the explicit capture - because 18033 // it makes for cleaner diagnostics later. This would purely be done 18034 // so that the diagnostic does not misleadingly claim that a variable 18035 // can not be captured by a lambda implicitly even though it is captured 18036 // explicitly. Suggestion: 18037 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 18038 // at the function head 18039 // - cache the StartingDeclContext - this must be a lambda 18040 // - captureInLambda in the innermost lambda the variable. 18041 } 18042 return true; 18043 } 18044 18045 FunctionScopesIndex--; 18046 DC = ParentDC; 18047 Explicit = false; 18048 } while (!VarDC->Equals(DC)); 18049 18050 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 18051 // computing the type of the capture at each step, checking type-specific 18052 // requirements, and adding captures if requested. 18053 // If the variable had already been captured previously, we start capturing 18054 // at the lambda nested within that one. 18055 bool Invalid = false; 18056 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 18057 ++I) { 18058 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 18059 18060 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18061 // certain types of variables (unnamed, variably modified types etc.) 18062 // so check for eligibility. 18063 if (!Invalid) 18064 Invalid = 18065 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 18066 18067 // After encountering an error, if we're actually supposed to capture, keep 18068 // capturing in nested contexts to suppress any follow-on diagnostics. 18069 if (Invalid && !BuildAndDiagnose) 18070 return true; 18071 18072 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 18073 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18074 DeclRefType, Nested, *this, Invalid); 18075 Nested = true; 18076 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18077 Invalid = !captureInCapturedRegion( 18078 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 18079 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 18080 Nested = true; 18081 } else { 18082 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18083 Invalid = 18084 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18085 DeclRefType, Nested, Kind, EllipsisLoc, 18086 /*IsTopScope*/ I == N - 1, *this, Invalid); 18087 Nested = true; 18088 } 18089 18090 if (Invalid && !BuildAndDiagnose) 18091 return true; 18092 } 18093 return Invalid; 18094 } 18095 18096 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 18097 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 18098 QualType CaptureType; 18099 QualType DeclRefType; 18100 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 18101 /*BuildAndDiagnose=*/true, CaptureType, 18102 DeclRefType, nullptr); 18103 } 18104 18105 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 18106 QualType CaptureType; 18107 QualType DeclRefType; 18108 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18109 /*BuildAndDiagnose=*/false, CaptureType, 18110 DeclRefType, nullptr); 18111 } 18112 18113 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 18114 QualType CaptureType; 18115 QualType DeclRefType; 18116 18117 // Determine whether we can capture this variable. 18118 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18119 /*BuildAndDiagnose=*/false, CaptureType, 18120 DeclRefType, nullptr)) 18121 return QualType(); 18122 18123 return DeclRefType; 18124 } 18125 18126 namespace { 18127 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 18128 // The produced TemplateArgumentListInfo* points to data stored within this 18129 // object, so should only be used in contexts where the pointer will not be 18130 // used after the CopiedTemplateArgs object is destroyed. 18131 class CopiedTemplateArgs { 18132 bool HasArgs; 18133 TemplateArgumentListInfo TemplateArgStorage; 18134 public: 18135 template<typename RefExpr> 18136 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 18137 if (HasArgs) 18138 E->copyTemplateArgumentsInto(TemplateArgStorage); 18139 } 18140 operator TemplateArgumentListInfo*() 18141 #ifdef __has_cpp_attribute 18142 #if __has_cpp_attribute(clang::lifetimebound) 18143 [[clang::lifetimebound]] 18144 #endif 18145 #endif 18146 { 18147 return HasArgs ? &TemplateArgStorage : nullptr; 18148 } 18149 }; 18150 } 18151 18152 /// Walk the set of potential results of an expression and mark them all as 18153 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 18154 /// 18155 /// \return A new expression if we found any potential results, ExprEmpty() if 18156 /// not, and ExprError() if we diagnosed an error. 18157 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 18158 NonOdrUseReason NOUR) { 18159 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 18160 // an object that satisfies the requirements for appearing in a 18161 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 18162 // is immediately applied." This function handles the lvalue-to-rvalue 18163 // conversion part. 18164 // 18165 // If we encounter a node that claims to be an odr-use but shouldn't be, we 18166 // transform it into the relevant kind of non-odr-use node and rebuild the 18167 // tree of nodes leading to it. 18168 // 18169 // This is a mini-TreeTransform that only transforms a restricted subset of 18170 // nodes (and only certain operands of them). 18171 18172 // Rebuild a subexpression. 18173 auto Rebuild = [&](Expr *Sub) { 18174 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 18175 }; 18176 18177 // Check whether a potential result satisfies the requirements of NOUR. 18178 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 18179 // Any entity other than a VarDecl is always odr-used whenever it's named 18180 // in a potentially-evaluated expression. 18181 auto *VD = dyn_cast<VarDecl>(D); 18182 if (!VD) 18183 return true; 18184 18185 // C++2a [basic.def.odr]p4: 18186 // A variable x whose name appears as a potentially-evalauted expression 18187 // e is odr-used by e unless 18188 // -- x is a reference that is usable in constant expressions, or 18189 // -- x is a variable of non-reference type that is usable in constant 18190 // expressions and has no mutable subobjects, and e is an element of 18191 // the set of potential results of an expression of 18192 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18193 // conversion is applied, or 18194 // -- x is a variable of non-reference type, and e is an element of the 18195 // set of potential results of a discarded-value expression to which 18196 // the lvalue-to-rvalue conversion is not applied 18197 // 18198 // We check the first bullet and the "potentially-evaluated" condition in 18199 // BuildDeclRefExpr. We check the type requirements in the second bullet 18200 // in CheckLValueToRValueConversionOperand below. 18201 switch (NOUR) { 18202 case NOUR_None: 18203 case NOUR_Unevaluated: 18204 llvm_unreachable("unexpected non-odr-use-reason"); 18205 18206 case NOUR_Constant: 18207 // Constant references were handled when they were built. 18208 if (VD->getType()->isReferenceType()) 18209 return true; 18210 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18211 if (RD->hasMutableFields()) 18212 return true; 18213 if (!VD->isUsableInConstantExpressions(S.Context)) 18214 return true; 18215 break; 18216 18217 case NOUR_Discarded: 18218 if (VD->getType()->isReferenceType()) 18219 return true; 18220 break; 18221 } 18222 return false; 18223 }; 18224 18225 // Mark that this expression does not constitute an odr-use. 18226 auto MarkNotOdrUsed = [&] { 18227 S.MaybeODRUseExprs.remove(E); 18228 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18229 LSI->markVariableExprAsNonODRUsed(E); 18230 }; 18231 18232 // C++2a [basic.def.odr]p2: 18233 // The set of potential results of an expression e is defined as follows: 18234 switch (E->getStmtClass()) { 18235 // -- If e is an id-expression, ... 18236 case Expr::DeclRefExprClass: { 18237 auto *DRE = cast<DeclRefExpr>(E); 18238 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18239 break; 18240 18241 // Rebuild as a non-odr-use DeclRefExpr. 18242 MarkNotOdrUsed(); 18243 return DeclRefExpr::Create( 18244 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18245 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18246 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18247 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18248 } 18249 18250 case Expr::FunctionParmPackExprClass: { 18251 auto *FPPE = cast<FunctionParmPackExpr>(E); 18252 // If any of the declarations in the pack is odr-used, then the expression 18253 // as a whole constitutes an odr-use. 18254 for (VarDecl *D : *FPPE) 18255 if (IsPotentialResultOdrUsed(D)) 18256 return ExprEmpty(); 18257 18258 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18259 // nothing cares about whether we marked this as an odr-use, but it might 18260 // be useful for non-compiler tools. 18261 MarkNotOdrUsed(); 18262 break; 18263 } 18264 18265 // -- If e is a subscripting operation with an array operand... 18266 case Expr::ArraySubscriptExprClass: { 18267 auto *ASE = cast<ArraySubscriptExpr>(E); 18268 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18269 if (!OldBase->getType()->isArrayType()) 18270 break; 18271 ExprResult Base = Rebuild(OldBase); 18272 if (!Base.isUsable()) 18273 return Base; 18274 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18275 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18276 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18277 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18278 ASE->getRBracketLoc()); 18279 } 18280 18281 case Expr::MemberExprClass: { 18282 auto *ME = cast<MemberExpr>(E); 18283 // -- If e is a class member access expression [...] naming a non-static 18284 // data member... 18285 if (isa<FieldDecl>(ME->getMemberDecl())) { 18286 ExprResult Base = Rebuild(ME->getBase()); 18287 if (!Base.isUsable()) 18288 return Base; 18289 return MemberExpr::Create( 18290 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18291 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18292 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18293 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18294 ME->getObjectKind(), ME->isNonOdrUse()); 18295 } 18296 18297 if (ME->getMemberDecl()->isCXXInstanceMember()) 18298 break; 18299 18300 // -- If e is a class member access expression naming a static data member, 18301 // ... 18302 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18303 break; 18304 18305 // Rebuild as a non-odr-use MemberExpr. 18306 MarkNotOdrUsed(); 18307 return MemberExpr::Create( 18308 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 18309 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 18310 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 18311 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 18312 } 18313 18314 case Expr::BinaryOperatorClass: { 18315 auto *BO = cast<BinaryOperator>(E); 18316 Expr *LHS = BO->getLHS(); 18317 Expr *RHS = BO->getRHS(); 18318 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18319 if (BO->getOpcode() == BO_PtrMemD) { 18320 ExprResult Sub = Rebuild(LHS); 18321 if (!Sub.isUsable()) 18322 return Sub; 18323 LHS = Sub.get(); 18324 // -- If e is a comma expression, ... 18325 } else if (BO->getOpcode() == BO_Comma) { 18326 ExprResult Sub = Rebuild(RHS); 18327 if (!Sub.isUsable()) 18328 return Sub; 18329 RHS = Sub.get(); 18330 } else { 18331 break; 18332 } 18333 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18334 LHS, RHS); 18335 } 18336 18337 // -- If e has the form (e1)... 18338 case Expr::ParenExprClass: { 18339 auto *PE = cast<ParenExpr>(E); 18340 ExprResult Sub = Rebuild(PE->getSubExpr()); 18341 if (!Sub.isUsable()) 18342 return Sub; 18343 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18344 } 18345 18346 // -- If e is a glvalue conditional expression, ... 18347 // We don't apply this to a binary conditional operator. FIXME: Should we? 18348 case Expr::ConditionalOperatorClass: { 18349 auto *CO = cast<ConditionalOperator>(E); 18350 ExprResult LHS = Rebuild(CO->getLHS()); 18351 if (LHS.isInvalid()) 18352 return ExprError(); 18353 ExprResult RHS = Rebuild(CO->getRHS()); 18354 if (RHS.isInvalid()) 18355 return ExprError(); 18356 if (!LHS.isUsable() && !RHS.isUsable()) 18357 return ExprEmpty(); 18358 if (!LHS.isUsable()) 18359 LHS = CO->getLHS(); 18360 if (!RHS.isUsable()) 18361 RHS = CO->getRHS(); 18362 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18363 CO->getCond(), LHS.get(), RHS.get()); 18364 } 18365 18366 // [Clang extension] 18367 // -- If e has the form __extension__ e1... 18368 case Expr::UnaryOperatorClass: { 18369 auto *UO = cast<UnaryOperator>(E); 18370 if (UO->getOpcode() != UO_Extension) 18371 break; 18372 ExprResult Sub = Rebuild(UO->getSubExpr()); 18373 if (!Sub.isUsable()) 18374 return Sub; 18375 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18376 Sub.get()); 18377 } 18378 18379 // [Clang extension] 18380 // -- If e has the form _Generic(...), the set of potential results is the 18381 // union of the sets of potential results of the associated expressions. 18382 case Expr::GenericSelectionExprClass: { 18383 auto *GSE = cast<GenericSelectionExpr>(E); 18384 18385 SmallVector<Expr *, 4> AssocExprs; 18386 bool AnyChanged = false; 18387 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18388 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18389 if (AssocExpr.isInvalid()) 18390 return ExprError(); 18391 if (AssocExpr.isUsable()) { 18392 AssocExprs.push_back(AssocExpr.get()); 18393 AnyChanged = true; 18394 } else { 18395 AssocExprs.push_back(OrigAssocExpr); 18396 } 18397 } 18398 18399 return AnyChanged ? S.CreateGenericSelectionExpr( 18400 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18401 GSE->getRParenLoc(), GSE->getControllingExpr(), 18402 GSE->getAssocTypeSourceInfos(), AssocExprs) 18403 : ExprEmpty(); 18404 } 18405 18406 // [Clang extension] 18407 // -- If e has the form __builtin_choose_expr(...), the set of potential 18408 // results is the union of the sets of potential results of the 18409 // second and third subexpressions. 18410 case Expr::ChooseExprClass: { 18411 auto *CE = cast<ChooseExpr>(E); 18412 18413 ExprResult LHS = Rebuild(CE->getLHS()); 18414 if (LHS.isInvalid()) 18415 return ExprError(); 18416 18417 ExprResult RHS = Rebuild(CE->getLHS()); 18418 if (RHS.isInvalid()) 18419 return ExprError(); 18420 18421 if (!LHS.get() && !RHS.get()) 18422 return ExprEmpty(); 18423 if (!LHS.isUsable()) 18424 LHS = CE->getLHS(); 18425 if (!RHS.isUsable()) 18426 RHS = CE->getRHS(); 18427 18428 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18429 RHS.get(), CE->getRParenLoc()); 18430 } 18431 18432 // Step through non-syntactic nodes. 18433 case Expr::ConstantExprClass: { 18434 auto *CE = cast<ConstantExpr>(E); 18435 ExprResult Sub = Rebuild(CE->getSubExpr()); 18436 if (!Sub.isUsable()) 18437 return Sub; 18438 return ConstantExpr::Create(S.Context, Sub.get()); 18439 } 18440 18441 // We could mostly rely on the recursive rebuilding to rebuild implicit 18442 // casts, but not at the top level, so rebuild them here. 18443 case Expr::ImplicitCastExprClass: { 18444 auto *ICE = cast<ImplicitCastExpr>(E); 18445 // Only step through the narrow set of cast kinds we expect to encounter. 18446 // Anything else suggests we've left the region in which potential results 18447 // can be found. 18448 switch (ICE->getCastKind()) { 18449 case CK_NoOp: 18450 case CK_DerivedToBase: 18451 case CK_UncheckedDerivedToBase: { 18452 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18453 if (!Sub.isUsable()) 18454 return Sub; 18455 CXXCastPath Path(ICE->path()); 18456 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18457 ICE->getValueKind(), &Path); 18458 } 18459 18460 default: 18461 break; 18462 } 18463 break; 18464 } 18465 18466 default: 18467 break; 18468 } 18469 18470 // Can't traverse through this node. Nothing to do. 18471 return ExprEmpty(); 18472 } 18473 18474 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18475 // Check whether the operand is or contains an object of non-trivial C union 18476 // type. 18477 if (E->getType().isVolatileQualified() && 18478 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18479 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18480 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18481 Sema::NTCUC_LValueToRValueVolatile, 18482 NTCUK_Destruct|NTCUK_Copy); 18483 18484 // C++2a [basic.def.odr]p4: 18485 // [...] an expression of non-volatile-qualified non-class type to which 18486 // the lvalue-to-rvalue conversion is applied [...] 18487 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18488 return E; 18489 18490 ExprResult Result = 18491 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18492 if (Result.isInvalid()) 18493 return ExprError(); 18494 return Result.get() ? Result : E; 18495 } 18496 18497 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18498 Res = CorrectDelayedTyposInExpr(Res); 18499 18500 if (!Res.isUsable()) 18501 return Res; 18502 18503 // If a constant-expression is a reference to a variable where we delay 18504 // deciding whether it is an odr-use, just assume we will apply the 18505 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18506 // (a non-type template argument), we have special handling anyway. 18507 return CheckLValueToRValueConversionOperand(Res.get()); 18508 } 18509 18510 void Sema::CleanupVarDeclMarking() { 18511 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18512 // call. 18513 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18514 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18515 18516 for (Expr *E : LocalMaybeODRUseExprs) { 18517 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18518 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18519 DRE->getLocation(), *this); 18520 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18521 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18522 *this); 18523 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18524 for (VarDecl *VD : *FP) 18525 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18526 } else { 18527 llvm_unreachable("Unexpected expression"); 18528 } 18529 } 18530 18531 assert(MaybeODRUseExprs.empty() && 18532 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18533 } 18534 18535 static void DoMarkVarDeclReferenced( 18536 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 18537 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18538 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18539 isa<FunctionParmPackExpr>(E)) && 18540 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18541 Var->setReferenced(); 18542 18543 if (Var->isInvalidDecl()) 18544 return; 18545 18546 auto *MSI = Var->getMemberSpecializationInfo(); 18547 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18548 : Var->getTemplateSpecializationKind(); 18549 18550 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18551 bool UsableInConstantExpr = 18552 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18553 18554 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 18555 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 18556 } 18557 18558 // C++20 [expr.const]p12: 18559 // A variable [...] is needed for constant evaluation if it is [...] a 18560 // variable whose name appears as a potentially constant evaluated 18561 // expression that is either a contexpr variable or is of non-volatile 18562 // const-qualified integral type or of reference type 18563 bool NeededForConstantEvaluation = 18564 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18565 18566 bool NeedDefinition = 18567 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18568 18569 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18570 "Can't instantiate a partial template specialization."); 18571 18572 // If this might be a member specialization of a static data member, check 18573 // the specialization is visible. We already did the checks for variable 18574 // template specializations when we created them. 18575 if (NeedDefinition && TSK != TSK_Undeclared && 18576 !isa<VarTemplateSpecializationDecl>(Var)) 18577 SemaRef.checkSpecializationVisibility(Loc, Var); 18578 18579 // Perform implicit instantiation of static data members, static data member 18580 // templates of class templates, and variable template specializations. Delay 18581 // instantiations of variable templates, except for those that could be used 18582 // in a constant expression. 18583 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18584 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18585 // instantiation declaration if a variable is usable in a constant 18586 // expression (among other cases). 18587 bool TryInstantiating = 18588 TSK == TSK_ImplicitInstantiation || 18589 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18590 18591 if (TryInstantiating) { 18592 SourceLocation PointOfInstantiation = 18593 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18594 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18595 if (FirstInstantiation) { 18596 PointOfInstantiation = Loc; 18597 if (MSI) 18598 MSI->setPointOfInstantiation(PointOfInstantiation); 18599 // FIXME: Notify listener. 18600 else 18601 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18602 } 18603 18604 if (UsableInConstantExpr) { 18605 // Do not defer instantiations of variables that could be used in a 18606 // constant expression. 18607 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18608 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18609 }); 18610 18611 // Re-set the member to trigger a recomputation of the dependence bits 18612 // for the expression. 18613 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18614 DRE->setDecl(DRE->getDecl()); 18615 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18616 ME->setMemberDecl(ME->getMemberDecl()); 18617 } else if (FirstInstantiation || 18618 isa<VarTemplateSpecializationDecl>(Var)) { 18619 // FIXME: For a specialization of a variable template, we don't 18620 // distinguish between "declaration and type implicitly instantiated" 18621 // and "implicit instantiation of definition requested", so we have 18622 // no direct way to avoid enqueueing the pending instantiation 18623 // multiple times. 18624 SemaRef.PendingInstantiations 18625 .push_back(std::make_pair(Var, PointOfInstantiation)); 18626 } 18627 } 18628 } 18629 18630 // C++2a [basic.def.odr]p4: 18631 // A variable x whose name appears as a potentially-evaluated expression e 18632 // is odr-used by e unless 18633 // -- x is a reference that is usable in constant expressions 18634 // -- x is a variable of non-reference type that is usable in constant 18635 // expressions and has no mutable subobjects [FIXME], and e is an 18636 // element of the set of potential results of an expression of 18637 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18638 // conversion is applied 18639 // -- x is a variable of non-reference type, and e is an element of the set 18640 // of potential results of a discarded-value expression to which the 18641 // lvalue-to-rvalue conversion is not applied [FIXME] 18642 // 18643 // We check the first part of the second bullet here, and 18644 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18645 // FIXME: To get the third bullet right, we need to delay this even for 18646 // variables that are not usable in constant expressions. 18647 18648 // If we already know this isn't an odr-use, there's nothing more to do. 18649 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18650 if (DRE->isNonOdrUse()) 18651 return; 18652 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18653 if (ME->isNonOdrUse()) 18654 return; 18655 18656 switch (OdrUse) { 18657 case OdrUseContext::None: 18658 assert((!E || isa<FunctionParmPackExpr>(E)) && 18659 "missing non-odr-use marking for unevaluated decl ref"); 18660 break; 18661 18662 case OdrUseContext::FormallyOdrUsed: 18663 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18664 // behavior. 18665 break; 18666 18667 case OdrUseContext::Used: 18668 // If we might later find that this expression isn't actually an odr-use, 18669 // delay the marking. 18670 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18671 SemaRef.MaybeODRUseExprs.insert(E); 18672 else 18673 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18674 break; 18675 18676 case OdrUseContext::Dependent: 18677 // If this is a dependent context, we don't need to mark variables as 18678 // odr-used, but we may still need to track them for lambda capture. 18679 // FIXME: Do we also need to do this inside dependent typeid expressions 18680 // (which are modeled as unevaluated at this point)? 18681 const bool RefersToEnclosingScope = 18682 (SemaRef.CurContext != Var->getDeclContext() && 18683 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18684 if (RefersToEnclosingScope) { 18685 LambdaScopeInfo *const LSI = 18686 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18687 if (LSI && (!LSI->CallOperator || 18688 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18689 // If a variable could potentially be odr-used, defer marking it so 18690 // until we finish analyzing the full expression for any 18691 // lvalue-to-rvalue 18692 // or discarded value conversions that would obviate odr-use. 18693 // Add it to the list of potential captures that will be analyzed 18694 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18695 // unless the variable is a reference that was initialized by a constant 18696 // expression (this will never need to be captured or odr-used). 18697 // 18698 // FIXME: We can simplify this a lot after implementing P0588R1. 18699 assert(E && "Capture variable should be used in an expression."); 18700 if (!Var->getType()->isReferenceType() || 18701 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18702 LSI->addPotentialCapture(E->IgnoreParens()); 18703 } 18704 } 18705 break; 18706 } 18707 } 18708 18709 /// Mark a variable referenced, and check whether it is odr-used 18710 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18711 /// used directly for normal expressions referring to VarDecl. 18712 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18713 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 18714 } 18715 18716 static void 18717 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 18718 bool MightBeOdrUse, 18719 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18720 if (SemaRef.isInOpenMPDeclareTargetContext()) 18721 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18722 18723 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18724 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 18725 return; 18726 } 18727 18728 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18729 18730 // If this is a call to a method via a cast, also mark the method in the 18731 // derived class used in case codegen can devirtualize the call. 18732 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18733 if (!ME) 18734 return; 18735 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18736 if (!MD) 18737 return; 18738 // Only attempt to devirtualize if this is truly a virtual call. 18739 bool IsVirtualCall = MD->isVirtual() && 18740 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18741 if (!IsVirtualCall) 18742 return; 18743 18744 // If it's possible to devirtualize the call, mark the called function 18745 // referenced. 18746 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18747 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18748 if (DM) 18749 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18750 } 18751 18752 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18753 /// 18754 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18755 /// handled with care if the DeclRefExpr is not newly-created. 18756 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18757 // TODO: update this with DR# once a defect report is filed. 18758 // C++11 defect. The address of a pure member should not be an ODR use, even 18759 // if it's a qualified reference. 18760 bool OdrUse = true; 18761 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18762 if (Method->isVirtual() && 18763 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18764 OdrUse = false; 18765 18766 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18767 if (!isUnevaluatedContext() && !isConstantEvaluated() && 18768 FD->isConsteval() && !RebuildingImmediateInvocation) 18769 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18770 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 18771 RefsMinusAssignments); 18772 } 18773 18774 /// Perform reference-marking and odr-use handling for a MemberExpr. 18775 void Sema::MarkMemberReferenced(MemberExpr *E) { 18776 // C++11 [basic.def.odr]p2: 18777 // A non-overloaded function whose name appears as a potentially-evaluated 18778 // expression or a member of a set of candidate functions, if selected by 18779 // overload resolution when referred to from a potentially-evaluated 18780 // expression, is odr-used, unless it is a pure virtual function and its 18781 // name is not explicitly qualified. 18782 bool MightBeOdrUse = true; 18783 if (E->performsVirtualDispatch(getLangOpts())) { 18784 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18785 if (Method->isPure()) 18786 MightBeOdrUse = false; 18787 } 18788 SourceLocation Loc = 18789 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18790 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 18791 RefsMinusAssignments); 18792 } 18793 18794 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18795 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18796 for (VarDecl *VD : *E) 18797 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 18798 RefsMinusAssignments); 18799 } 18800 18801 /// Perform marking for a reference to an arbitrary declaration. It 18802 /// marks the declaration referenced, and performs odr-use checking for 18803 /// functions and variables. This method should not be used when building a 18804 /// normal expression which refers to a variable. 18805 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18806 bool MightBeOdrUse) { 18807 if (MightBeOdrUse) { 18808 if (auto *VD = dyn_cast<VarDecl>(D)) { 18809 MarkVariableReferenced(Loc, VD); 18810 return; 18811 } 18812 } 18813 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18814 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18815 return; 18816 } 18817 D->setReferenced(); 18818 } 18819 18820 namespace { 18821 // Mark all of the declarations used by a type as referenced. 18822 // FIXME: Not fully implemented yet! We need to have a better understanding 18823 // of when we're entering a context we should not recurse into. 18824 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18825 // TreeTransforms rebuilding the type in a new context. Rather than 18826 // duplicating the TreeTransform logic, we should consider reusing it here. 18827 // Currently that causes problems when rebuilding LambdaExprs. 18828 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18829 Sema &S; 18830 SourceLocation Loc; 18831 18832 public: 18833 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18834 18835 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18836 18837 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18838 }; 18839 } 18840 18841 bool MarkReferencedDecls::TraverseTemplateArgument( 18842 const TemplateArgument &Arg) { 18843 { 18844 // A non-type template argument is a constant-evaluated context. 18845 EnterExpressionEvaluationContext Evaluated( 18846 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18847 if (Arg.getKind() == TemplateArgument::Declaration) { 18848 if (Decl *D = Arg.getAsDecl()) 18849 S.MarkAnyDeclReferenced(Loc, D, true); 18850 } else if (Arg.getKind() == TemplateArgument::Expression) { 18851 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18852 } 18853 } 18854 18855 return Inherited::TraverseTemplateArgument(Arg); 18856 } 18857 18858 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18859 MarkReferencedDecls Marker(*this, Loc); 18860 Marker.TraverseType(T); 18861 } 18862 18863 namespace { 18864 /// Helper class that marks all of the declarations referenced by 18865 /// potentially-evaluated subexpressions as "referenced". 18866 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18867 public: 18868 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18869 bool SkipLocalVariables; 18870 18871 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18872 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18873 18874 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18875 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18876 } 18877 18878 void VisitDeclRefExpr(DeclRefExpr *E) { 18879 // If we were asked not to visit local variables, don't. 18880 if (SkipLocalVariables) { 18881 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18882 if (VD->hasLocalStorage()) 18883 return; 18884 } 18885 18886 // FIXME: This can trigger the instantiation of the initializer of a 18887 // variable, which can cause the expression to become value-dependent 18888 // or error-dependent. Do we need to propagate the new dependence bits? 18889 S.MarkDeclRefReferenced(E); 18890 } 18891 18892 void VisitMemberExpr(MemberExpr *E) { 18893 S.MarkMemberReferenced(E); 18894 Visit(E->getBase()); 18895 } 18896 }; 18897 } // namespace 18898 18899 /// Mark any declarations that appear within this expression or any 18900 /// potentially-evaluated subexpressions as "referenced". 18901 /// 18902 /// \param SkipLocalVariables If true, don't mark local variables as 18903 /// 'referenced'. 18904 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18905 bool SkipLocalVariables) { 18906 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18907 } 18908 18909 /// Emit a diagnostic when statements are reachable. 18910 /// FIXME: check for reachability even in expressions for which we don't build a 18911 /// CFG (eg, in the initializer of a global or in a constant expression). 18912 /// For example, 18913 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; } 18914 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, 18915 const PartialDiagnostic &PD) { 18916 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18917 if (!FunctionScopes.empty()) 18918 FunctionScopes.back()->PossiblyUnreachableDiags.push_back( 18919 sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18920 return true; 18921 } 18922 18923 // The initializer of a constexpr variable or of the first declaration of a 18924 // static data member is not syntactically a constant evaluated constant, 18925 // but nonetheless is always required to be a constant expression, so we 18926 // can skip diagnosing. 18927 // FIXME: Using the mangling context here is a hack. 18928 if (auto *VD = dyn_cast_or_null<VarDecl>( 18929 ExprEvalContexts.back().ManglingContextDecl)) { 18930 if (VD->isConstexpr() || 18931 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18932 return false; 18933 // FIXME: For any other kind of variable, we should build a CFG for its 18934 // initializer and check whether the context in question is reachable. 18935 } 18936 18937 Diag(Loc, PD); 18938 return true; 18939 } 18940 18941 /// Emit a diagnostic that describes an effect on the run-time behavior 18942 /// of the program being compiled. 18943 /// 18944 /// This routine emits the given diagnostic when the code currently being 18945 /// type-checked is "potentially evaluated", meaning that there is a 18946 /// possibility that the code will actually be executable. Code in sizeof() 18947 /// expressions, code used only during overload resolution, etc., are not 18948 /// potentially evaluated. This routine will suppress such diagnostics or, 18949 /// in the absolutely nutty case of potentially potentially evaluated 18950 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18951 /// later. 18952 /// 18953 /// This routine should be used for all diagnostics that describe the run-time 18954 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18955 /// Failure to do so will likely result in spurious diagnostics or failures 18956 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18957 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18958 const PartialDiagnostic &PD) { 18959 switch (ExprEvalContexts.back().Context) { 18960 case ExpressionEvaluationContext::Unevaluated: 18961 case ExpressionEvaluationContext::UnevaluatedList: 18962 case ExpressionEvaluationContext::UnevaluatedAbstract: 18963 case ExpressionEvaluationContext::DiscardedStatement: 18964 // The argument will never be evaluated, so don't complain. 18965 break; 18966 18967 case ExpressionEvaluationContext::ConstantEvaluated: 18968 case ExpressionEvaluationContext::ImmediateFunctionContext: 18969 // Relevant diagnostics should be produced by constant evaluation. 18970 break; 18971 18972 case ExpressionEvaluationContext::PotentiallyEvaluated: 18973 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18974 return DiagIfReachable(Loc, Stmts, PD); 18975 } 18976 18977 return false; 18978 } 18979 18980 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18981 const PartialDiagnostic &PD) { 18982 return DiagRuntimeBehavior( 18983 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18984 } 18985 18986 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18987 CallExpr *CE, FunctionDecl *FD) { 18988 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18989 return false; 18990 18991 // If we're inside a decltype's expression, don't check for a valid return 18992 // type or construct temporaries until we know whether this is the last call. 18993 if (ExprEvalContexts.back().ExprContext == 18994 ExpressionEvaluationContextRecord::EK_Decltype) { 18995 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18996 return false; 18997 } 18998 18999 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 19000 FunctionDecl *FD; 19001 CallExpr *CE; 19002 19003 public: 19004 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 19005 : FD(FD), CE(CE) { } 19006 19007 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 19008 if (!FD) { 19009 S.Diag(Loc, diag::err_call_incomplete_return) 19010 << T << CE->getSourceRange(); 19011 return; 19012 } 19013 19014 S.Diag(Loc, diag::err_call_function_incomplete_return) 19015 << CE->getSourceRange() << FD << T; 19016 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 19017 << FD->getDeclName(); 19018 } 19019 } Diagnoser(FD, CE); 19020 19021 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 19022 return true; 19023 19024 return false; 19025 } 19026 19027 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 19028 // will prevent this condition from triggering, which is what we want. 19029 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 19030 SourceLocation Loc; 19031 19032 unsigned diagnostic = diag::warn_condition_is_assignment; 19033 bool IsOrAssign = false; 19034 19035 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 19036 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 19037 return; 19038 19039 IsOrAssign = Op->getOpcode() == BO_OrAssign; 19040 19041 // Greylist some idioms by putting them into a warning subcategory. 19042 if (ObjCMessageExpr *ME 19043 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 19044 Selector Sel = ME->getSelector(); 19045 19046 // self = [<foo> init...] 19047 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 19048 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19049 19050 // <foo> = [<bar> nextObject] 19051 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 19052 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19053 } 19054 19055 Loc = Op->getOperatorLoc(); 19056 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 19057 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 19058 return; 19059 19060 IsOrAssign = Op->getOperator() == OO_PipeEqual; 19061 Loc = Op->getOperatorLoc(); 19062 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 19063 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 19064 else { 19065 // Not an assignment. 19066 return; 19067 } 19068 19069 Diag(Loc, diagnostic) << E->getSourceRange(); 19070 19071 SourceLocation Open = E->getBeginLoc(); 19072 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 19073 Diag(Loc, diag::note_condition_assign_silence) 19074 << FixItHint::CreateInsertion(Open, "(") 19075 << FixItHint::CreateInsertion(Close, ")"); 19076 19077 if (IsOrAssign) 19078 Diag(Loc, diag::note_condition_or_assign_to_comparison) 19079 << FixItHint::CreateReplacement(Loc, "!="); 19080 else 19081 Diag(Loc, diag::note_condition_assign_to_comparison) 19082 << FixItHint::CreateReplacement(Loc, "=="); 19083 } 19084 19085 /// Redundant parentheses over an equality comparison can indicate 19086 /// that the user intended an assignment used as condition. 19087 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 19088 // Don't warn if the parens came from a macro. 19089 SourceLocation parenLoc = ParenE->getBeginLoc(); 19090 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 19091 return; 19092 // Don't warn for dependent expressions. 19093 if (ParenE->isTypeDependent()) 19094 return; 19095 19096 Expr *E = ParenE->IgnoreParens(); 19097 19098 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 19099 if (opE->getOpcode() == BO_EQ && 19100 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 19101 == Expr::MLV_Valid) { 19102 SourceLocation Loc = opE->getOperatorLoc(); 19103 19104 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 19105 SourceRange ParenERange = ParenE->getSourceRange(); 19106 Diag(Loc, diag::note_equality_comparison_silence) 19107 << FixItHint::CreateRemoval(ParenERange.getBegin()) 19108 << FixItHint::CreateRemoval(ParenERange.getEnd()); 19109 Diag(Loc, diag::note_equality_comparison_to_assign) 19110 << FixItHint::CreateReplacement(Loc, "="); 19111 } 19112 } 19113 19114 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 19115 bool IsConstexpr) { 19116 DiagnoseAssignmentAsCondition(E); 19117 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 19118 DiagnoseEqualityWithExtraParens(parenE); 19119 19120 ExprResult result = CheckPlaceholderExpr(E); 19121 if (result.isInvalid()) return ExprError(); 19122 E = result.get(); 19123 19124 if (!E->isTypeDependent()) { 19125 if (getLangOpts().CPlusPlus) 19126 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 19127 19128 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 19129 if (ERes.isInvalid()) 19130 return ExprError(); 19131 E = ERes.get(); 19132 19133 QualType T = E->getType(); 19134 if (!T->isScalarType()) { // C99 6.8.4.1p1 19135 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 19136 << T << E->getSourceRange(); 19137 return ExprError(); 19138 } 19139 CheckBoolLikeConversion(E, Loc); 19140 } 19141 19142 return E; 19143 } 19144 19145 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 19146 Expr *SubExpr, ConditionKind CK) { 19147 // Empty conditions are valid in for-statements. 19148 if (!SubExpr) 19149 return ConditionResult(); 19150 19151 ExprResult Cond; 19152 switch (CK) { 19153 case ConditionKind::Boolean: 19154 Cond = CheckBooleanCondition(Loc, SubExpr); 19155 break; 19156 19157 case ConditionKind::ConstexprIf: 19158 Cond = CheckBooleanCondition(Loc, SubExpr, true); 19159 break; 19160 19161 case ConditionKind::Switch: 19162 Cond = CheckSwitchCondition(Loc, SubExpr); 19163 break; 19164 } 19165 if (Cond.isInvalid()) { 19166 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 19167 {SubExpr}); 19168 if (!Cond.get()) 19169 return ConditionError(); 19170 } 19171 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 19172 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 19173 if (!FullExpr.get()) 19174 return ConditionError(); 19175 19176 return ConditionResult(*this, nullptr, FullExpr, 19177 CK == ConditionKind::ConstexprIf); 19178 } 19179 19180 namespace { 19181 /// A visitor for rebuilding a call to an __unknown_any expression 19182 /// to have an appropriate type. 19183 struct RebuildUnknownAnyFunction 19184 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 19185 19186 Sema &S; 19187 19188 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 19189 19190 ExprResult VisitStmt(Stmt *S) { 19191 llvm_unreachable("unexpected statement!"); 19192 } 19193 19194 ExprResult VisitExpr(Expr *E) { 19195 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 19196 << E->getSourceRange(); 19197 return ExprError(); 19198 } 19199 19200 /// Rebuild an expression which simply semantically wraps another 19201 /// expression which it shares the type and value kind of. 19202 template <class T> ExprResult rebuildSugarExpr(T *E) { 19203 ExprResult SubResult = Visit(E->getSubExpr()); 19204 if (SubResult.isInvalid()) return ExprError(); 19205 19206 Expr *SubExpr = SubResult.get(); 19207 E->setSubExpr(SubExpr); 19208 E->setType(SubExpr->getType()); 19209 E->setValueKind(SubExpr->getValueKind()); 19210 assert(E->getObjectKind() == OK_Ordinary); 19211 return E; 19212 } 19213 19214 ExprResult VisitParenExpr(ParenExpr *E) { 19215 return rebuildSugarExpr(E); 19216 } 19217 19218 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19219 return rebuildSugarExpr(E); 19220 } 19221 19222 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19223 ExprResult SubResult = Visit(E->getSubExpr()); 19224 if (SubResult.isInvalid()) return ExprError(); 19225 19226 Expr *SubExpr = SubResult.get(); 19227 E->setSubExpr(SubExpr); 19228 E->setType(S.Context.getPointerType(SubExpr->getType())); 19229 assert(E->isPRValue()); 19230 assert(E->getObjectKind() == OK_Ordinary); 19231 return E; 19232 } 19233 19234 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19235 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19236 19237 E->setType(VD->getType()); 19238 19239 assert(E->isPRValue()); 19240 if (S.getLangOpts().CPlusPlus && 19241 !(isa<CXXMethodDecl>(VD) && 19242 cast<CXXMethodDecl>(VD)->isInstance())) 19243 E->setValueKind(VK_LValue); 19244 19245 return E; 19246 } 19247 19248 ExprResult VisitMemberExpr(MemberExpr *E) { 19249 return resolveDecl(E, E->getMemberDecl()); 19250 } 19251 19252 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19253 return resolveDecl(E, E->getDecl()); 19254 } 19255 }; 19256 } 19257 19258 /// Given a function expression of unknown-any type, try to rebuild it 19259 /// to have a function type. 19260 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19261 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19262 if (Result.isInvalid()) return ExprError(); 19263 return S.DefaultFunctionArrayConversion(Result.get()); 19264 } 19265 19266 namespace { 19267 /// A visitor for rebuilding an expression of type __unknown_anytype 19268 /// into one which resolves the type directly on the referring 19269 /// expression. Strict preservation of the original source 19270 /// structure is not a goal. 19271 struct RebuildUnknownAnyExpr 19272 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19273 19274 Sema &S; 19275 19276 /// The current destination type. 19277 QualType DestType; 19278 19279 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19280 : S(S), DestType(CastType) {} 19281 19282 ExprResult VisitStmt(Stmt *S) { 19283 llvm_unreachable("unexpected statement!"); 19284 } 19285 19286 ExprResult VisitExpr(Expr *E) { 19287 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19288 << E->getSourceRange(); 19289 return ExprError(); 19290 } 19291 19292 ExprResult VisitCallExpr(CallExpr *E); 19293 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 19294 19295 /// Rebuild an expression which simply semantically wraps another 19296 /// expression which it shares the type and value kind of. 19297 template <class T> ExprResult rebuildSugarExpr(T *E) { 19298 ExprResult SubResult = Visit(E->getSubExpr()); 19299 if (SubResult.isInvalid()) return ExprError(); 19300 Expr *SubExpr = SubResult.get(); 19301 E->setSubExpr(SubExpr); 19302 E->setType(SubExpr->getType()); 19303 E->setValueKind(SubExpr->getValueKind()); 19304 assert(E->getObjectKind() == OK_Ordinary); 19305 return E; 19306 } 19307 19308 ExprResult VisitParenExpr(ParenExpr *E) { 19309 return rebuildSugarExpr(E); 19310 } 19311 19312 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19313 return rebuildSugarExpr(E); 19314 } 19315 19316 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19317 const PointerType *Ptr = DestType->getAs<PointerType>(); 19318 if (!Ptr) { 19319 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19320 << E->getSourceRange(); 19321 return ExprError(); 19322 } 19323 19324 if (isa<CallExpr>(E->getSubExpr())) { 19325 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19326 << E->getSourceRange(); 19327 return ExprError(); 19328 } 19329 19330 assert(E->isPRValue()); 19331 assert(E->getObjectKind() == OK_Ordinary); 19332 E->setType(DestType); 19333 19334 // Build the sub-expression as if it were an object of the pointee type. 19335 DestType = Ptr->getPointeeType(); 19336 ExprResult SubResult = Visit(E->getSubExpr()); 19337 if (SubResult.isInvalid()) return ExprError(); 19338 E->setSubExpr(SubResult.get()); 19339 return E; 19340 } 19341 19342 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19343 19344 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19345 19346 ExprResult VisitMemberExpr(MemberExpr *E) { 19347 return resolveDecl(E, E->getMemberDecl()); 19348 } 19349 19350 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19351 return resolveDecl(E, E->getDecl()); 19352 } 19353 }; 19354 } 19355 19356 /// Rebuilds a call expression which yielded __unknown_anytype. 19357 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19358 Expr *CalleeExpr = E->getCallee(); 19359 19360 enum FnKind { 19361 FK_MemberFunction, 19362 FK_FunctionPointer, 19363 FK_BlockPointer 19364 }; 19365 19366 FnKind Kind; 19367 QualType CalleeType = CalleeExpr->getType(); 19368 if (CalleeType == S.Context.BoundMemberTy) { 19369 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19370 Kind = FK_MemberFunction; 19371 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19372 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19373 CalleeType = Ptr->getPointeeType(); 19374 Kind = FK_FunctionPointer; 19375 } else { 19376 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19377 Kind = FK_BlockPointer; 19378 } 19379 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19380 19381 // Verify that this is a legal result type of a function. 19382 if (DestType->isArrayType() || DestType->isFunctionType()) { 19383 unsigned diagID = diag::err_func_returning_array_function; 19384 if (Kind == FK_BlockPointer) 19385 diagID = diag::err_block_returning_array_function; 19386 19387 S.Diag(E->getExprLoc(), diagID) 19388 << DestType->isFunctionType() << DestType; 19389 return ExprError(); 19390 } 19391 19392 // Otherwise, go ahead and set DestType as the call's result. 19393 E->setType(DestType.getNonLValueExprType(S.Context)); 19394 E->setValueKind(Expr::getValueKindForType(DestType)); 19395 assert(E->getObjectKind() == OK_Ordinary); 19396 19397 // Rebuild the function type, replacing the result type with DestType. 19398 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19399 if (Proto) { 19400 // __unknown_anytype(...) is a special case used by the debugger when 19401 // it has no idea what a function's signature is. 19402 // 19403 // We want to build this call essentially under the K&R 19404 // unprototyped rules, but making a FunctionNoProtoType in C++ 19405 // would foul up all sorts of assumptions. However, we cannot 19406 // simply pass all arguments as variadic arguments, nor can we 19407 // portably just call the function under a non-variadic type; see 19408 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19409 // However, it turns out that in practice it is generally safe to 19410 // call a function declared as "A foo(B,C,D);" under the prototype 19411 // "A foo(B,C,D,...);". The only known exception is with the 19412 // Windows ABI, where any variadic function is implicitly cdecl 19413 // regardless of its normal CC. Therefore we change the parameter 19414 // types to match the types of the arguments. 19415 // 19416 // This is a hack, but it is far superior to moving the 19417 // corresponding target-specific code from IR-gen to Sema/AST. 19418 19419 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19420 SmallVector<QualType, 8> ArgTypes; 19421 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19422 ArgTypes.reserve(E->getNumArgs()); 19423 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19424 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); 19425 } 19426 ParamTypes = ArgTypes; 19427 } 19428 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19429 Proto->getExtProtoInfo()); 19430 } else { 19431 DestType = S.Context.getFunctionNoProtoType(DestType, 19432 FnType->getExtInfo()); 19433 } 19434 19435 // Rebuild the appropriate pointer-to-function type. 19436 switch (Kind) { 19437 case FK_MemberFunction: 19438 // Nothing to do. 19439 break; 19440 19441 case FK_FunctionPointer: 19442 DestType = S.Context.getPointerType(DestType); 19443 break; 19444 19445 case FK_BlockPointer: 19446 DestType = S.Context.getBlockPointerType(DestType); 19447 break; 19448 } 19449 19450 // Finally, we can recurse. 19451 ExprResult CalleeResult = Visit(CalleeExpr); 19452 if (!CalleeResult.isUsable()) return ExprError(); 19453 E->setCallee(CalleeResult.get()); 19454 19455 // Bind a temporary if necessary. 19456 return S.MaybeBindToTemporary(E); 19457 } 19458 19459 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19460 // Verify that this is a legal result type of a call. 19461 if (DestType->isArrayType() || DestType->isFunctionType()) { 19462 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19463 << DestType->isFunctionType() << DestType; 19464 return ExprError(); 19465 } 19466 19467 // Rewrite the method result type if available. 19468 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19469 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19470 Method->setReturnType(DestType); 19471 } 19472 19473 // Change the type of the message. 19474 E->setType(DestType.getNonReferenceType()); 19475 E->setValueKind(Expr::getValueKindForType(DestType)); 19476 19477 return S.MaybeBindToTemporary(E); 19478 } 19479 19480 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19481 // The only case we should ever see here is a function-to-pointer decay. 19482 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19483 assert(E->isPRValue()); 19484 assert(E->getObjectKind() == OK_Ordinary); 19485 19486 E->setType(DestType); 19487 19488 // Rebuild the sub-expression as the pointee (function) type. 19489 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19490 19491 ExprResult Result = Visit(E->getSubExpr()); 19492 if (!Result.isUsable()) return ExprError(); 19493 19494 E->setSubExpr(Result.get()); 19495 return E; 19496 } else if (E->getCastKind() == CK_LValueToRValue) { 19497 assert(E->isPRValue()); 19498 assert(E->getObjectKind() == OK_Ordinary); 19499 19500 assert(isa<BlockPointerType>(E->getType())); 19501 19502 E->setType(DestType); 19503 19504 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19505 DestType = S.Context.getLValueReferenceType(DestType); 19506 19507 ExprResult Result = Visit(E->getSubExpr()); 19508 if (!Result.isUsable()) return ExprError(); 19509 19510 E->setSubExpr(Result.get()); 19511 return E; 19512 } else { 19513 llvm_unreachable("Unhandled cast type!"); 19514 } 19515 } 19516 19517 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19518 ExprValueKind ValueKind = VK_LValue; 19519 QualType Type = DestType; 19520 19521 // We know how to make this work for certain kinds of decls: 19522 19523 // - functions 19524 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19525 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19526 DestType = Ptr->getPointeeType(); 19527 ExprResult Result = resolveDecl(E, VD); 19528 if (Result.isInvalid()) return ExprError(); 19529 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 19530 VK_PRValue); 19531 } 19532 19533 if (!Type->isFunctionType()) { 19534 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19535 << VD << E->getSourceRange(); 19536 return ExprError(); 19537 } 19538 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19539 // We must match the FunctionDecl's type to the hack introduced in 19540 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19541 // type. See the lengthy commentary in that routine. 19542 QualType FDT = FD->getType(); 19543 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19544 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19545 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19546 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19547 SourceLocation Loc = FD->getLocation(); 19548 FunctionDecl *NewFD = FunctionDecl::Create( 19549 S.Context, FD->getDeclContext(), Loc, Loc, 19550 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19551 SC_None, S.getCurFPFeatures().isFPConstrained(), 19552 false /*isInlineSpecified*/, FD->hasPrototype(), 19553 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19554 19555 if (FD->getQualifier()) 19556 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19557 19558 SmallVector<ParmVarDecl*, 16> Params; 19559 for (const auto &AI : FT->param_types()) { 19560 ParmVarDecl *Param = 19561 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19562 Param->setScopeInfo(0, Params.size()); 19563 Params.push_back(Param); 19564 } 19565 NewFD->setParams(Params); 19566 DRE->setDecl(NewFD); 19567 VD = DRE->getDecl(); 19568 } 19569 } 19570 19571 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19572 if (MD->isInstance()) { 19573 ValueKind = VK_PRValue; 19574 Type = S.Context.BoundMemberTy; 19575 } 19576 19577 // Function references aren't l-values in C. 19578 if (!S.getLangOpts().CPlusPlus) 19579 ValueKind = VK_PRValue; 19580 19581 // - variables 19582 } else if (isa<VarDecl>(VD)) { 19583 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19584 Type = RefTy->getPointeeType(); 19585 } else if (Type->isFunctionType()) { 19586 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19587 << VD << E->getSourceRange(); 19588 return ExprError(); 19589 } 19590 19591 // - nothing else 19592 } else { 19593 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19594 << VD << E->getSourceRange(); 19595 return ExprError(); 19596 } 19597 19598 // Modifying the declaration like this is friendly to IR-gen but 19599 // also really dangerous. 19600 VD->setType(DestType); 19601 E->setType(Type); 19602 E->setValueKind(ValueKind); 19603 return E; 19604 } 19605 19606 /// Check a cast of an unknown-any type. We intentionally only 19607 /// trigger this for C-style casts. 19608 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19609 Expr *CastExpr, CastKind &CastKind, 19610 ExprValueKind &VK, CXXCastPath &Path) { 19611 // The type we're casting to must be either void or complete. 19612 if (!CastType->isVoidType() && 19613 RequireCompleteType(TypeRange.getBegin(), CastType, 19614 diag::err_typecheck_cast_to_incomplete)) 19615 return ExprError(); 19616 19617 // Rewrite the casted expression from scratch. 19618 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19619 if (!result.isUsable()) return ExprError(); 19620 19621 CastExpr = result.get(); 19622 VK = CastExpr->getValueKind(); 19623 CastKind = CK_NoOp; 19624 19625 return CastExpr; 19626 } 19627 19628 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19629 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19630 } 19631 19632 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19633 Expr *arg, QualType ¶mType) { 19634 // If the syntactic form of the argument is not an explicit cast of 19635 // any sort, just do default argument promotion. 19636 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19637 if (!castArg) { 19638 ExprResult result = DefaultArgumentPromotion(arg); 19639 if (result.isInvalid()) return ExprError(); 19640 paramType = result.get()->getType(); 19641 return result; 19642 } 19643 19644 // Otherwise, use the type that was written in the explicit cast. 19645 assert(!arg->hasPlaceholderType()); 19646 paramType = castArg->getTypeAsWritten(); 19647 19648 // Copy-initialize a parameter of that type. 19649 InitializedEntity entity = 19650 InitializedEntity::InitializeParameter(Context, paramType, 19651 /*consumed*/ false); 19652 return PerformCopyInitialization(entity, callLoc, arg); 19653 } 19654 19655 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19656 Expr *orig = E; 19657 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19658 while (true) { 19659 E = E->IgnoreParenImpCasts(); 19660 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19661 E = call->getCallee(); 19662 diagID = diag::err_uncasted_call_of_unknown_any; 19663 } else { 19664 break; 19665 } 19666 } 19667 19668 SourceLocation loc; 19669 NamedDecl *d; 19670 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19671 loc = ref->getLocation(); 19672 d = ref->getDecl(); 19673 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19674 loc = mem->getMemberLoc(); 19675 d = mem->getMemberDecl(); 19676 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19677 diagID = diag::err_uncasted_call_of_unknown_any; 19678 loc = msg->getSelectorStartLoc(); 19679 d = msg->getMethodDecl(); 19680 if (!d) { 19681 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19682 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19683 << orig->getSourceRange(); 19684 return ExprError(); 19685 } 19686 } else { 19687 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19688 << E->getSourceRange(); 19689 return ExprError(); 19690 } 19691 19692 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19693 19694 // Never recoverable. 19695 return ExprError(); 19696 } 19697 19698 /// Check for operands with placeholder types and complain if found. 19699 /// Returns ExprError() if there was an error and no recovery was possible. 19700 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19701 if (!Context.isDependenceAllowed()) { 19702 // C cannot handle TypoExpr nodes on either side of a binop because it 19703 // doesn't handle dependent types properly, so make sure any TypoExprs have 19704 // been dealt with before checking the operands. 19705 ExprResult Result = CorrectDelayedTyposInExpr(E); 19706 if (!Result.isUsable()) return ExprError(); 19707 E = Result.get(); 19708 } 19709 19710 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19711 if (!placeholderType) return E; 19712 19713 switch (placeholderType->getKind()) { 19714 19715 // Overloaded expressions. 19716 case BuiltinType::Overload: { 19717 // Try to resolve a single function template specialization. 19718 // This is obligatory. 19719 ExprResult Result = E; 19720 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19721 return Result; 19722 19723 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19724 // leaves Result unchanged on failure. 19725 Result = E; 19726 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19727 return Result; 19728 19729 // If that failed, try to recover with a call. 19730 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19731 /*complain*/ true); 19732 return Result; 19733 } 19734 19735 // Bound member functions. 19736 case BuiltinType::BoundMember: { 19737 ExprResult result = E; 19738 const Expr *BME = E->IgnoreParens(); 19739 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19740 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19741 if (isa<CXXPseudoDestructorExpr>(BME)) { 19742 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19743 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19744 if (ME->getMemberNameInfo().getName().getNameKind() == 19745 DeclarationName::CXXDestructorName) 19746 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19747 } 19748 tryToRecoverWithCall(result, PD, 19749 /*complain*/ true); 19750 return result; 19751 } 19752 19753 // ARC unbridged casts. 19754 case BuiltinType::ARCUnbridgedCast: { 19755 Expr *realCast = stripARCUnbridgedCast(E); 19756 diagnoseARCUnbridgedCast(realCast); 19757 return realCast; 19758 } 19759 19760 // Expressions of unknown type. 19761 case BuiltinType::UnknownAny: 19762 return diagnoseUnknownAnyExpr(*this, E); 19763 19764 // Pseudo-objects. 19765 case BuiltinType::PseudoObject: 19766 return checkPseudoObjectRValue(E); 19767 19768 case BuiltinType::BuiltinFn: { 19769 // Accept __noop without parens by implicitly converting it to a call expr. 19770 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19771 if (DRE) { 19772 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19773 if (FD->getBuiltinID() == Builtin::BI__noop) { 19774 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19775 CK_BuiltinFnToFnPtr) 19776 .get(); 19777 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19778 VK_PRValue, SourceLocation(), 19779 FPOptionsOverride()); 19780 } 19781 } 19782 19783 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19784 return ExprError(); 19785 } 19786 19787 case BuiltinType::IncompleteMatrixIdx: 19788 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19789 ->getRowIdx() 19790 ->getBeginLoc(), 19791 diag::err_matrix_incomplete_index); 19792 return ExprError(); 19793 19794 // Expressions of unknown type. 19795 case BuiltinType::OMPArraySection: 19796 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19797 return ExprError(); 19798 19799 // Expressions of unknown type. 19800 case BuiltinType::OMPArrayShaping: 19801 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19802 19803 case BuiltinType::OMPIterator: 19804 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19805 19806 // Everything else should be impossible. 19807 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19808 case BuiltinType::Id: 19809 #include "clang/Basic/OpenCLImageTypes.def" 19810 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19811 case BuiltinType::Id: 19812 #include "clang/Basic/OpenCLExtensionTypes.def" 19813 #define SVE_TYPE(Name, Id, SingletonId) \ 19814 case BuiltinType::Id: 19815 #include "clang/Basic/AArch64SVEACLETypes.def" 19816 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19817 case BuiltinType::Id: 19818 #include "clang/Basic/PPCTypes.def" 19819 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19820 #include "clang/Basic/RISCVVTypes.def" 19821 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19822 #define PLACEHOLDER_TYPE(Id, SingletonId) 19823 #include "clang/AST/BuiltinTypes.def" 19824 break; 19825 } 19826 19827 llvm_unreachable("invalid placeholder type!"); 19828 } 19829 19830 bool Sema::CheckCaseExpression(Expr *E) { 19831 if (E->isTypeDependent()) 19832 return true; 19833 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19834 return E->getType()->isIntegralOrEnumerationType(); 19835 return false; 19836 } 19837 19838 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19839 ExprResult 19840 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19841 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19842 "Unknown Objective-C Boolean value!"); 19843 QualType BoolT = Context.ObjCBuiltinBoolTy; 19844 if (!Context.getBOOLDecl()) { 19845 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19846 Sema::LookupOrdinaryName); 19847 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19848 NamedDecl *ND = Result.getFoundDecl(); 19849 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19850 Context.setBOOLDecl(TD); 19851 } 19852 } 19853 if (Context.getBOOLDecl()) 19854 BoolT = Context.getBOOLType(); 19855 return new (Context) 19856 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19857 } 19858 19859 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19860 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19861 SourceLocation RParen) { 19862 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { 19863 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19864 return Spec.getPlatform() == Platform; 19865 }); 19866 // Transcribe the "ios" availability check to "maccatalyst" when compiling 19867 // for "maccatalyst" if "maccatalyst" is not specified. 19868 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { 19869 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19870 return Spec.getPlatform() == "ios"; 19871 }); 19872 } 19873 if (Spec == AvailSpecs.end()) 19874 return None; 19875 return Spec->getVersion(); 19876 }; 19877 19878 VersionTuple Version; 19879 if (auto MaybeVersion = 19880 FindSpecVersion(Context.getTargetInfo().getPlatformName())) 19881 Version = *MaybeVersion; 19882 19883 // The use of `@available` in the enclosing context should be analyzed to 19884 // warn when it's used inappropriately (i.e. not if(@available)). 19885 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 19886 Context->HasPotentialAvailabilityViolations = true; 19887 19888 return new (Context) 19889 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19890 } 19891 19892 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19893 ArrayRef<Expr *> SubExprs, QualType T) { 19894 if (!Context.getLangOpts().RecoveryAST) 19895 return ExprError(); 19896 19897 if (isSFINAEContext()) 19898 return ExprError(); 19899 19900 if (T.isNull() || T->isUndeducedType() || 19901 !Context.getLangOpts().RecoveryASTType) 19902 // We don't know the concrete type, fallback to dependent type. 19903 T = Context.DependentTy; 19904 19905 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19906 } 19907